three.webgpu.nodes.js 958 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452
  1. /**
  2. * @license
  3. * Copyright 2010-2024 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. import { Color, Vector2, Vector3, Vector4, Matrix3, Matrix4, EventDispatcher, MathUtils, ColorManagement, SRGBTransfer, NoToneMapping, StaticDrawUsage, InterleavedBuffer, DynamicDrawUsage, InterleavedBufferAttribute, NoColorSpace, UnsignedIntType, IntType, WebGLCoordinateSystem, BackSide, CubeReflectionMapping, CubeRefractionMapping, WebGPUCoordinateSystem, TangentSpaceNormalMap, ObjectSpaceNormalMap, InstancedInterleavedBuffer, InstancedBufferAttribute, DataArrayTexture, FloatType, FramebufferTexture, LinearMipmapLinearFilter, DepthTexture, Material, NormalBlending, PointsMaterial, LineBasicMaterial, LineDashedMaterial, NoBlending, MeshNormalMaterial, WebGLCubeRenderTarget, BoxGeometry, Mesh, Scene, LinearFilter, CubeCamera, CubeTexture, EquirectangularReflectionMapping, EquirectangularRefractionMapping, AddOperation, MixOperation, MultiplyOperation, MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial, Texture, MeshStandardMaterial, MeshPhysicalMaterial, MeshToonMaterial, MeshMatcapMaterial, SpriteMaterial, ShadowMaterial, Uint32BufferAttribute, Uint16BufferAttribute, DoubleSide, DepthStencilFormat, DepthFormat, UnsignedInt248Type, UnsignedByteType, RenderTarget, Plane, Object3D, HalfFloatType, LinearMipMapLinearFilter, OrthographicCamera, BufferGeometry, Float32BufferAttribute, BufferAttribute, UVMapping, Euler, LinearSRGBColorSpace, LessCompare, VSMShadowMap, RGFormat, BasicShadowMap, SphereGeometry, CubeUVReflectionMapping, PerspectiveCamera, RGBAFormat, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, REVISION, SRGBColorSpace, PCFShadowMap, FrontSide, Frustum, DataTexture, RedIntegerFormat, RedFormat, RGIntegerFormat, RGBIntegerFormat, RGBFormat, RGBAIntegerFormat, UnsignedShortType, ByteType, ShortType, createCanvasElement, AddEquation, SubtractEquation, ReverseSubtractEquation, ZeroFactor, OneFactor, SrcColorFactor, SrcAlphaFactor, SrcAlphaSaturateFactor, DstColorFactor, DstAlphaFactor, OneMinusSrcColorFactor, OneMinusSrcAlphaFactor, OneMinusDstColorFactor, OneMinusDstAlphaFactor, CullFaceNone, CullFaceBack, CullFaceFront, CustomBlending, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt5999Type, AlphaFormat, LuminanceFormat, LuminanceAlphaFormat, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGBA_ETC2_EAC_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_10x10_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_BPTC_Format, RED_RGTC1_Format, SIGNED_RED_RGTC1_Format, RED_GREEN_RGTC2_Format, SIGNED_RED_GREEN_RGTC2_Format, RepeatWrapping, ClampToEdgeWrapping, MirroredRepeatWrapping, NearestFilter, NearestMipmapNearestFilter, NeverCompare, AlwaysCompare, LessEqualCompare, EqualCompare, GreaterEqualCompare, GreaterCompare, NotEqualCompare, warnOnce, NotEqualStencilFunc, GreaterStencilFunc, GreaterEqualStencilFunc, EqualStencilFunc, LessEqualStencilFunc, LessStencilFunc, AlwaysStencilFunc, NeverStencilFunc, DecrementWrapStencilOp, IncrementWrapStencilOp, DecrementStencilOp, IncrementStencilOp, InvertStencilOp, ReplaceStencilOp, ZeroStencilOp, KeepStencilOp, MaxEquation, MinEquation, SpotLight, PointLight, DirectionalLight, RectAreaLight, AmbientLight, HemisphereLight, LightProbe, LinearToneMapping, ReinhardToneMapping, CineonToneMapping, ACESFilmicToneMapping, AgXToneMapping, NeutralToneMapping, Group, Loader, FileLoader, MaterialLoader, ObjectLoader } from './three.core.js';
  7. export { AdditiveAnimationBlendMode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CircleGeometry, Clock, ColorKeyframeTrack, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeTextureLoader, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceFrontBack, Curve, CurvePath, CustomToneMapping, CylinderGeometry, Cylindrical, Data3DTexture, DataTextureLoader, DataUtils, DefaultLoadingManager, DetachedBindMode, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DynamicCopyUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, ExtrudeGeometry, Fog, FogExp2, GLBufferAttribute, GLSL1, GLSL3, GridHelper, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, InstancedBufferGeometry, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, KeyframeTrack, LOD, LatheGeometry, Layers, Light, Line, Line3, LineCurve, LineCurve3, LineLoop, LineSegments, LinearInterpolant, LinearMipMapNearestFilter, LinearTransfer, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, Matrix2, MeshDepthMaterial, MeshDistanceMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NormalAnimationBlendMode, NumberKeyframeTrack, OctahedronGeometry, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, PCFSoftShadowMap, Path, PlaneGeometry, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RingGeometry, ShaderMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, Spherical, SphericalHarmonics3, SplineCurve, SpotLightHelper, Sprite, StaticCopyUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureUtils, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, 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. const typeFromLength = /*@__PURE__*/ new Map( [
  323. [ 1, 'float' ],
  324. [ 2, 'vec2' ],
  325. [ 3, 'vec3' ],
  326. [ 4, 'vec4' ],
  327. [ 9, 'mat3' ],
  328. [ 16, 'mat4' ]
  329. ] );
  330. function getTypeFromLength( length ) {
  331. return typeFromLength.get( length );
  332. }
  333. function getLengthFromType( type ) {
  334. if ( /float|int|uint/.test( type ) ) return 1;
  335. if ( /vec2/.test( type ) ) return 2;
  336. if ( /vec3/.test( type ) ) return 3;
  337. if ( /vec4/.test( type ) ) return 4;
  338. if ( /mat3/.test( type ) ) return 9;
  339. if ( /mat4/.test( type ) ) return 16;
  340. console.error( 'THREE.TSL: Unsupported type:', type );
  341. }
  342. function getValueType( value ) {
  343. if ( value === undefined || value === null ) return null;
  344. const typeOf = typeof value;
  345. if ( value.isNode === true ) {
  346. return 'node';
  347. } else if ( typeOf === 'number' ) {
  348. return 'float';
  349. } else if ( typeOf === 'boolean' ) {
  350. return 'bool';
  351. } else if ( typeOf === 'string' ) {
  352. return 'string';
  353. } else if ( typeOf === 'function' ) {
  354. return 'shader';
  355. } else if ( value.isVector2 === true ) {
  356. return 'vec2';
  357. } else if ( value.isVector3 === true ) {
  358. return 'vec3';
  359. } else if ( value.isVector4 === true ) {
  360. return 'vec4';
  361. } else if ( value.isMatrix3 === true ) {
  362. return 'mat3';
  363. } else if ( value.isMatrix4 === true ) {
  364. return 'mat4';
  365. } else if ( value.isColor === true ) {
  366. return 'color';
  367. } else if ( value instanceof ArrayBuffer ) {
  368. return 'ArrayBuffer';
  369. }
  370. return null;
  371. }
  372. function getValueFromType( type, ...params ) {
  373. const last4 = type ? type.slice( - 4 ) : undefined;
  374. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  375. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  376. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  377. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  378. }
  379. if ( type === 'color' ) {
  380. return new Color( ...params );
  381. } else if ( last4 === 'vec2' ) {
  382. return new Vector2( ...params );
  383. } else if ( last4 === 'vec3' ) {
  384. return new Vector3( ...params );
  385. } else if ( last4 === 'vec4' ) {
  386. return new Vector4( ...params );
  387. } else if ( last4 === 'mat3' ) {
  388. return new Matrix3( ...params );
  389. } else if ( last4 === 'mat4' ) {
  390. return new Matrix4( ...params );
  391. } else if ( type === 'bool' ) {
  392. return params[ 0 ] || false;
  393. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  394. return params[ 0 ] || 0;
  395. } else if ( type === 'string' ) {
  396. return params[ 0 ] || '';
  397. } else if ( type === 'ArrayBuffer' ) {
  398. return base64ToArrayBuffer( params[ 0 ] );
  399. }
  400. return null;
  401. }
  402. function arrayBufferToBase64( arrayBuffer ) {
  403. let chars = '';
  404. const array = new Uint8Array( arrayBuffer );
  405. for ( let i = 0; i < array.length; i ++ ) {
  406. chars += String.fromCharCode( array[ i ] );
  407. }
  408. return btoa( chars );
  409. }
  410. function base64ToArrayBuffer( base64 ) {
  411. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  412. }
  413. var NodeUtils = /*#__PURE__*/Object.freeze({
  414. __proto__: null,
  415. arrayBufferToBase64: arrayBufferToBase64,
  416. base64ToArrayBuffer: base64ToArrayBuffer,
  417. getCacheKey: getCacheKey$1,
  418. getLengthFromType: getLengthFromType,
  419. getNodeChildren: getNodeChildren,
  420. getTypeFromLength: getTypeFromLength,
  421. getValueFromType: getValueFromType,
  422. getValueType: getValueType,
  423. hash: hash$1,
  424. hashArray: hashArray,
  425. hashString: hashString
  426. });
  427. const NodeShaderStage = {
  428. VERTEX: 'vertex',
  429. FRAGMENT: 'fragment'
  430. };
  431. const NodeUpdateType = {
  432. NONE: 'none',
  433. FRAME: 'frame',
  434. RENDER: 'render',
  435. OBJECT: 'object'
  436. };
  437. const NodeType = {
  438. BOOLEAN: 'bool',
  439. INTEGER: 'int',
  440. FLOAT: 'float',
  441. VECTOR2: 'vec2',
  442. VECTOR3: 'vec3',
  443. VECTOR4: 'vec4',
  444. MATRIX2: 'mat2',
  445. MATRIX3: 'mat3',
  446. MATRIX4: 'mat4'
  447. };
  448. const NodeAccess = {
  449. READ_ONLY: 'readOnly',
  450. WRITE_ONLY: 'writeOnly',
  451. READ_WRITE: 'readWrite',
  452. };
  453. const defaultShaderStages = [ 'fragment', 'vertex' ];
  454. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  455. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  456. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  457. let _nodeId = 0;
  458. class Node extends EventDispatcher {
  459. static get type() {
  460. return 'Node';
  461. }
  462. constructor( nodeType = null ) {
  463. super();
  464. this.nodeType = nodeType;
  465. this.updateType = NodeUpdateType.NONE;
  466. this.updateBeforeType = NodeUpdateType.NONE;
  467. this.updateAfterType = NodeUpdateType.NONE;
  468. this.uuid = MathUtils.generateUUID();
  469. this.version = 0;
  470. this._cacheKey = null;
  471. this._cacheKeyVersion = 0;
  472. this.global = false;
  473. this.isNode = true;
  474. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  475. }
  476. set needsUpdate( value ) {
  477. if ( value === true ) {
  478. this.version ++;
  479. }
  480. }
  481. get type() {
  482. return this.constructor.type;
  483. }
  484. onUpdate( callback, updateType ) {
  485. this.updateType = updateType;
  486. this.update = callback.bind( this.getSelf() );
  487. return this;
  488. }
  489. onFrameUpdate( callback ) {
  490. return this.onUpdate( callback, NodeUpdateType.FRAME );
  491. }
  492. onRenderUpdate( callback ) {
  493. return this.onUpdate( callback, NodeUpdateType.RENDER );
  494. }
  495. onObjectUpdate( callback ) {
  496. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  497. }
  498. onReference( callback ) {
  499. this.updateReference = callback.bind( this.getSelf() );
  500. return this;
  501. }
  502. getSelf() {
  503. // Returns non-node object.
  504. return this.self || this;
  505. }
  506. updateReference( /*state*/ ) {
  507. return this;
  508. }
  509. isGlobal( /*builder*/ ) {
  510. return this.global;
  511. }
  512. * getChildren() {
  513. for ( const { childNode } of getNodeChildren( this ) ) {
  514. yield childNode;
  515. }
  516. }
  517. dispose() {
  518. this.dispatchEvent( { type: 'dispose' } );
  519. }
  520. traverse( callback ) {
  521. callback( this );
  522. for ( const childNode of this.getChildren() ) {
  523. childNode.traverse( callback );
  524. }
  525. }
  526. getCacheKey( force = false ) {
  527. force = force || this.version !== this._cacheKeyVersion;
  528. if ( force === true || this._cacheKey === null ) {
  529. this._cacheKey = getCacheKey$1( this, force );
  530. this._cacheKeyVersion = this.version;
  531. }
  532. return this._cacheKey;
  533. }
  534. getScope() {
  535. return this;
  536. }
  537. getHash( /*builder*/ ) {
  538. return this.uuid;
  539. }
  540. getUpdateType() {
  541. return this.updateType;
  542. }
  543. getUpdateBeforeType() {
  544. return this.updateBeforeType;
  545. }
  546. getUpdateAfterType() {
  547. return this.updateAfterType;
  548. }
  549. getElementType( builder ) {
  550. const type = this.getNodeType( builder );
  551. const elementType = builder.getElementType( type );
  552. return elementType;
  553. }
  554. getNodeType( builder ) {
  555. const nodeProperties = builder.getNodeProperties( this );
  556. if ( nodeProperties.outputNode ) {
  557. return nodeProperties.outputNode.getNodeType( builder );
  558. }
  559. return this.nodeType;
  560. }
  561. getShared( builder ) {
  562. const hash = this.getHash( builder );
  563. const nodeFromHash = builder.getNodeFromHash( hash );
  564. return nodeFromHash || this;
  565. }
  566. setup( builder ) {
  567. const nodeProperties = builder.getNodeProperties( this );
  568. let index = 0;
  569. for ( const childNode of this.getChildren() ) {
  570. nodeProperties[ 'node' + index ++ ] = childNode;
  571. }
  572. // return a outputNode if exists
  573. return null;
  574. }
  575. analyze( builder ) {
  576. const usageCount = builder.increaseUsage( this );
  577. if ( usageCount === 1 ) {
  578. // node flow children
  579. const nodeProperties = builder.getNodeProperties( this );
  580. for ( const childNode of Object.values( nodeProperties ) ) {
  581. if ( childNode && childNode.isNode === true ) {
  582. childNode.build( builder );
  583. }
  584. }
  585. }
  586. }
  587. generate( builder, output ) {
  588. const { outputNode } = builder.getNodeProperties( this );
  589. if ( outputNode && outputNode.isNode === true ) {
  590. return outputNode.build( builder, output );
  591. }
  592. }
  593. updateBefore( /*frame*/ ) {
  594. console.warn( 'Abstract function.' );
  595. }
  596. updateAfter( /*frame*/ ) {
  597. console.warn( 'Abstract function.' );
  598. }
  599. update( /*frame*/ ) {
  600. console.warn( 'Abstract function.' );
  601. }
  602. build( builder, output = null ) {
  603. const refNode = this.getShared( builder );
  604. if ( this !== refNode ) {
  605. return refNode.build( builder, output );
  606. }
  607. builder.addNode( this );
  608. builder.addChain( this );
  609. /* Build stages expected results:
  610. - "setup" -> Node
  611. - "analyze" -> null
  612. - "generate" -> String
  613. */
  614. let result = null;
  615. const buildStage = builder.getBuildStage();
  616. if ( buildStage === 'setup' ) {
  617. this.updateReference( builder );
  618. const properties = builder.getNodeProperties( this );
  619. if ( properties.initialized !== true ) {
  620. const stackNodesBeforeSetup = builder.stack.nodes.length;
  621. properties.initialized = true;
  622. properties.outputNode = this.setup( builder );
  623. if ( properties.outputNode !== null && builder.stack.nodes.length !== stackNodesBeforeSetup ) ;
  624. for ( const childNode of Object.values( properties ) ) {
  625. if ( childNode && childNode.isNode === true ) {
  626. childNode.build( builder );
  627. }
  628. }
  629. }
  630. } else if ( buildStage === 'analyze' ) {
  631. this.analyze( builder );
  632. } else if ( buildStage === 'generate' ) {
  633. const isGenerateOnce = this.generate.length === 1;
  634. if ( isGenerateOnce ) {
  635. const type = this.getNodeType( builder );
  636. const nodeData = builder.getDataFromNode( this );
  637. result = nodeData.snippet;
  638. if ( result === undefined ) {
  639. result = this.generate( builder ) || '';
  640. nodeData.snippet = result;
  641. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  642. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  643. }
  644. result = builder.format( result, type, output );
  645. } else {
  646. result = this.generate( builder, output ) || '';
  647. }
  648. }
  649. builder.removeChain( this );
  650. builder.addSequentialNode( this );
  651. return result;
  652. }
  653. getSerializeChildren() {
  654. return getNodeChildren( this );
  655. }
  656. serialize( json ) {
  657. const nodeChildren = this.getSerializeChildren();
  658. const inputNodes = {};
  659. for ( const { property, index, childNode } of nodeChildren ) {
  660. if ( index !== undefined ) {
  661. if ( inputNodes[ property ] === undefined ) {
  662. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  663. }
  664. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  665. } else {
  666. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  667. }
  668. }
  669. if ( Object.keys( inputNodes ).length > 0 ) {
  670. json.inputNodes = inputNodes;
  671. }
  672. }
  673. deserialize( json ) {
  674. if ( json.inputNodes !== undefined ) {
  675. const nodes = json.meta.nodes;
  676. for ( const property in json.inputNodes ) {
  677. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  678. const inputArray = [];
  679. for ( const uuid of json.inputNodes[ property ] ) {
  680. inputArray.push( nodes[ uuid ] );
  681. }
  682. this[ property ] = inputArray;
  683. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  684. const inputObject = {};
  685. for ( const subProperty in json.inputNodes[ property ] ) {
  686. const uuid = json.inputNodes[ property ][ subProperty ];
  687. inputObject[ subProperty ] = nodes[ uuid ];
  688. }
  689. this[ property ] = inputObject;
  690. } else {
  691. const uuid = json.inputNodes[ property ];
  692. this[ property ] = nodes[ uuid ];
  693. }
  694. }
  695. }
  696. }
  697. toJSON( meta ) {
  698. const { uuid, type } = this;
  699. const isRoot = ( meta === undefined || typeof meta === 'string' );
  700. if ( isRoot ) {
  701. meta = {
  702. textures: {},
  703. images: {},
  704. nodes: {}
  705. };
  706. }
  707. // serialize
  708. let data = meta.nodes[ uuid ];
  709. if ( data === undefined ) {
  710. data = {
  711. uuid,
  712. type,
  713. meta,
  714. metadata: {
  715. version: 4.6,
  716. type: 'Node',
  717. generator: 'Node.toJSON'
  718. }
  719. };
  720. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  721. this.serialize( data );
  722. delete data.meta;
  723. }
  724. // TODO: Copied from Object3D.toJSON
  725. function extractFromCache( cache ) {
  726. const values = [];
  727. for ( const key in cache ) {
  728. const data = cache[ key ];
  729. delete data.metadata;
  730. values.push( data );
  731. }
  732. return values;
  733. }
  734. if ( isRoot ) {
  735. const textures = extractFromCache( meta.textures );
  736. const images = extractFromCache( meta.images );
  737. const nodes = extractFromCache( meta.nodes );
  738. if ( textures.length > 0 ) data.textures = textures;
  739. if ( images.length > 0 ) data.images = images;
  740. if ( nodes.length > 0 ) data.nodes = nodes;
  741. }
  742. return data;
  743. }
  744. }
  745. class ArrayElementNode extends Node {
  746. static get type() {
  747. return 'ArrayElementNode';
  748. } // @TODO: If extending from TempNode it breaks webgpu_compute
  749. constructor( node, indexNode ) {
  750. super();
  751. this.node = node;
  752. this.indexNode = indexNode;
  753. this.isArrayElementNode = true;
  754. }
  755. getNodeType( builder ) {
  756. return this.node.getElementType( builder );
  757. }
  758. generate( builder ) {
  759. const nodeSnippet = this.node.build( builder );
  760. const indexSnippet = this.indexNode.build( builder, 'uint' );
  761. return `${nodeSnippet}[ ${indexSnippet} ]`;
  762. }
  763. }
  764. class ConvertNode extends Node {
  765. static get type() {
  766. return 'ConvertNode';
  767. }
  768. constructor( node, convertTo ) {
  769. super();
  770. this.node = node;
  771. this.convertTo = convertTo;
  772. }
  773. getNodeType( builder ) {
  774. const requestType = this.node.getNodeType( builder );
  775. let convertTo = null;
  776. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  777. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  778. convertTo = overloadingType;
  779. }
  780. }
  781. return convertTo;
  782. }
  783. serialize( data ) {
  784. super.serialize( data );
  785. data.convertTo = this.convertTo;
  786. }
  787. deserialize( data ) {
  788. super.deserialize( data );
  789. this.convertTo = data.convertTo;
  790. }
  791. generate( builder, output ) {
  792. const node = this.node;
  793. const type = this.getNodeType( builder );
  794. const snippet = node.build( builder, type );
  795. return builder.format( snippet, type, output );
  796. }
  797. }
  798. class TempNode extends Node {
  799. static get type() {
  800. return 'TempNode';
  801. }
  802. constructor( type ) {
  803. super( type );
  804. this.isTempNode = true;
  805. }
  806. hasDependencies( builder ) {
  807. return builder.getDataFromNode( this ).usageCount > 1;
  808. }
  809. build( builder, output ) {
  810. const buildStage = builder.getBuildStage();
  811. if ( buildStage === 'generate' ) {
  812. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  813. const nodeData = builder.getDataFromNode( this );
  814. if ( nodeData.propertyName !== undefined ) {
  815. return builder.format( nodeData.propertyName, type, output );
  816. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  817. const snippet = super.build( builder, type );
  818. const nodeVar = builder.getVarFromNode( this, null, type );
  819. const propertyName = builder.getPropertyName( nodeVar );
  820. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  821. nodeData.snippet = snippet;
  822. nodeData.propertyName = propertyName;
  823. return builder.format( nodeData.propertyName, type, output );
  824. }
  825. }
  826. return super.build( builder, output );
  827. }
  828. }
  829. class JoinNode extends TempNode {
  830. static get type() {
  831. return 'JoinNode';
  832. }
  833. constructor( nodes = [], nodeType = null ) {
  834. super( nodeType );
  835. this.nodes = nodes;
  836. }
  837. getNodeType( builder ) {
  838. if ( this.nodeType !== null ) {
  839. return builder.getVectorType( this.nodeType );
  840. }
  841. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  842. }
  843. generate( builder, output ) {
  844. const type = this.getNodeType( builder );
  845. const nodes = this.nodes;
  846. const primitiveType = builder.getComponentType( type );
  847. const snippetValues = [];
  848. for ( const input of nodes ) {
  849. let inputSnippet = input.build( builder );
  850. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  851. if ( inputPrimitiveType !== primitiveType ) {
  852. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  853. }
  854. snippetValues.push( inputSnippet );
  855. }
  856. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  857. return builder.format( snippet, type, output );
  858. }
  859. }
  860. const stringVectorComponents = vectorComponents.join( '' );
  861. class SplitNode extends Node {
  862. static get type() {
  863. return 'SplitNode';
  864. }
  865. constructor( node, components = 'x' ) {
  866. super();
  867. this.node = node;
  868. this.components = components;
  869. this.isSplitNode = true;
  870. }
  871. getVectorLength() {
  872. let vectorLength = this.components.length;
  873. for ( const c of this.components ) {
  874. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  875. }
  876. return vectorLength;
  877. }
  878. getComponentType( builder ) {
  879. return builder.getComponentType( this.node.getNodeType( builder ) );
  880. }
  881. getNodeType( builder ) {
  882. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  883. }
  884. generate( builder, output ) {
  885. const node = this.node;
  886. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  887. let snippet = null;
  888. if ( nodeTypeLength > 1 ) {
  889. let type = null;
  890. const componentsLength = this.getVectorLength();
  891. if ( componentsLength >= nodeTypeLength ) {
  892. // needed expand the input node
  893. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  894. }
  895. const nodeSnippet = node.build( builder, type );
  896. if ( this.components.length === nodeTypeLength && this.components === stringVectorComponents.slice( 0, this.components.length ) ) {
  897. // unnecessary swizzle
  898. snippet = builder.format( nodeSnippet, type, output );
  899. } else {
  900. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  901. }
  902. } else {
  903. // ignore .components if .node returns float/integer
  904. snippet = node.build( builder, output );
  905. }
  906. return snippet;
  907. }
  908. serialize( data ) {
  909. super.serialize( data );
  910. data.components = this.components;
  911. }
  912. deserialize( data ) {
  913. super.deserialize( data );
  914. this.components = data.components;
  915. }
  916. }
  917. class SetNode extends TempNode {
  918. static get type() {
  919. return 'SetNode';
  920. }
  921. constructor( sourceNode, components, targetNode ) {
  922. super();
  923. this.sourceNode = sourceNode;
  924. this.components = components;
  925. this.targetNode = targetNode;
  926. }
  927. getNodeType( builder ) {
  928. return this.sourceNode.getNodeType( builder );
  929. }
  930. generate( builder ) {
  931. const { sourceNode, components, targetNode } = this;
  932. const sourceType = this.getNodeType( builder );
  933. const targetType = builder.getTypeFromLength( components.length, targetNode.getNodeType( builder ) );
  934. const targetSnippet = targetNode.build( builder, targetType );
  935. const sourceSnippet = sourceNode.build( builder, sourceType );
  936. const length = builder.getTypeLength( sourceType );
  937. const snippetValues = [];
  938. for ( let i = 0; i < length; i ++ ) {
  939. const component = vectorComponents[ i ];
  940. if ( component === components[ 0 ] ) {
  941. snippetValues.push( targetSnippet );
  942. i += components.length - 1;
  943. } else {
  944. snippetValues.push( sourceSnippet + '.' + component );
  945. }
  946. }
  947. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  948. }
  949. }
  950. class FlipNode extends TempNode {
  951. static get type() {
  952. return 'FlipNode';
  953. }
  954. constructor( sourceNode, components ) {
  955. super();
  956. this.sourceNode = sourceNode;
  957. this.components = components;
  958. }
  959. getNodeType( builder ) {
  960. return this.sourceNode.getNodeType( builder );
  961. }
  962. generate( builder ) {
  963. const { components, sourceNode } = this;
  964. const sourceType = this.getNodeType( builder );
  965. const sourceSnippet = sourceNode.build( builder );
  966. const sourceCache = builder.getVarFromNode( this );
  967. const sourceProperty = builder.getPropertyName( sourceCache );
  968. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  969. const length = builder.getTypeLength( sourceType );
  970. const snippetValues = [];
  971. let componentIndex = 0;
  972. for ( let i = 0; i < length; i ++ ) {
  973. const component = vectorComponents[ i ];
  974. if ( component === components[ componentIndex ] ) {
  975. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  976. componentIndex ++;
  977. } else {
  978. snippetValues.push( sourceProperty + '.' + component );
  979. }
  980. }
  981. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  982. }
  983. }
  984. class InputNode extends Node {
  985. static get type() {
  986. return 'InputNode';
  987. }
  988. constructor( value, nodeType = null ) {
  989. super( nodeType );
  990. this.isInputNode = true;
  991. this.value = value;
  992. this.precision = null;
  993. }
  994. getNodeType( /*builder*/ ) {
  995. if ( this.nodeType === null ) {
  996. return getValueType( this.value );
  997. }
  998. return this.nodeType;
  999. }
  1000. getInputType( builder ) {
  1001. return this.getNodeType( builder );
  1002. }
  1003. setPrecision( precision ) {
  1004. this.precision = precision;
  1005. return this;
  1006. }
  1007. serialize( data ) {
  1008. super.serialize( data );
  1009. data.value = this.value;
  1010. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  1011. data.valueType = getValueType( this.value );
  1012. data.nodeType = this.nodeType;
  1013. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  1014. data.precision = this.precision;
  1015. }
  1016. deserialize( data ) {
  1017. super.deserialize( data );
  1018. this.nodeType = data.nodeType;
  1019. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  1020. this.precision = data.precision || null;
  1021. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  1022. }
  1023. generate( /*builder, output*/ ) {
  1024. console.warn( 'Abstract function.' );
  1025. }
  1026. }
  1027. class ConstNode extends InputNode {
  1028. static get type() {
  1029. return 'ConstNode';
  1030. }
  1031. constructor( value, nodeType = null ) {
  1032. super( value, nodeType );
  1033. this.isConstNode = true;
  1034. }
  1035. generateConst( builder ) {
  1036. return builder.generateConst( this.getNodeType( builder ), this.value );
  1037. }
  1038. generate( builder, output ) {
  1039. const type = this.getNodeType( builder );
  1040. return builder.format( this.generateConst( builder ), type, output );
  1041. }
  1042. }
  1043. //
  1044. let currentStack = null;
  1045. const NodeElements = new Map();
  1046. function addMethodChaining( name, nodeElement ) {
  1047. if ( NodeElements.has( name ) ) {
  1048. console.warn( `Redefinition of method chaining ${ name }` );
  1049. return;
  1050. }
  1051. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  1052. NodeElements.set( name, nodeElement );
  1053. }
  1054. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  1055. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  1056. const shaderNodeHandler = {
  1057. setup( NodeClosure, params ) {
  1058. const inputs = params.shift();
  1059. return NodeClosure( nodeObjects( inputs ), ...params );
  1060. },
  1061. get( node, prop, nodeObj ) {
  1062. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1063. if ( node.isStackNode !== true && prop === 'assign' ) {
  1064. return ( ...params ) => {
  1065. currentStack.assign( nodeObj, ...params );
  1066. return nodeObj;
  1067. };
  1068. } else if ( NodeElements.has( prop ) ) {
  1069. const nodeElement = NodeElements.get( prop );
  1070. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  1071. } else if ( prop === 'self' ) {
  1072. return node;
  1073. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  1074. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  1075. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  1076. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  1077. // accessing properties ( swizzle )
  1078. prop = parseSwizzle( prop );
  1079. return nodeObject( new SplitNode( nodeObj, prop ) );
  1080. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1081. // set properties ( swizzle ) and sort to xyzw sequence
  1082. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  1083. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  1084. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1085. // set properties ( swizzle ) and sort to xyzw sequence
  1086. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  1087. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  1088. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  1089. // accessing property
  1090. if ( prop === 'width' ) prop = 'x';
  1091. else if ( prop === 'height' ) prop = 'y';
  1092. else if ( prop === 'depth' ) prop = 'z';
  1093. return nodeObject( new SplitNode( node, prop ) );
  1094. } else if ( /^\d+$/.test( prop ) === true ) {
  1095. // accessing array
  1096. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  1097. }
  1098. }
  1099. return Reflect.get( node, prop, nodeObj );
  1100. },
  1101. set( node, prop, value, nodeObj ) {
  1102. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1103. // setting properties
  1104. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  1105. nodeObj[ prop ].assign( value );
  1106. return true;
  1107. }
  1108. }
  1109. return Reflect.set( node, prop, value, nodeObj );
  1110. }
  1111. };
  1112. const nodeObjectsCacheMap = new WeakMap();
  1113. const nodeBuilderFunctionsCacheMap = new WeakMap();
  1114. const ShaderNodeObject = function ( obj, altType = null ) {
  1115. const type = getValueType( obj );
  1116. if ( type === 'node' ) {
  1117. let nodeObject = nodeObjectsCacheMap.get( obj );
  1118. if ( nodeObject === undefined ) {
  1119. nodeObject = new Proxy( obj, shaderNodeHandler );
  1120. nodeObjectsCacheMap.set( obj, nodeObject );
  1121. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  1122. }
  1123. return nodeObject;
  1124. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  1125. return nodeObject( getConstNode( obj, altType ) );
  1126. } else if ( type === 'shader' ) {
  1127. return Fn( obj );
  1128. }
  1129. return obj;
  1130. };
  1131. const ShaderNodeObjects = function ( objects, altType = null ) {
  1132. for ( const name in objects ) {
  1133. objects[ name ] = nodeObject( objects[ name ], altType );
  1134. }
  1135. return objects;
  1136. };
  1137. const ShaderNodeArray = function ( array, altType = null ) {
  1138. const len = array.length;
  1139. for ( let i = 0; i < len; i ++ ) {
  1140. array[ i ] = nodeObject( array[ i ], altType );
  1141. }
  1142. return array;
  1143. };
  1144. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  1145. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  1146. if ( scope === null ) {
  1147. return ( ...params ) => {
  1148. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  1149. };
  1150. } else if ( factor !== null ) {
  1151. factor = nodeObject( factor );
  1152. return ( ...params ) => {
  1153. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  1154. };
  1155. } else {
  1156. return ( ...params ) => {
  1157. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  1158. };
  1159. }
  1160. };
  1161. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  1162. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  1163. };
  1164. class ShaderCallNodeInternal extends Node {
  1165. constructor( shaderNode, inputNodes ) {
  1166. super();
  1167. this.shaderNode = shaderNode;
  1168. this.inputNodes = inputNodes;
  1169. }
  1170. getNodeType( builder ) {
  1171. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  1172. }
  1173. call( builder ) {
  1174. const { shaderNode, inputNodes } = this;
  1175. const properties = builder.getNodeProperties( shaderNode );
  1176. if ( properties.onceOutput ) return properties.onceOutput;
  1177. //
  1178. let result = null;
  1179. if ( shaderNode.layout ) {
  1180. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  1181. if ( functionNodesCacheMap === undefined ) {
  1182. functionNodesCacheMap = new WeakMap();
  1183. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  1184. }
  1185. let functionNode = functionNodesCacheMap.get( shaderNode );
  1186. if ( functionNode === undefined ) {
  1187. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  1188. functionNodesCacheMap.set( shaderNode, functionNode );
  1189. }
  1190. if ( builder.currentFunctionNode !== null ) {
  1191. builder.currentFunctionNode.includes.push( functionNode );
  1192. }
  1193. result = nodeObject( functionNode.call( inputNodes ) );
  1194. } else {
  1195. const jsFunc = shaderNode.jsFunc;
  1196. const outputNode = inputNodes !== null ? jsFunc( inputNodes, builder ) : jsFunc( builder );
  1197. result = nodeObject( outputNode );
  1198. }
  1199. if ( shaderNode.once ) {
  1200. properties.onceOutput = result;
  1201. }
  1202. return result;
  1203. }
  1204. getOutputNode( builder ) {
  1205. const properties = builder.getNodeProperties( this );
  1206. if ( properties.outputNode === null ) {
  1207. properties.outputNode = this.setupOutput( builder );
  1208. }
  1209. return properties.outputNode;
  1210. }
  1211. setup( builder ) {
  1212. return this.getOutputNode( builder );
  1213. }
  1214. setupOutput( builder ) {
  1215. builder.addStack();
  1216. builder.stack.outputNode = this.call( builder );
  1217. return builder.removeStack();
  1218. }
  1219. generate( builder, output ) {
  1220. const outputNode = this.getOutputNode( builder );
  1221. return outputNode.build( builder, output );
  1222. }
  1223. }
  1224. class ShaderNodeInternal extends Node {
  1225. constructor( jsFunc, nodeType ) {
  1226. super( nodeType );
  1227. this.jsFunc = jsFunc;
  1228. this.layout = null;
  1229. this.global = true;
  1230. this.once = false;
  1231. }
  1232. setLayout( layout ) {
  1233. this.layout = layout;
  1234. return this;
  1235. }
  1236. call( inputs = null ) {
  1237. nodeObjects( inputs );
  1238. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  1239. }
  1240. setup() {
  1241. return this.call();
  1242. }
  1243. }
  1244. const bools = [ false, true ];
  1245. const uints = [ 0, 1, 2, 3 ];
  1246. const ints = [ - 1, - 2 ];
  1247. 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 ];
  1248. const boolsCacheMap = new Map();
  1249. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  1250. const uintsCacheMap = new Map();
  1251. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  1252. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  1253. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  1254. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  1255. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  1256. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  1257. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  1258. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  1259. const getConstNode = ( value, type ) => {
  1260. if ( constNodesCacheMap.has( value ) ) {
  1261. return constNodesCacheMap.get( value );
  1262. } else if ( value.isNode === true ) {
  1263. return value;
  1264. } else {
  1265. return new ConstNode( value, type );
  1266. }
  1267. };
  1268. const safeGetNodeType = ( node ) => {
  1269. try {
  1270. return node.getNodeType();
  1271. } catch ( _ ) {
  1272. return undefined;
  1273. }
  1274. };
  1275. const ConvertType = function ( type, cacheMap = null ) {
  1276. return ( ...params ) => {
  1277. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  1278. params = [ getValueFromType( type, ...params ) ];
  1279. }
  1280. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  1281. return nodeObject( cacheMap.get( params[ 0 ] ) );
  1282. }
  1283. if ( params.length === 1 ) {
  1284. const node = getConstNode( params[ 0 ], type );
  1285. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  1286. return nodeObject( new ConvertNode( node, type ) );
  1287. }
  1288. const nodes = params.map( param => getConstNode( param ) );
  1289. return nodeObject( new JoinNode( nodes, type ) );
  1290. };
  1291. };
  1292. // exports
  1293. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  1294. // utils
  1295. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  1296. // shader node base
  1297. function ShaderNode( jsFunc, nodeType ) {
  1298. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  1299. }
  1300. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  1301. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  1302. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  1303. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  1304. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  1305. const Fn = ( jsFunc, nodeType ) => {
  1306. const shaderNode = new ShaderNode( jsFunc, nodeType );
  1307. const fn = ( ...params ) => {
  1308. let inputs;
  1309. nodeObjects( params );
  1310. if ( params[ 0 ] && params[ 0 ].isNode ) {
  1311. inputs = [ ...params ];
  1312. } else {
  1313. inputs = params[ 0 ];
  1314. }
  1315. return shaderNode.call( inputs );
  1316. };
  1317. fn.shaderNode = shaderNode;
  1318. fn.setLayout = ( layout ) => {
  1319. shaderNode.setLayout( layout );
  1320. return fn;
  1321. };
  1322. fn.once = () => {
  1323. shaderNode.once = true;
  1324. return fn;
  1325. };
  1326. return fn;
  1327. };
  1328. const tslFn = ( ...params ) => { // @deprecated, r168
  1329. console.warn( 'TSL.ShaderNode: tslFn() has been renamed to Fn().' );
  1330. return Fn( ...params );
  1331. };
  1332. //
  1333. addMethodChaining( 'toGlobal', ( node ) => {
  1334. node.global = true;
  1335. return node;
  1336. } );
  1337. //
  1338. const setCurrentStack = ( stack ) => {
  1339. currentStack = stack;
  1340. };
  1341. const getCurrentStack = () => currentStack;
  1342. const If = ( ...params ) => currentStack.If( ...params );
  1343. function append( node ) {
  1344. if ( currentStack ) currentStack.add( node );
  1345. return node;
  1346. }
  1347. addMethodChaining( 'append', append );
  1348. // types
  1349. const color = new ConvertType( 'color' );
  1350. const float = new ConvertType( 'float', cacheMaps.float );
  1351. const int = new ConvertType( 'int', cacheMaps.ints );
  1352. const uint = new ConvertType( 'uint', cacheMaps.uint );
  1353. const bool = new ConvertType( 'bool', cacheMaps.bool );
  1354. const vec2 = new ConvertType( 'vec2' );
  1355. const ivec2 = new ConvertType( 'ivec2' );
  1356. const uvec2 = new ConvertType( 'uvec2' );
  1357. const bvec2 = new ConvertType( 'bvec2' );
  1358. const vec3 = new ConvertType( 'vec3' );
  1359. const ivec3 = new ConvertType( 'ivec3' );
  1360. const uvec3 = new ConvertType( 'uvec3' );
  1361. const bvec3 = new ConvertType( 'bvec3' );
  1362. const vec4 = new ConvertType( 'vec4' );
  1363. const ivec4 = new ConvertType( 'ivec4' );
  1364. const uvec4 = new ConvertType( 'uvec4' );
  1365. const bvec4 = new ConvertType( 'bvec4' );
  1366. const mat2 = new ConvertType( 'mat2' );
  1367. const mat3 = new ConvertType( 'mat3' );
  1368. const mat4 = new ConvertType( 'mat4' );
  1369. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  1370. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  1371. addMethodChaining( 'toColor', color );
  1372. addMethodChaining( 'toFloat', float );
  1373. addMethodChaining( 'toInt', int );
  1374. addMethodChaining( 'toUint', uint );
  1375. addMethodChaining( 'toBool', bool );
  1376. addMethodChaining( 'toVec2', vec2 );
  1377. addMethodChaining( 'toIVec2', ivec2 );
  1378. addMethodChaining( 'toUVec2', uvec2 );
  1379. addMethodChaining( 'toBVec2', bvec2 );
  1380. addMethodChaining( 'toVec3', vec3 );
  1381. addMethodChaining( 'toIVec3', ivec3 );
  1382. addMethodChaining( 'toUVec3', uvec3 );
  1383. addMethodChaining( 'toBVec3', bvec3 );
  1384. addMethodChaining( 'toVec4', vec4 );
  1385. addMethodChaining( 'toIVec4', ivec4 );
  1386. addMethodChaining( 'toUVec4', uvec4 );
  1387. addMethodChaining( 'toBVec4', bvec4 );
  1388. addMethodChaining( 'toMat2', mat2 );
  1389. addMethodChaining( 'toMat3', mat3 );
  1390. addMethodChaining( 'toMat4', mat4 );
  1391. // basic nodes
  1392. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode );
  1393. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  1394. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  1395. addMethodChaining( 'element', element );
  1396. addMethodChaining( 'convert', convert );
  1397. class UniformGroupNode extends Node {
  1398. static get type() {
  1399. return 'UniformGroupNode';
  1400. }
  1401. constructor( name, shared = false, order = 1 ) {
  1402. super( 'string' );
  1403. this.name = name;
  1404. this.version = 0;
  1405. this.shared = shared;
  1406. this.order = order;
  1407. this.isUniformGroup = true;
  1408. }
  1409. set needsUpdate( value ) {
  1410. if ( value === true ) this.version ++;
  1411. }
  1412. serialize( data ) {
  1413. super.serialize( data );
  1414. data.name = this.name;
  1415. data.version = this.version;
  1416. data.shared = this.shared;
  1417. }
  1418. deserialize( data ) {
  1419. super.deserialize( data );
  1420. this.name = data.name;
  1421. this.version = data.version;
  1422. this.shared = data.shared;
  1423. }
  1424. }
  1425. const uniformGroup = ( name ) => new UniformGroupNode( name );
  1426. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  1427. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  1428. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  1429. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  1430. class UniformNode extends InputNode {
  1431. static get type() {
  1432. return 'UniformNode';
  1433. }
  1434. constructor( value, nodeType = null ) {
  1435. super( value, nodeType );
  1436. this.isUniformNode = true;
  1437. this.name = '';
  1438. this.groupNode = objectGroup;
  1439. }
  1440. label( name ) {
  1441. this.name = name;
  1442. return this;
  1443. }
  1444. setGroup( group ) {
  1445. this.groupNode = group;
  1446. return this;
  1447. }
  1448. getGroup() {
  1449. return this.groupNode;
  1450. }
  1451. getUniformHash( builder ) {
  1452. return this.getHash( builder );
  1453. }
  1454. onUpdate( callback, updateType ) {
  1455. const self = this.getSelf();
  1456. callback = callback.bind( self );
  1457. return super.onUpdate( ( frame ) => {
  1458. const value = callback( frame, self );
  1459. if ( value !== undefined ) {
  1460. this.value = value;
  1461. }
  1462. }, updateType );
  1463. }
  1464. generate( builder, output ) {
  1465. const type = this.getNodeType( builder );
  1466. const hash = this.getUniformHash( builder );
  1467. let sharedNode = builder.getNodeFromHash( hash );
  1468. if ( sharedNode === undefined ) {
  1469. builder.setHashNode( this, hash );
  1470. sharedNode = this;
  1471. }
  1472. const sharedNodeType = sharedNode.getInputType( builder );
  1473. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  1474. const propertyName = builder.getPropertyName( nodeUniform );
  1475. if ( builder.context.label !== undefined ) delete builder.context.label;
  1476. return builder.format( propertyName, type, output );
  1477. }
  1478. }
  1479. const uniform = ( arg1, arg2 ) => {
  1480. const nodeType = getConstNodeType( arg2 || arg1 );
  1481. // @TODO: get ConstNode from .traverse() in the future
  1482. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  1483. return nodeObject( new UniformNode( value, nodeType ) );
  1484. };
  1485. class PropertyNode extends Node {
  1486. static get type() {
  1487. return 'PropertyNode';
  1488. }
  1489. constructor( nodeType, name = null, varying = false ) {
  1490. super( nodeType );
  1491. this.name = name;
  1492. this.varying = varying;
  1493. this.isPropertyNode = true;
  1494. }
  1495. getHash( builder ) {
  1496. return this.name || super.getHash( builder );
  1497. }
  1498. isGlobal( /*builder*/ ) {
  1499. return true;
  1500. }
  1501. generate( builder ) {
  1502. let nodeVar;
  1503. if ( this.varying === true ) {
  1504. nodeVar = builder.getVaryingFromNode( this, this.name );
  1505. nodeVar.needsInterpolation = true;
  1506. } else {
  1507. nodeVar = builder.getVarFromNode( this, this.name );
  1508. }
  1509. return builder.getPropertyName( nodeVar );
  1510. }
  1511. }
  1512. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  1513. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  1514. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  1515. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  1516. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  1517. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  1518. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  1519. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  1520. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  1521. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  1522. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  1523. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  1524. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  1525. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  1526. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  1527. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  1528. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  1529. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  1530. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  1531. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  1532. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  1533. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  1534. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  1535. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  1536. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  1537. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  1538. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  1539. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  1540. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  1541. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  1542. class AssignNode extends TempNode {
  1543. static get type() {
  1544. return 'AssignNode';
  1545. }
  1546. constructor( targetNode, sourceNode ) {
  1547. super();
  1548. this.targetNode = targetNode;
  1549. this.sourceNode = sourceNode;
  1550. }
  1551. hasDependencies() {
  1552. return false;
  1553. }
  1554. getNodeType( builder, output ) {
  1555. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  1556. }
  1557. needsSplitAssign( builder ) {
  1558. const { targetNode } = this;
  1559. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  1560. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  1561. const assignDiferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  1562. return assignDiferentVector;
  1563. }
  1564. return false;
  1565. }
  1566. generate( builder, output ) {
  1567. const { targetNode, sourceNode } = this;
  1568. const needsSplitAssign = this.needsSplitAssign( builder );
  1569. const targetType = targetNode.getNodeType( builder );
  1570. const target = targetNode.context( { assign: true } ).build( builder );
  1571. const source = sourceNode.build( builder, targetType );
  1572. const sourceType = sourceNode.getNodeType( builder );
  1573. const nodeData = builder.getDataFromNode( this );
  1574. //
  1575. let snippet;
  1576. if ( nodeData.initialized === true ) {
  1577. if ( output !== 'void' ) {
  1578. snippet = target;
  1579. }
  1580. } else if ( needsSplitAssign ) {
  1581. const sourceVar = builder.getVarFromNode( this, null, targetType );
  1582. const sourceProperty = builder.getPropertyName( sourceVar );
  1583. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  1584. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  1585. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  1586. const component = targetNode.components[ i ];
  1587. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  1588. }
  1589. if ( output !== 'void' ) {
  1590. snippet = target;
  1591. }
  1592. } else {
  1593. snippet = `${ target } = ${ source }`;
  1594. if ( output === 'void' || sourceType === 'void' ) {
  1595. builder.addLineFlowCode( snippet, this );
  1596. if ( output !== 'void' ) {
  1597. snippet = target;
  1598. }
  1599. }
  1600. }
  1601. nodeData.initialized = true;
  1602. return builder.format( snippet, targetType, output );
  1603. }
  1604. }
  1605. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  1606. addMethodChaining( 'assign', assign );
  1607. class FunctionCallNode extends TempNode {
  1608. static get type() {
  1609. return 'FunctionCallNode';
  1610. }
  1611. constructor( functionNode = null, parameters = {} ) {
  1612. super();
  1613. this.functionNode = functionNode;
  1614. this.parameters = parameters;
  1615. }
  1616. setParameters( parameters ) {
  1617. this.parameters = parameters;
  1618. return this;
  1619. }
  1620. getParameters() {
  1621. return this.parameters;
  1622. }
  1623. getNodeType( builder ) {
  1624. return this.functionNode.getNodeType( builder );
  1625. }
  1626. generate( builder ) {
  1627. const params = [];
  1628. const functionNode = this.functionNode;
  1629. const inputs = functionNode.getInputs( builder );
  1630. const parameters = this.parameters;
  1631. const generateInput = ( node, inputNode ) => {
  1632. const type = inputNode.type;
  1633. const pointer = type === 'pointer';
  1634. let output;
  1635. if ( pointer ) output = '&' + node.build( builder );
  1636. else output = node.build( builder, type );
  1637. return output;
  1638. };
  1639. if ( Array.isArray( parameters ) ) {
  1640. for ( let i = 0; i < parameters.length; i ++ ) {
  1641. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  1642. }
  1643. } else {
  1644. for ( const inputNode of inputs ) {
  1645. const node = parameters[ inputNode.name ];
  1646. if ( node !== undefined ) {
  1647. params.push( generateInput( node, inputNode ) );
  1648. } else {
  1649. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  1650. }
  1651. }
  1652. }
  1653. const functionName = functionNode.build( builder, 'property' );
  1654. return `${functionName}( ${params.join( ', ' )} )`;
  1655. }
  1656. }
  1657. const call = ( func, ...params ) => {
  1658. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  1659. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  1660. };
  1661. addMethodChaining( 'call', call );
  1662. class OperatorNode extends TempNode {
  1663. static get type() {
  1664. return 'OperatorNode';
  1665. }
  1666. constructor( op, aNode, bNode, ...params ) {
  1667. super();
  1668. if ( params.length > 0 ) {
  1669. let finalOp = new OperatorNode( op, aNode, bNode );
  1670. for ( let i = 0; i < params.length - 1; i ++ ) {
  1671. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  1672. }
  1673. aNode = finalOp;
  1674. bNode = params[ params.length - 1 ];
  1675. }
  1676. this.op = op;
  1677. this.aNode = aNode;
  1678. this.bNode = bNode;
  1679. }
  1680. getNodeType( builder, output ) {
  1681. const op = this.op;
  1682. const aNode = this.aNode;
  1683. const bNode = this.bNode;
  1684. const typeA = aNode.getNodeType( builder );
  1685. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  1686. if ( typeA === 'void' || typeB === 'void' ) {
  1687. return 'void';
  1688. } else if ( op === '%' ) {
  1689. return typeA;
  1690. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  1691. return builder.getIntegerType( typeA );
  1692. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  1693. return 'bool';
  1694. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  1695. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  1696. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  1697. } else {
  1698. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  1699. return typeB;
  1700. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  1701. // matrix x vector
  1702. return builder.getVectorFromMatrix( typeA );
  1703. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  1704. // vector x matrix
  1705. return builder.getVectorFromMatrix( typeB );
  1706. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  1707. // anytype x anytype: use the greater length vector
  1708. return typeB;
  1709. }
  1710. return typeA;
  1711. }
  1712. }
  1713. generate( builder, output ) {
  1714. const op = this.op;
  1715. const aNode = this.aNode;
  1716. const bNode = this.bNode;
  1717. const type = this.getNodeType( builder, output );
  1718. let typeA = null;
  1719. let typeB = null;
  1720. if ( type !== 'void' ) {
  1721. typeA = aNode.getNodeType( builder );
  1722. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  1723. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  1724. if ( builder.isVector( typeA ) ) {
  1725. typeB = typeA;
  1726. } else if ( typeA !== typeB ) {
  1727. typeA = typeB = 'float';
  1728. }
  1729. } else if ( op === '>>' || op === '<<' ) {
  1730. typeA = type;
  1731. typeB = builder.changeComponentType( typeB, 'uint' );
  1732. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  1733. // matrix x vector
  1734. typeB = builder.getVectorFromMatrix( typeA );
  1735. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  1736. // vector x matrix
  1737. typeA = builder.getVectorFromMatrix( typeB );
  1738. } else {
  1739. // anytype x anytype
  1740. typeA = typeB = type;
  1741. }
  1742. } else {
  1743. typeA = typeB = type;
  1744. }
  1745. const a = aNode.build( builder, typeA );
  1746. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  1747. const outputLength = builder.getTypeLength( output );
  1748. const fnOpSnippet = builder.getFunctionOperator( op );
  1749. if ( output !== 'void' ) {
  1750. if ( op === '<' && outputLength > 1 ) {
  1751. if ( builder.useComparisonMethod ) {
  1752. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  1753. } else {
  1754. return builder.format( `( ${ a } < ${ b } )`, type, output );
  1755. }
  1756. } else if ( op === '<=' && outputLength > 1 ) {
  1757. if ( builder.useComparisonMethod ) {
  1758. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  1759. } else {
  1760. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  1761. }
  1762. } else if ( op === '>' && outputLength > 1 ) {
  1763. if ( builder.useComparisonMethod ) {
  1764. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  1765. } else {
  1766. return builder.format( `( ${ a } > ${ b } )`, type, output );
  1767. }
  1768. } else if ( op === '>=' && outputLength > 1 ) {
  1769. if ( builder.useComparisonMethod ) {
  1770. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  1771. } else {
  1772. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  1773. }
  1774. } else if ( op === '!' || op === '~' ) {
  1775. return builder.format( `(${op}${a})`, typeA, output );
  1776. } else if ( fnOpSnippet ) {
  1777. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  1778. } else {
  1779. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  1780. }
  1781. } else if ( typeA !== 'void' ) {
  1782. if ( fnOpSnippet ) {
  1783. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  1784. } else {
  1785. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  1786. }
  1787. }
  1788. }
  1789. serialize( data ) {
  1790. super.serialize( data );
  1791. data.op = this.op;
  1792. }
  1793. deserialize( data ) {
  1794. super.deserialize( data );
  1795. this.op = data.op;
  1796. }
  1797. }
  1798. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  1799. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  1800. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  1801. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  1802. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  1803. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  1804. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  1805. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  1806. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  1807. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  1808. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  1809. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  1810. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  1811. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  1812. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  1813. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  1814. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  1815. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  1816. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  1817. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  1818. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  1819. addMethodChaining( 'add', add );
  1820. addMethodChaining( 'sub', sub );
  1821. addMethodChaining( 'mul', mul );
  1822. addMethodChaining( 'div', div );
  1823. addMethodChaining( 'modInt', modInt );
  1824. addMethodChaining( 'equal', equal );
  1825. addMethodChaining( 'notEqual', notEqual );
  1826. addMethodChaining( 'lessThan', lessThan );
  1827. addMethodChaining( 'greaterThan', greaterThan );
  1828. addMethodChaining( 'lessThanEqual', lessThanEqual );
  1829. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  1830. addMethodChaining( 'and', and );
  1831. addMethodChaining( 'or', or );
  1832. addMethodChaining( 'not', not );
  1833. addMethodChaining( 'xor', xor );
  1834. addMethodChaining( 'bitAnd', bitAnd );
  1835. addMethodChaining( 'bitNot', bitNot );
  1836. addMethodChaining( 'bitOr', bitOr );
  1837. addMethodChaining( 'bitXor', bitXor );
  1838. addMethodChaining( 'shiftLeft', shiftLeft );
  1839. addMethodChaining( 'shiftRight', shiftRight );
  1840. const remainder = ( ...params ) => { // @deprecated, r168
  1841. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  1842. return modInt( ...params );
  1843. };
  1844. addMethodChaining( 'remainder', remainder );
  1845. class MathNode extends TempNode {
  1846. static get type() {
  1847. return 'MathNode';
  1848. }
  1849. constructor( method, aNode, bNode = null, cNode = null ) {
  1850. super();
  1851. this.method = method;
  1852. this.aNode = aNode;
  1853. this.bNode = bNode;
  1854. this.cNode = cNode;
  1855. }
  1856. getInputType( builder ) {
  1857. const aType = this.aNode.getNodeType( builder );
  1858. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  1859. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  1860. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  1861. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  1862. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  1863. if ( aLen > bLen && aLen > cLen ) {
  1864. return aType;
  1865. } else if ( bLen > cLen ) {
  1866. return bType;
  1867. } else if ( cLen > aLen ) {
  1868. return cType;
  1869. }
  1870. return aType;
  1871. }
  1872. getNodeType( builder ) {
  1873. const method = this.method;
  1874. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  1875. return 'float';
  1876. } else if ( method === MathNode.CROSS ) {
  1877. return 'vec3';
  1878. } else if ( method === MathNode.ALL ) {
  1879. return 'bool';
  1880. } else if ( method === MathNode.EQUALS ) {
  1881. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  1882. } else if ( method === MathNode.MOD ) {
  1883. return this.aNode.getNodeType( builder );
  1884. } else {
  1885. return this.getInputType( builder );
  1886. }
  1887. }
  1888. generate( builder, output ) {
  1889. const method = this.method;
  1890. const type = this.getNodeType( builder );
  1891. const inputType = this.getInputType( builder );
  1892. const a = this.aNode;
  1893. const b = this.bNode;
  1894. const c = this.cNode;
  1895. const isWebGL = builder.renderer.isWebGLRenderer === true;
  1896. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  1897. // dir can be either a direction vector or a normal vector
  1898. // upper-left 3x3 of matrix is assumed to be orthogonal
  1899. let tA = a;
  1900. let tB = b;
  1901. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  1902. tB = vec4( vec3( tB ), 0.0 );
  1903. } else {
  1904. tA = vec4( vec3( tA ), 0.0 );
  1905. }
  1906. const mulNode = mul( tA, tB ).xyz;
  1907. return normalize( mulNode ).build( builder, output );
  1908. } else if ( method === MathNode.NEGATE ) {
  1909. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  1910. } else if ( method === MathNode.ONE_MINUS ) {
  1911. return sub( 1.0, a ).build( builder, output );
  1912. } else if ( method === MathNode.RECIPROCAL ) {
  1913. return div( 1.0, a ).build( builder, output );
  1914. } else if ( method === MathNode.DIFFERENCE ) {
  1915. return abs( sub( a, b ) ).build( builder, output );
  1916. } else {
  1917. const params = [];
  1918. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  1919. params.push(
  1920. a.build( builder, type ),
  1921. b.build( builder, type )
  1922. );
  1923. } else if ( isWebGL && method === MathNode.STEP ) {
  1924. params.push(
  1925. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  1926. b.build( builder, inputType )
  1927. );
  1928. } else if ( ( isWebGL && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  1929. params.push(
  1930. a.build( builder, inputType ),
  1931. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  1932. );
  1933. } else if ( method === MathNode.REFRACT ) {
  1934. params.push(
  1935. a.build( builder, inputType ),
  1936. b.build( builder, inputType ),
  1937. c.build( builder, 'float' )
  1938. );
  1939. } else if ( method === MathNode.MIX ) {
  1940. params.push(
  1941. a.build( builder, inputType ),
  1942. b.build( builder, inputType ),
  1943. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  1944. );
  1945. } else {
  1946. params.push( a.build( builder, inputType ) );
  1947. if ( b !== null ) params.push( b.build( builder, inputType ) );
  1948. if ( c !== null ) params.push( c.build( builder, inputType ) );
  1949. }
  1950. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  1951. }
  1952. }
  1953. serialize( data ) {
  1954. super.serialize( data );
  1955. data.method = this.method;
  1956. }
  1957. deserialize( data ) {
  1958. super.deserialize( data );
  1959. this.method = data.method;
  1960. }
  1961. }
  1962. // 1 input
  1963. MathNode.ALL = 'all';
  1964. MathNode.ANY = 'any';
  1965. MathNode.EQUALS = 'equals';
  1966. MathNode.RADIANS = 'radians';
  1967. MathNode.DEGREES = 'degrees';
  1968. MathNode.EXP = 'exp';
  1969. MathNode.EXP2 = 'exp2';
  1970. MathNode.LOG = 'log';
  1971. MathNode.LOG2 = 'log2';
  1972. MathNode.SQRT = 'sqrt';
  1973. MathNode.INVERSE_SQRT = 'inversesqrt';
  1974. MathNode.FLOOR = 'floor';
  1975. MathNode.CEIL = 'ceil';
  1976. MathNode.NORMALIZE = 'normalize';
  1977. MathNode.FRACT = 'fract';
  1978. MathNode.SIN = 'sin';
  1979. MathNode.COS = 'cos';
  1980. MathNode.TAN = 'tan';
  1981. MathNode.ASIN = 'asin';
  1982. MathNode.ACOS = 'acos';
  1983. MathNode.ATAN = 'atan';
  1984. MathNode.ABS = 'abs';
  1985. MathNode.SIGN = 'sign';
  1986. MathNode.LENGTH = 'length';
  1987. MathNode.NEGATE = 'negate';
  1988. MathNode.ONE_MINUS = 'oneMinus';
  1989. MathNode.DFDX = 'dFdx';
  1990. MathNode.DFDY = 'dFdy';
  1991. MathNode.ROUND = 'round';
  1992. MathNode.RECIPROCAL = 'reciprocal';
  1993. MathNode.TRUNC = 'trunc';
  1994. MathNode.FWIDTH = 'fwidth';
  1995. MathNode.BITCAST = 'bitcast';
  1996. MathNode.TRANSPOSE = 'transpose';
  1997. // 2 inputs
  1998. MathNode.ATAN2 = 'atan2';
  1999. MathNode.MIN = 'min';
  2000. MathNode.MAX = 'max';
  2001. MathNode.MOD = 'mod';
  2002. MathNode.STEP = 'step';
  2003. MathNode.REFLECT = 'reflect';
  2004. MathNode.DISTANCE = 'distance';
  2005. MathNode.DIFFERENCE = 'difference';
  2006. MathNode.DOT = 'dot';
  2007. MathNode.CROSS = 'cross';
  2008. MathNode.POW = 'pow';
  2009. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  2010. // 3 inputs
  2011. MathNode.MIX = 'mix';
  2012. MathNode.CLAMP = 'clamp';
  2013. MathNode.REFRACT = 'refract';
  2014. MathNode.SMOOTHSTEP = 'smoothstep';
  2015. MathNode.FACEFORWARD = 'faceforward';
  2016. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  2017. const INFINITY = /*@__PURE__*/ float( 1e6 );
  2018. const PI = /*@__PURE__*/ float( Math.PI );
  2019. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  2020. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  2021. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  2022. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  2023. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  2024. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  2025. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  2026. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  2027. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  2028. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  2029. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  2030. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  2031. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  2032. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  2033. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  2034. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  2035. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  2036. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  2037. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  2038. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  2039. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  2040. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  2041. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  2042. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  2043. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  2044. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  2045. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  2046. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  2047. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  2048. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  2049. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  2050. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  2051. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  2052. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  2053. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  2054. const atan2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN2 );
  2055. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  2056. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  2057. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  2058. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  2059. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  2060. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  2061. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  2062. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  2063. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  2064. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  2065. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  2066. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  2067. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  2068. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  2069. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  2070. const lengthSq = ( a ) => dot( a, a );
  2071. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  2072. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  2073. const saturate = ( value ) => clamp( value );
  2074. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  2075. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  2076. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  2077. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  2078. const a = 12.9898, b = 78.233, c = 43758.5453;
  2079. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  2080. return fract( sin( sn ).mul( c ) );
  2081. } );
  2082. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  2083. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  2084. addMethodChaining( 'all', all );
  2085. addMethodChaining( 'any', any );
  2086. addMethodChaining( 'equals', equals );
  2087. addMethodChaining( 'radians', radians );
  2088. addMethodChaining( 'degrees', degrees );
  2089. addMethodChaining( 'exp', exp );
  2090. addMethodChaining( 'exp2', exp2 );
  2091. addMethodChaining( 'log', log );
  2092. addMethodChaining( 'log2', log2 );
  2093. addMethodChaining( 'sqrt', sqrt );
  2094. addMethodChaining( 'inverseSqrt', inverseSqrt );
  2095. addMethodChaining( 'floor', floor );
  2096. addMethodChaining( 'ceil', ceil );
  2097. addMethodChaining( 'normalize', normalize );
  2098. addMethodChaining( 'fract', fract );
  2099. addMethodChaining( 'sin', sin );
  2100. addMethodChaining( 'cos', cos );
  2101. addMethodChaining( 'tan', tan );
  2102. addMethodChaining( 'asin', asin );
  2103. addMethodChaining( 'acos', acos );
  2104. addMethodChaining( 'atan', atan );
  2105. addMethodChaining( 'abs', abs );
  2106. addMethodChaining( 'sign', sign );
  2107. addMethodChaining( 'length', length );
  2108. addMethodChaining( 'lengthSq', lengthSq );
  2109. addMethodChaining( 'negate', negate );
  2110. addMethodChaining( 'oneMinus', oneMinus );
  2111. addMethodChaining( 'dFdx', dFdx );
  2112. addMethodChaining( 'dFdy', dFdy );
  2113. addMethodChaining( 'round', round );
  2114. addMethodChaining( 'reciprocal', reciprocal );
  2115. addMethodChaining( 'trunc', trunc );
  2116. addMethodChaining( 'fwidth', fwidth );
  2117. addMethodChaining( 'atan2', atan2 );
  2118. addMethodChaining( 'min', min$1 );
  2119. addMethodChaining( 'max', max$1 );
  2120. addMethodChaining( 'mod', mod );
  2121. addMethodChaining( 'step', step );
  2122. addMethodChaining( 'reflect', reflect );
  2123. addMethodChaining( 'distance', distance );
  2124. addMethodChaining( 'dot', dot );
  2125. addMethodChaining( 'cross', cross );
  2126. addMethodChaining( 'pow', pow );
  2127. addMethodChaining( 'pow2', pow2 );
  2128. addMethodChaining( 'pow3', pow3 );
  2129. addMethodChaining( 'pow4', pow4 );
  2130. addMethodChaining( 'transformDirection', transformDirection );
  2131. addMethodChaining( 'mix', mixElement );
  2132. addMethodChaining( 'clamp', clamp );
  2133. addMethodChaining( 'refract', refract );
  2134. addMethodChaining( 'smoothstep', smoothstepElement );
  2135. addMethodChaining( 'faceForward', faceForward );
  2136. addMethodChaining( 'difference', difference );
  2137. addMethodChaining( 'saturate', saturate );
  2138. addMethodChaining( 'cbrt', cbrt );
  2139. addMethodChaining( 'transpose', transpose );
  2140. addMethodChaining( 'rand', rand );
  2141. class ConditionalNode extends Node {
  2142. static get type() {
  2143. return 'ConditionalNode';
  2144. }
  2145. constructor( condNode, ifNode, elseNode = null ) {
  2146. super();
  2147. this.condNode = condNode;
  2148. this.ifNode = ifNode;
  2149. this.elseNode = elseNode;
  2150. }
  2151. getNodeType( builder ) {
  2152. const ifType = this.ifNode.getNodeType( builder );
  2153. if ( this.elseNode !== null ) {
  2154. const elseType = this.elseNode.getNodeType( builder );
  2155. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  2156. return elseType;
  2157. }
  2158. }
  2159. return ifType;
  2160. }
  2161. setup( builder ) {
  2162. const condNode = this.condNode.cache();
  2163. const ifNode = this.ifNode.cache();
  2164. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  2165. //
  2166. const currentNodeBlock = builder.context.nodeBlock;
  2167. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  2168. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  2169. //
  2170. const properties = builder.getNodeProperties( this );
  2171. properties.condNode = condNode;
  2172. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  2173. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  2174. }
  2175. generate( builder, output ) {
  2176. const type = this.getNodeType( builder );
  2177. const nodeData = builder.getDataFromNode( this );
  2178. if ( nodeData.nodeProperty !== undefined ) {
  2179. return nodeData.nodeProperty;
  2180. }
  2181. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  2182. const needsOutput = output !== 'void';
  2183. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  2184. nodeData.nodeProperty = nodeProperty;
  2185. const nodeSnippet = condNode.build( builder, 'bool' );
  2186. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  2187. let ifSnippet = ifNode.build( builder, type );
  2188. if ( ifSnippet ) {
  2189. if ( needsOutput ) {
  2190. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  2191. } else {
  2192. ifSnippet = 'return ' + ifSnippet + ';';
  2193. }
  2194. }
  2195. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  2196. if ( elseNode !== null ) {
  2197. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  2198. let elseSnippet = elseNode.build( builder, type );
  2199. if ( elseSnippet ) {
  2200. if ( needsOutput ) {
  2201. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  2202. } else {
  2203. elseSnippet = 'return ' + elseSnippet + ';';
  2204. }
  2205. }
  2206. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  2207. } else {
  2208. builder.addFlowCode( '\n\n' );
  2209. }
  2210. return builder.format( nodeProperty, type, output );
  2211. }
  2212. }
  2213. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  2214. addMethodChaining( 'select', select );
  2215. //
  2216. const cond = ( ...params ) => { // @deprecated, r168
  2217. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  2218. return select( ...params );
  2219. };
  2220. addMethodChaining( 'cond', cond );
  2221. class ContextNode extends Node {
  2222. static get type() {
  2223. return 'ContextNode';
  2224. }
  2225. constructor( node, value = {} ) {
  2226. super();
  2227. this.isContextNode = true;
  2228. this.node = node;
  2229. this.value = value;
  2230. }
  2231. getScope() {
  2232. return this.node.getScope();
  2233. }
  2234. getNodeType( builder ) {
  2235. return this.node.getNodeType( builder );
  2236. }
  2237. analyze( builder ) {
  2238. this.node.build( builder );
  2239. }
  2240. setup( builder ) {
  2241. const previousContext = builder.getContext();
  2242. builder.setContext( { ...builder.context, ...this.value } );
  2243. const node = this.node.build( builder );
  2244. builder.setContext( previousContext );
  2245. return node;
  2246. }
  2247. generate( builder, output ) {
  2248. const previousContext = builder.getContext();
  2249. builder.setContext( { ...builder.context, ...this.value } );
  2250. const snippet = this.node.build( builder, output );
  2251. builder.setContext( previousContext );
  2252. return snippet;
  2253. }
  2254. }
  2255. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  2256. const label = ( node, name ) => context( node, { label: name } );
  2257. addMethodChaining( 'context', context );
  2258. addMethodChaining( 'label', label );
  2259. class VarNode extends Node {
  2260. static get type() {
  2261. return 'VarNode';
  2262. }
  2263. constructor( node, name = null ) {
  2264. super();
  2265. this.node = node;
  2266. this.name = name;
  2267. this.global = true;
  2268. this.isVarNode = true;
  2269. }
  2270. getHash( builder ) {
  2271. return this.name || super.getHash( builder );
  2272. }
  2273. getNodeType( builder ) {
  2274. return this.node.getNodeType( builder );
  2275. }
  2276. generate( builder ) {
  2277. const { node, name } = this;
  2278. const nodeVar = builder.getVarFromNode( this, name, builder.getVectorType( this.getNodeType( builder ) ) );
  2279. const propertyName = builder.getPropertyName( nodeVar );
  2280. const snippet = node.build( builder, nodeVar.type );
  2281. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  2282. return propertyName;
  2283. }
  2284. }
  2285. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  2286. addMethodChaining( 'toVar', ( ...params ) => createVar( ...params ).append() );
  2287. // Deprecated
  2288. const temp = ( node ) => { // @deprecated, r170
  2289. console.warn( 'TSL: "temp" is deprecated. Use ".toVar()" instead.' );
  2290. return createVar( node );
  2291. };
  2292. addMethodChaining( 'temp', temp );
  2293. class VaryingNode extends Node {
  2294. static get type() {
  2295. return 'VaryingNode';
  2296. }
  2297. constructor( node, name = null ) {
  2298. super();
  2299. this.node = node;
  2300. this.name = name;
  2301. this.isVaryingNode = true;
  2302. }
  2303. isGlobal() {
  2304. return true;
  2305. }
  2306. getHash( builder ) {
  2307. return this.name || super.getHash( builder );
  2308. }
  2309. getNodeType( builder ) {
  2310. // VaryingNode is auto type
  2311. return this.node.getNodeType( builder );
  2312. }
  2313. setupVarying( builder ) {
  2314. const properties = builder.getNodeProperties( this );
  2315. let varying = properties.varying;
  2316. if ( varying === undefined ) {
  2317. const name = this.name;
  2318. const type = this.getNodeType( builder );
  2319. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  2320. properties.node = this.node;
  2321. }
  2322. // this property can be used to check if the varying can be optimized for a variable
  2323. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  2324. return varying;
  2325. }
  2326. setup( builder ) {
  2327. this.setupVarying( builder );
  2328. }
  2329. analyze( builder ) {
  2330. this.setupVarying( builder );
  2331. return this.node.analyze( builder );
  2332. }
  2333. generate( builder ) {
  2334. const properties = builder.getNodeProperties( this );
  2335. const varying = this.setupVarying( builder );
  2336. if ( properties.propertyName === undefined ) {
  2337. const type = this.getNodeType( builder );
  2338. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  2339. // force node run in vertex stage
  2340. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  2341. properties.propertyName = propertyName;
  2342. }
  2343. return builder.getPropertyName( varying );
  2344. }
  2345. }
  2346. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  2347. addMethodChaining( 'varying', varying );
  2348. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  2349. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  2350. const b = color.mul( 0.0773993808 );
  2351. const factor = color.lessThanEqual( 0.04045 );
  2352. const rgbResult = mix( a, b, factor );
  2353. return rgbResult;
  2354. } ).setLayout( {
  2355. name: 'sRGBTransferEOTF',
  2356. type: 'vec3',
  2357. inputs: [
  2358. { name: 'color', type: 'vec3' }
  2359. ]
  2360. } );
  2361. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  2362. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  2363. const b = color.mul( 12.92 );
  2364. const factor = color.lessThanEqual( 0.0031308 );
  2365. const rgbResult = mix( a, b, factor );
  2366. return rgbResult;
  2367. } ).setLayout( {
  2368. name: 'sRGBTransferOETF',
  2369. type: 'vec3',
  2370. inputs: [
  2371. { name: 'color', type: 'vec3' }
  2372. ]
  2373. } );
  2374. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  2375. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  2376. class ColorSpaceNode extends TempNode {
  2377. static get type() {
  2378. return 'ColorSpaceNode';
  2379. }
  2380. constructor( colorNode, source, target ) {
  2381. super( 'vec4' );
  2382. this.colorNode = colorNode;
  2383. this.source = source;
  2384. this.target = target;
  2385. }
  2386. resolveColorSpace( builder, colorSpace ) {
  2387. if ( colorSpace === WORKING_COLOR_SPACE ) {
  2388. return ColorManagement.workingColorSpace;
  2389. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  2390. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  2391. }
  2392. return colorSpace;
  2393. }
  2394. setup( builder ) {
  2395. const { colorNode } = this;
  2396. const source = this.resolveColorSpace( builder, this.source );
  2397. const target = this.resolveColorSpace( builder, this.target );
  2398. let outputNode = colorNode;
  2399. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  2400. return outputNode;
  2401. }
  2402. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  2403. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  2404. }
  2405. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  2406. outputNode = vec4(
  2407. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  2408. outputNode.a
  2409. );
  2410. }
  2411. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  2412. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  2413. }
  2414. return outputNode;
  2415. }
  2416. }
  2417. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  2418. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  2419. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  2420. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  2421. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  2422. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  2423. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  2424. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  2425. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  2426. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  2427. static get type() {
  2428. return 'ReferenceElementNode';
  2429. }
  2430. constructor( referenceNode, indexNode ) {
  2431. super( referenceNode, indexNode );
  2432. this.referenceNode = referenceNode;
  2433. this.isReferenceElementNode = true;
  2434. }
  2435. getNodeType() {
  2436. return this.referenceNode.uniformType;
  2437. }
  2438. generate( builder ) {
  2439. const snippet = super.generate( builder );
  2440. const arrayType = this.referenceNode.getNodeType();
  2441. const elementType = this.getNodeType();
  2442. return builder.format( snippet, arrayType, elementType );
  2443. }
  2444. };
  2445. class ReferenceBaseNode extends Node {
  2446. static get type() {
  2447. return 'ReferenceBaseNode';
  2448. }
  2449. constructor( property, uniformType, object = null, count = null ) {
  2450. super();
  2451. this.property = property;
  2452. this.uniformType = uniformType;
  2453. this.object = object;
  2454. this.count = count;
  2455. this.properties = property.split( '.' );
  2456. this.reference = object;
  2457. this.node = null;
  2458. this.group = null;
  2459. this.updateType = NodeUpdateType.OBJECT;
  2460. }
  2461. setGroup( group ) {
  2462. this.group = group;
  2463. return this;
  2464. }
  2465. element( indexNode ) {
  2466. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  2467. }
  2468. setNodeType( uniformType ) {
  2469. const node = uniform( null, uniformType ).getSelf();
  2470. if ( this.group !== null ) {
  2471. node.setGroup( this.group );
  2472. }
  2473. this.node = node;
  2474. }
  2475. getNodeType( builder ) {
  2476. if ( this.node === null ) {
  2477. this.updateReference( builder );
  2478. this.updateValue();
  2479. }
  2480. return this.node.getNodeType( builder );
  2481. }
  2482. getValueFromReference( object = this.reference ) {
  2483. const { properties } = this;
  2484. let value = object[ properties[ 0 ] ];
  2485. for ( let i = 1; i < properties.length; i ++ ) {
  2486. value = value[ properties[ i ] ];
  2487. }
  2488. return value;
  2489. }
  2490. updateReference( state ) {
  2491. this.reference = this.object !== null ? this.object : state.object;
  2492. return this.reference;
  2493. }
  2494. setup() {
  2495. this.updateValue();
  2496. return this.node;
  2497. }
  2498. update( /*frame*/ ) {
  2499. this.updateValue();
  2500. }
  2501. updateValue() {
  2502. if ( this.node === null ) this.setNodeType( this.uniformType );
  2503. const value = this.getValueFromReference();
  2504. if ( Array.isArray( value ) ) {
  2505. this.node.array = value;
  2506. } else {
  2507. this.node.value = value;
  2508. }
  2509. }
  2510. }
  2511. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  2512. class RendererReferenceNode extends ReferenceBaseNode {
  2513. static get type() {
  2514. return 'RendererReferenceNode';
  2515. }
  2516. constructor( property, inputType, renderer = null ) {
  2517. super( property, inputType, renderer );
  2518. this.renderer = renderer;
  2519. this.setGroup( renderGroup );
  2520. }
  2521. updateReference( state ) {
  2522. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  2523. return this.reference;
  2524. }
  2525. }
  2526. const rendererReference = ( name, type, renderer ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  2527. class ToneMappingNode extends TempNode {
  2528. static get type() {
  2529. return 'ToneMappingNode';
  2530. }
  2531. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  2532. super( 'vec3' );
  2533. this.toneMapping = toneMapping;
  2534. this.exposureNode = exposureNode;
  2535. this.colorNode = colorNode;
  2536. }
  2537. getCacheKey() {
  2538. return hash$1( super.getCacheKey(), this.toneMapping );
  2539. }
  2540. setup( builder ) {
  2541. const colorNode = this.colorNode || builder.context.color;
  2542. const toneMapping = this.toneMapping;
  2543. if ( toneMapping === NoToneMapping ) return colorNode;
  2544. let outputNode = null;
  2545. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  2546. if ( toneMappingFn !== null ) {
  2547. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  2548. } else {
  2549. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  2550. outputNode = colorNode;
  2551. }
  2552. return outputNode;
  2553. }
  2554. }
  2555. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  2556. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  2557. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  2558. class BufferAttributeNode extends InputNode {
  2559. static get type() {
  2560. return 'BufferAttributeNode';
  2561. }
  2562. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  2563. super( value, bufferType );
  2564. this.isBufferNode = true;
  2565. this.bufferType = bufferType;
  2566. this.bufferStride = bufferStride;
  2567. this.bufferOffset = bufferOffset;
  2568. this.usage = StaticDrawUsage;
  2569. this.instanced = false;
  2570. this.attribute = null;
  2571. this.global = true;
  2572. if ( value && value.isBufferAttribute === true ) {
  2573. this.attribute = value;
  2574. this.usage = value.usage;
  2575. this.instanced = value.isInstancedBufferAttribute;
  2576. }
  2577. }
  2578. getHash( builder ) {
  2579. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  2580. let bufferData = builder.globalCache.getData( this.value );
  2581. if ( bufferData === undefined ) {
  2582. bufferData = {
  2583. node: this
  2584. };
  2585. builder.globalCache.setData( this.value, bufferData );
  2586. }
  2587. return bufferData.node.uuid;
  2588. }
  2589. return this.uuid;
  2590. }
  2591. getNodeType( builder ) {
  2592. if ( this.bufferType === null ) {
  2593. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  2594. }
  2595. return this.bufferType;
  2596. }
  2597. setup( builder ) {
  2598. if ( this.attribute !== null ) return;
  2599. const type = this.getNodeType( builder );
  2600. const array = this.value;
  2601. const itemSize = builder.getTypeLength( type );
  2602. const stride = this.bufferStride || itemSize;
  2603. const offset = this.bufferOffset;
  2604. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  2605. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  2606. buffer.setUsage( this.usage );
  2607. this.attribute = bufferAttribute;
  2608. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  2609. }
  2610. generate( builder ) {
  2611. const nodeType = this.getNodeType( builder );
  2612. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  2613. const propertyName = builder.getPropertyName( nodeAttribute );
  2614. let output = null;
  2615. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  2616. this.name = propertyName;
  2617. output = propertyName;
  2618. } else {
  2619. const nodeVarying = varying( this );
  2620. output = nodeVarying.build( builder, nodeType );
  2621. }
  2622. return output;
  2623. }
  2624. getInputType( /*builder*/ ) {
  2625. return 'bufferAttribute';
  2626. }
  2627. setUsage( value ) {
  2628. this.usage = value;
  2629. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  2630. this.attribute.usage = value;
  2631. }
  2632. return this;
  2633. }
  2634. setInstanced( value ) {
  2635. this.instanced = value;
  2636. return this;
  2637. }
  2638. }
  2639. const bufferAttribute = ( array, type, stride, offset ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  2640. const dynamicBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  2641. const instancedBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  2642. const instancedDynamicBufferAttribute = ( array, type, stride, offset ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  2643. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  2644. class ComputeNode extends Node {
  2645. static get type() {
  2646. return 'ComputeNode';
  2647. }
  2648. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  2649. super( 'void' );
  2650. this.isComputeNode = true;
  2651. this.computeNode = computeNode;
  2652. this.count = count;
  2653. this.workgroupSize = workgroupSize;
  2654. this.dispatchCount = 0;
  2655. this.version = 1;
  2656. this.updateBeforeType = NodeUpdateType.OBJECT;
  2657. this.onInitFunction = null;
  2658. this.updateDispatchCount();
  2659. }
  2660. dispose() {
  2661. this.dispatchEvent( { type: 'dispose' } );
  2662. }
  2663. set needsUpdate( value ) {
  2664. if ( value === true ) this.version ++;
  2665. }
  2666. updateDispatchCount() {
  2667. const { count, workgroupSize } = this;
  2668. let size = workgroupSize[ 0 ];
  2669. for ( let i = 1; i < workgroupSize.length; i ++ )
  2670. size *= workgroupSize[ i ];
  2671. this.dispatchCount = Math.ceil( count / size );
  2672. }
  2673. onInit( callback ) {
  2674. this.onInitFunction = callback;
  2675. return this;
  2676. }
  2677. updateBefore( { renderer } ) {
  2678. renderer.compute( this );
  2679. }
  2680. generate( builder ) {
  2681. const { shaderStage } = builder;
  2682. if ( shaderStage === 'compute' ) {
  2683. const snippet = this.computeNode.build( builder, 'void' );
  2684. if ( snippet !== '' ) {
  2685. builder.addLineFlowCode( snippet, this );
  2686. }
  2687. }
  2688. }
  2689. }
  2690. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  2691. addMethodChaining( 'compute', compute );
  2692. class CacheNode extends Node {
  2693. static get type() {
  2694. return 'CacheNode';
  2695. }
  2696. constructor( node, parent = true ) {
  2697. super();
  2698. this.node = node;
  2699. this.parent = parent;
  2700. this.isCacheNode = true;
  2701. }
  2702. getNodeType( builder ) {
  2703. return this.node.getNodeType( builder );
  2704. }
  2705. build( builder, ...params ) {
  2706. const previousCache = builder.getCache();
  2707. const cache = builder.getCacheFromNode( this, this.parent );
  2708. builder.setCache( cache );
  2709. const data = this.node.build( builder, ...params );
  2710. builder.setCache( previousCache );
  2711. return data;
  2712. }
  2713. }
  2714. const cache = ( node, ...params ) => nodeObject( new CacheNode( nodeObject( node ), ...params ) );
  2715. addMethodChaining( 'cache', cache );
  2716. class BypassNode extends Node {
  2717. static get type() {
  2718. return 'BypassNode';
  2719. }
  2720. constructor( returnNode, callNode ) {
  2721. super();
  2722. this.isBypassNode = true;
  2723. this.outputNode = returnNode;
  2724. this.callNode = callNode;
  2725. }
  2726. getNodeType( builder ) {
  2727. return this.outputNode.getNodeType( builder );
  2728. }
  2729. generate( builder ) {
  2730. const snippet = this.callNode.build( builder, 'void' );
  2731. if ( snippet !== '' ) {
  2732. builder.addLineFlowCode( snippet, this );
  2733. }
  2734. return this.outputNode.build( builder );
  2735. }
  2736. }
  2737. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  2738. addMethodChaining( 'bypass', bypass );
  2739. class RemapNode extends Node {
  2740. static get type() {
  2741. return 'RemapNode';
  2742. }
  2743. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  2744. super();
  2745. this.node = node;
  2746. this.inLowNode = inLowNode;
  2747. this.inHighNode = inHighNode;
  2748. this.outLowNode = outLowNode;
  2749. this.outHighNode = outHighNode;
  2750. this.doClamp = true;
  2751. }
  2752. setup() {
  2753. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  2754. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  2755. if ( doClamp === true ) t = t.clamp();
  2756. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  2757. }
  2758. }
  2759. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  2760. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  2761. addMethodChaining( 'remap', remap );
  2762. addMethodChaining( 'remapClamp', remapClamp );
  2763. class ExpressionNode extends Node {
  2764. static get type() {
  2765. return 'ExpressionNode';
  2766. }
  2767. constructor( snippet = '', nodeType = 'void' ) {
  2768. super( nodeType );
  2769. this.snippet = snippet;
  2770. }
  2771. generate( builder, output ) {
  2772. const type = this.getNodeType( builder );
  2773. const snippet = this.snippet;
  2774. if ( type === 'void' ) {
  2775. builder.addLineFlowCode( snippet, this );
  2776. } else {
  2777. return builder.format( `( ${ snippet } )`, type, output );
  2778. }
  2779. }
  2780. }
  2781. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  2782. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  2783. const Return = () => expression( 'return' ).append();
  2784. addMethodChaining( 'discard', Discard );
  2785. class RenderOutputNode extends TempNode {
  2786. static get type() {
  2787. return 'RenderOutputNode';
  2788. }
  2789. constructor( colorNode, toneMapping, outputColorSpace ) {
  2790. super( 'vec4' );
  2791. this.colorNode = colorNode;
  2792. this.toneMapping = toneMapping;
  2793. this.outputColorSpace = outputColorSpace;
  2794. this.isRenderOutput = true;
  2795. }
  2796. setup( { context } ) {
  2797. let outputNode = this.colorNode || context.color;
  2798. // tone mapping
  2799. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  2800. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  2801. if ( toneMapping !== NoToneMapping ) {
  2802. outputNode = outputNode.toneMapping( toneMapping );
  2803. }
  2804. // working to output color space
  2805. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  2806. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  2807. }
  2808. return outputNode;
  2809. }
  2810. }
  2811. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  2812. addMethodChaining( 'renderOutput', renderOutput );
  2813. // Non-PURE exports list, side-effects are required here.
  2814. // TSL Base Syntax
  2815. function addNodeElement( name/*, nodeElement*/ ) {
  2816. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  2817. }
  2818. class AttributeNode extends Node {
  2819. static get type() {
  2820. return 'AttributeNode';
  2821. }
  2822. constructor( attributeName, nodeType = null ) {
  2823. super( nodeType );
  2824. this.global = true;
  2825. this._attributeName = attributeName;
  2826. }
  2827. getHash( builder ) {
  2828. return this.getAttributeName( builder );
  2829. }
  2830. getNodeType( builder ) {
  2831. let nodeType = this.nodeType;
  2832. if ( nodeType === null ) {
  2833. const attributeName = this.getAttributeName( builder );
  2834. if ( builder.hasGeometryAttribute( attributeName ) ) {
  2835. const attribute = builder.geometry.getAttribute( attributeName );
  2836. nodeType = builder.getTypeFromAttribute( attribute );
  2837. } else {
  2838. nodeType = 'float';
  2839. }
  2840. }
  2841. return nodeType;
  2842. }
  2843. setAttributeName( attributeName ) {
  2844. this._attributeName = attributeName;
  2845. return this;
  2846. }
  2847. getAttributeName( /*builder*/ ) {
  2848. return this._attributeName;
  2849. }
  2850. generate( builder ) {
  2851. const attributeName = this.getAttributeName( builder );
  2852. const nodeType = this.getNodeType( builder );
  2853. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  2854. if ( geometryAttribute === true ) {
  2855. const attribute = builder.geometry.getAttribute( attributeName );
  2856. const attributeType = builder.getTypeFromAttribute( attribute );
  2857. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  2858. if ( builder.shaderStage === 'vertex' ) {
  2859. return builder.format( nodeAttribute.name, attributeType, nodeType );
  2860. } else {
  2861. const nodeVarying = varying( this );
  2862. return nodeVarying.build( builder, nodeType );
  2863. }
  2864. } else {
  2865. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  2866. return builder.generateConst( nodeType );
  2867. }
  2868. }
  2869. serialize( data ) {
  2870. super.serialize( data );
  2871. data.global = this.global;
  2872. data._attributeName = this._attributeName;
  2873. }
  2874. deserialize( data ) {
  2875. super.deserialize( data );
  2876. this.global = data.global;
  2877. this._attributeName = data._attributeName;
  2878. }
  2879. }
  2880. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  2881. const uv = ( index ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  2882. class TextureSizeNode extends Node {
  2883. static get type() {
  2884. return 'TextureSizeNode';
  2885. }
  2886. constructor( textureNode, levelNode = null ) {
  2887. super( 'uvec2' );
  2888. this.isTextureSizeNode = true;
  2889. this.textureNode = textureNode;
  2890. this.levelNode = levelNode;
  2891. }
  2892. generate( builder, output ) {
  2893. const textureProperty = this.textureNode.build( builder, 'property' );
  2894. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  2895. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  2896. }
  2897. }
  2898. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  2899. class MaxMipLevelNode extends UniformNode {
  2900. static get type() {
  2901. return 'MaxMipLevelNode';
  2902. }
  2903. constructor( textureNode ) {
  2904. super( 0 );
  2905. this._textureNode = textureNode;
  2906. this.updateType = NodeUpdateType.FRAME;
  2907. }
  2908. get textureNode() {
  2909. return this._textureNode;
  2910. }
  2911. get texture() {
  2912. return this._textureNode.value;
  2913. }
  2914. update() {
  2915. const texture = this.texture;
  2916. const images = texture.images;
  2917. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  2918. if ( image && image.width !== undefined ) {
  2919. const { width, height } = image;
  2920. this.value = Math.log2( Math.max( width, height ) );
  2921. }
  2922. }
  2923. }
  2924. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  2925. class TextureNode extends UniformNode {
  2926. static get type() {
  2927. return 'TextureNode';
  2928. }
  2929. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  2930. super( value );
  2931. this.isTextureNode = true;
  2932. this.uvNode = uvNode;
  2933. this.levelNode = levelNode;
  2934. this.biasNode = biasNode;
  2935. this.compareNode = null;
  2936. this.depthNode = null;
  2937. this.gradNode = null;
  2938. this.sampler = true;
  2939. this.updateMatrix = false;
  2940. this.updateType = NodeUpdateType.NONE;
  2941. this.referenceNode = null;
  2942. this._value = value;
  2943. this._matrixUniform = null;
  2944. this.setUpdateMatrix( uvNode === null );
  2945. }
  2946. set value( value ) {
  2947. if ( this.referenceNode ) {
  2948. this.referenceNode.value = value;
  2949. } else {
  2950. this._value = value;
  2951. }
  2952. }
  2953. get value() {
  2954. return this.referenceNode ? this.referenceNode.value : this._value;
  2955. }
  2956. getUniformHash( /*builder*/ ) {
  2957. return this.value.uuid;
  2958. }
  2959. getNodeType( /*builder*/ ) {
  2960. if ( this.value.isDepthTexture === true ) return 'float';
  2961. if ( this.value.type === UnsignedIntType ) {
  2962. return 'uvec4';
  2963. } else if ( this.value.type === IntType ) {
  2964. return 'ivec4';
  2965. }
  2966. return 'vec4';
  2967. }
  2968. getInputType( /*builder*/ ) {
  2969. return 'texture';
  2970. }
  2971. getDefaultUV() {
  2972. return uv( this.value.channel );
  2973. }
  2974. updateReference( /*state*/ ) {
  2975. return this.value;
  2976. }
  2977. getTransformedUV( uvNode ) {
  2978. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  2979. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  2980. }
  2981. setUpdateMatrix( value ) {
  2982. this.updateMatrix = value;
  2983. this.updateType = value ? NodeUpdateType.FRAME : NodeUpdateType.NONE;
  2984. return this;
  2985. }
  2986. setupUV( builder, uvNode ) {
  2987. const texture = this.value;
  2988. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  2989. if ( this.sampler ) {
  2990. uvNode = uvNode.flipY();
  2991. } else {
  2992. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  2993. }
  2994. }
  2995. return uvNode;
  2996. }
  2997. setup( builder ) {
  2998. const properties = builder.getNodeProperties( this );
  2999. properties.referenceNode = this.referenceNode;
  3000. //
  3001. let uvNode = this.uvNode;
  3002. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  3003. uvNode = builder.context.getUV( this );
  3004. }
  3005. if ( ! uvNode ) uvNode = this.getDefaultUV();
  3006. if ( this.updateMatrix === true ) {
  3007. uvNode = this.getTransformedUV( uvNode );
  3008. }
  3009. uvNode = this.setupUV( builder, uvNode );
  3010. //
  3011. let levelNode = this.levelNode;
  3012. if ( levelNode === null && builder.context.getTextureLevel ) {
  3013. levelNode = builder.context.getTextureLevel( this );
  3014. }
  3015. //
  3016. properties.uvNode = uvNode;
  3017. properties.levelNode = levelNode;
  3018. properties.biasNode = this.biasNode;
  3019. properties.compareNode = this.compareNode;
  3020. properties.gradNode = this.gradNode;
  3021. properties.depthNode = this.depthNode;
  3022. }
  3023. generateUV( builder, uvNode ) {
  3024. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  3025. }
  3026. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  3027. const texture = this.value;
  3028. let snippet;
  3029. if ( levelSnippet ) {
  3030. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  3031. } else if ( biasSnippet ) {
  3032. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  3033. } else if ( gradSnippet ) {
  3034. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  3035. } else if ( compareSnippet ) {
  3036. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  3037. } else if ( this.sampler === false ) {
  3038. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  3039. } else {
  3040. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  3041. }
  3042. return snippet;
  3043. }
  3044. generate( builder, output ) {
  3045. const properties = builder.getNodeProperties( this );
  3046. const texture = this.value;
  3047. if ( ! texture || texture.isTexture !== true ) {
  3048. throw new Error( 'TextureNode: Need a three.js texture.' );
  3049. }
  3050. const textureProperty = super.generate( builder, 'property' );
  3051. if ( output === 'sampler' ) {
  3052. return textureProperty + '_sampler';
  3053. } else if ( builder.isReference( output ) ) {
  3054. return textureProperty;
  3055. } else {
  3056. const nodeData = builder.getDataFromNode( this );
  3057. let propertyName = nodeData.propertyName;
  3058. if ( propertyName === undefined ) {
  3059. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  3060. const uvSnippet = this.generateUV( builder, uvNode );
  3061. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  3062. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  3063. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  3064. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  3065. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  3066. const nodeVar = builder.getVarFromNode( this );
  3067. propertyName = builder.getPropertyName( nodeVar );
  3068. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  3069. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  3070. nodeData.snippet = snippet;
  3071. nodeData.propertyName = propertyName;
  3072. }
  3073. let snippet = propertyName;
  3074. const nodeType = this.getNodeType( builder );
  3075. if ( builder.needsToWorkingColorSpace( texture ) ) {
  3076. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  3077. }
  3078. return builder.format( snippet, nodeType, output );
  3079. }
  3080. }
  3081. setSampler( value ) {
  3082. this.sampler = value;
  3083. return this;
  3084. }
  3085. getSampler() {
  3086. return this.sampler;
  3087. }
  3088. // @TODO: Move to TSL
  3089. uv( uvNode ) {
  3090. const textureNode = this.clone();
  3091. textureNode.uvNode = nodeObject( uvNode );
  3092. textureNode.referenceNode = this.getSelf();
  3093. return nodeObject( textureNode );
  3094. }
  3095. blur( amountNode ) {
  3096. const textureNode = this.clone();
  3097. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  3098. textureNode.referenceNode = this.getSelf();
  3099. return nodeObject( textureNode );
  3100. }
  3101. level( levelNode ) {
  3102. const textureNode = this.clone();
  3103. textureNode.levelNode = nodeObject( levelNode );
  3104. textureNode.referenceNode = this.getSelf();
  3105. return nodeObject( textureNode );
  3106. }
  3107. size( levelNode ) {
  3108. return textureSize( this, levelNode );
  3109. }
  3110. bias( biasNode ) {
  3111. const textureNode = this.clone();
  3112. textureNode.biasNode = nodeObject( biasNode );
  3113. textureNode.referenceNode = this.getSelf();
  3114. return nodeObject( textureNode );
  3115. }
  3116. compare( compareNode ) {
  3117. const textureNode = this.clone();
  3118. textureNode.compareNode = nodeObject( compareNode );
  3119. textureNode.referenceNode = this.getSelf();
  3120. return nodeObject( textureNode );
  3121. }
  3122. grad( gradNodeX, gradNodeY ) {
  3123. const textureNode = this.clone();
  3124. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  3125. textureNode.referenceNode = this.getSelf();
  3126. return nodeObject( textureNode );
  3127. }
  3128. depth( depthNode ) {
  3129. const textureNode = this.clone();
  3130. textureNode.depthNode = nodeObject( depthNode );
  3131. textureNode.referenceNode = this.getSelf();
  3132. return nodeObject( textureNode );
  3133. }
  3134. // --
  3135. serialize( data ) {
  3136. super.serialize( data );
  3137. data.value = this.value.toJSON( data.meta ).uuid;
  3138. data.sampler = this.sampler;
  3139. data.updateMatrix = this.updateMatrix;
  3140. data.updateType = this.updateType;
  3141. }
  3142. deserialize( data ) {
  3143. super.deserialize( data );
  3144. this.value = data.meta.textures[ data.value ];
  3145. this.sampler = data.sampler;
  3146. this.updateMatrix = data.updateMatrix;
  3147. this.updateType = data.updateType;
  3148. }
  3149. update() {
  3150. const texture = this.value;
  3151. const matrixUniform = this._matrixUniform;
  3152. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  3153. if ( texture.matrixAutoUpdate === true ) {
  3154. texture.updateMatrix();
  3155. }
  3156. }
  3157. clone() {
  3158. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  3159. newNode.sampler = this.sampler;
  3160. return newNode;
  3161. }
  3162. }
  3163. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  3164. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  3165. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  3166. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  3167. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  3168. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  3169. const cameraProjectionMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  3170. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  3171. const cameraViewMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  3172. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  3173. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  3174. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  3175. class Object3DNode extends Node {
  3176. static get type() {
  3177. return 'Object3DNode';
  3178. }
  3179. constructor( scope, object3d = null ) {
  3180. super();
  3181. this.scope = scope;
  3182. this.object3d = object3d;
  3183. this.updateType = NodeUpdateType.OBJECT;
  3184. this._uniformNode = new UniformNode( null );
  3185. }
  3186. getNodeType() {
  3187. const scope = this.scope;
  3188. if ( scope === Object3DNode.WORLD_MATRIX ) {
  3189. return 'mat4';
  3190. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  3191. return 'vec3';
  3192. }
  3193. }
  3194. update( frame ) {
  3195. const object = this.object3d;
  3196. const uniformNode = this._uniformNode;
  3197. const scope = this.scope;
  3198. if ( scope === Object3DNode.WORLD_MATRIX ) {
  3199. uniformNode.value = object.matrixWorld;
  3200. } else if ( scope === Object3DNode.POSITION ) {
  3201. uniformNode.value = uniformNode.value || new Vector3();
  3202. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  3203. } else if ( scope === Object3DNode.SCALE ) {
  3204. uniformNode.value = uniformNode.value || new Vector3();
  3205. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  3206. } else if ( scope === Object3DNode.DIRECTION ) {
  3207. uniformNode.value = uniformNode.value || new Vector3();
  3208. object.getWorldDirection( uniformNode.value );
  3209. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  3210. const camera = frame.camera;
  3211. uniformNode.value = uniformNode.value || new Vector3();
  3212. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  3213. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  3214. }
  3215. }
  3216. generate( builder ) {
  3217. const scope = this.scope;
  3218. if ( scope === Object3DNode.WORLD_MATRIX ) {
  3219. this._uniformNode.nodeType = 'mat4';
  3220. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  3221. this._uniformNode.nodeType = 'vec3';
  3222. }
  3223. return this._uniformNode.build( builder );
  3224. }
  3225. serialize( data ) {
  3226. super.serialize( data );
  3227. data.scope = this.scope;
  3228. }
  3229. deserialize( data ) {
  3230. super.deserialize( data );
  3231. this.scope = data.scope;
  3232. }
  3233. }
  3234. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  3235. Object3DNode.POSITION = 'position';
  3236. Object3DNode.SCALE = 'scale';
  3237. Object3DNode.VIEW_POSITION = 'viewPosition';
  3238. Object3DNode.DIRECTION = 'direction';
  3239. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  3240. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  3241. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  3242. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  3243. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  3244. class ModelNode extends Object3DNode {
  3245. static get type() {
  3246. return 'ModelNode';
  3247. }
  3248. constructor( scope ) {
  3249. super( scope );
  3250. }
  3251. update( frame ) {
  3252. this.object3d = frame.object;
  3253. super.update( frame );
  3254. }
  3255. }
  3256. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  3257. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  3258. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  3259. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  3260. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  3261. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  3262. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  3263. const modelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix ).toVar( 'modelViewMatrix' );
  3264. const highPrecisionModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  3265. builder.context.isHighPrecisionModelViewMatrix = true;
  3266. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  3267. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  3268. } );
  3269. } ).once() )().toVar( 'highPrecisionModelViewMatrix' );
  3270. const highPrecisionModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  3271. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  3272. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  3273. if ( isHighPrecisionModelViewMatrix !== true ) {
  3274. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  3275. }
  3276. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  3277. } );
  3278. } ).once() )().toVar( 'highPrecisionModelNormalMatrix' );
  3279. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  3280. const positionLocal = /*@__PURE__*/ positionGeometry.varying( 'positionLocal' );
  3281. const positionPrevious = /*@__PURE__*/ positionGeometry.varying( 'positionPrevious' );
  3282. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.varying( 'v_positionWorld' );
  3283. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).varying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' );
  3284. const positionView = /*@__PURE__*/ modelViewMatrix.mul( positionLocal ).xyz.varying( 'v_positionView' );
  3285. const positionViewDirection = /*@__PURE__*/ positionView.negate().varying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  3286. class FrontFacingNode extends Node {
  3287. static get type() {
  3288. return 'FrontFacingNode';
  3289. }
  3290. constructor() {
  3291. super( 'bool' );
  3292. this.isFrontFacingNode = true;
  3293. }
  3294. generate( builder ) {
  3295. const { renderer, material } = builder;
  3296. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  3297. if ( material.side === BackSide ) {
  3298. return 'false';
  3299. }
  3300. }
  3301. return builder.getFrontFacing();
  3302. }
  3303. }
  3304. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  3305. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  3306. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  3307. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  3308. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  3309. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  3310. return vec3( 0, 1, 0 );
  3311. }
  3312. return normalGeometry;
  3313. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  3314. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  3315. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  3316. let node;
  3317. if ( builder.material.flatShading === true ) {
  3318. node = normalFlat;
  3319. } else {
  3320. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  3321. }
  3322. return node;
  3323. }, 'vec3' ).once() )().toVar( 'normalView' );
  3324. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  3325. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  3326. return builder.context.setupNormal();
  3327. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  3328. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  3329. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  3330. return builder.context.setupClearcoatNormal();
  3331. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  3332. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  3333. const m = mat3( matrix );
  3334. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  3335. return m.mul( transformedNormal ).xyz;
  3336. } );
  3337. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  3338. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  3339. if ( modelNormalViewMatrix !== null ) {
  3340. return modelNormalViewMatrix.transformDirection( normal );
  3341. }
  3342. //
  3343. const transformedNormal = modelNormalMatrix.mul( normal );
  3344. return cameraViewMatrix.transformDirection( transformedNormal );
  3345. } );
  3346. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  3347. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  3348. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  3349. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  3350. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  3351. class CubeTextureNode extends TextureNode {
  3352. static get type() {
  3353. return 'CubeTextureNode';
  3354. }
  3355. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  3356. super( value, uvNode, levelNode, biasNode );
  3357. this.isCubeTextureNode = true;
  3358. }
  3359. getInputType( /*builder*/ ) {
  3360. return 'cubeTexture';
  3361. }
  3362. getDefaultUV() {
  3363. const texture = this.value;
  3364. if ( texture.mapping === CubeReflectionMapping ) {
  3365. return reflectVector;
  3366. } else if ( texture.mapping === CubeRefractionMapping ) {
  3367. return refractVector;
  3368. } else {
  3369. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  3370. return vec3( 0, 0, 0 );
  3371. }
  3372. }
  3373. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  3374. setupUV( builder, uvNode ) {
  3375. const texture = this.value;
  3376. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  3377. return vec3( uvNode.x.negate(), uvNode.yz );
  3378. } else {
  3379. return uvNode;
  3380. }
  3381. }
  3382. generateUV( builder, cubeUV ) {
  3383. return cubeUV.build( builder, 'vec3' );
  3384. }
  3385. }
  3386. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  3387. class BufferNode extends UniformNode {
  3388. static get type() {
  3389. return 'BufferNode';
  3390. }
  3391. constructor( value, bufferType, bufferCount = 0 ) {
  3392. super( value, bufferType );
  3393. this.isBufferNode = true;
  3394. this.bufferType = bufferType;
  3395. this.bufferCount = bufferCount;
  3396. }
  3397. getElementType( builder ) {
  3398. return this.getNodeType( builder );
  3399. }
  3400. getInputType( /*builder*/ ) {
  3401. return 'buffer';
  3402. }
  3403. }
  3404. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  3405. class UniformArrayElementNode extends ArrayElementNode {
  3406. static get type() {
  3407. return 'UniformArrayElementNode';
  3408. }
  3409. constructor( arrayBuffer, indexNode ) {
  3410. super( arrayBuffer, indexNode );
  3411. this.isArrayBufferElementNode = true;
  3412. }
  3413. generate( builder ) {
  3414. const snippet = super.generate( builder );
  3415. const type = this.getNodeType();
  3416. return builder.format( snippet, 'vec4', type );
  3417. }
  3418. }
  3419. class UniformArrayNode extends BufferNode {
  3420. static get type() {
  3421. return 'UniformArrayNode';
  3422. }
  3423. constructor( value, elementType = null ) {
  3424. super( null, 'vec4' );
  3425. this.array = value;
  3426. this.elementType = elementType;
  3427. this._elementType = null;
  3428. this._elementLength = 0;
  3429. this.updateType = NodeUpdateType.RENDER;
  3430. this.isArrayBufferNode = true;
  3431. }
  3432. getElementType() {
  3433. return this.elementType || this._elementType;
  3434. }
  3435. getElementLength() {
  3436. return this._elementLength;
  3437. }
  3438. update( /*frame*/ ) {
  3439. const { array, value } = this;
  3440. const elementLength = this.getElementLength();
  3441. const elementType = this.getElementType();
  3442. if ( elementLength === 1 ) {
  3443. for ( let i = 0; i < array.length; i ++ ) {
  3444. const index = i * 4;
  3445. value[ index ] = array[ i ];
  3446. }
  3447. } else if ( elementType === 'color' ) {
  3448. for ( let i = 0; i < array.length; i ++ ) {
  3449. const index = i * 4;
  3450. const vector = array[ i ];
  3451. value[ index ] = vector.r;
  3452. value[ index + 1 ] = vector.g;
  3453. value[ index + 2 ] = vector.b || 0;
  3454. //value[ index + 3 ] = vector.a || 0;
  3455. }
  3456. } else {
  3457. for ( let i = 0; i < array.length; i ++ ) {
  3458. const index = i * 4;
  3459. const vector = array[ i ];
  3460. value[ index ] = vector.x;
  3461. value[ index + 1 ] = vector.y;
  3462. value[ index + 2 ] = vector.z || 0;
  3463. value[ index + 3 ] = vector.w || 0;
  3464. }
  3465. }
  3466. }
  3467. setup( builder ) {
  3468. const length = this.array.length;
  3469. this._elementType = this.elementType === null ? getValueType( this.array[ 0 ] ) : this.elementType;
  3470. this._elementLength = builder.getTypeLength( this._elementType );
  3471. let arrayType = Float32Array;
  3472. if ( this._elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  3473. else if ( this._elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  3474. this.value = new arrayType( length * 4 );
  3475. this.bufferCount = length;
  3476. this.bufferType = builder.changeComponentType( 'vec4', builder.getComponentType( this._elementType ) );
  3477. return super.setup( builder );
  3478. }
  3479. element( indexNode ) {
  3480. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  3481. }
  3482. }
  3483. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  3484. //
  3485. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  3486. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  3487. return nodeObject( new UniformArrayNode( values, nodeType ) );
  3488. };
  3489. class ReferenceElementNode extends ArrayElementNode {
  3490. static get type() {
  3491. return 'ReferenceElementNode';
  3492. }
  3493. constructor( referenceNode, indexNode ) {
  3494. super( referenceNode, indexNode );
  3495. this.referenceNode = referenceNode;
  3496. this.isReferenceElementNode = true;
  3497. }
  3498. getNodeType() {
  3499. return this.referenceNode.uniformType;
  3500. }
  3501. generate( builder ) {
  3502. const snippet = super.generate( builder );
  3503. const arrayType = this.referenceNode.getNodeType();
  3504. const elementType = this.getNodeType();
  3505. return builder.format( snippet, arrayType, elementType );
  3506. }
  3507. }
  3508. // TODO: Extends this from ReferenceBaseNode
  3509. class ReferenceNode extends Node {
  3510. static get type() {
  3511. return 'ReferenceNode';
  3512. }
  3513. constructor( property, uniformType, object = null, count = null ) {
  3514. super();
  3515. this.property = property;
  3516. this.uniformType = uniformType;
  3517. this.object = object;
  3518. this.count = count;
  3519. this.properties = property.split( '.' );
  3520. this.reference = object;
  3521. this.node = null;
  3522. this.group = null;
  3523. this.name = null;
  3524. this.updateType = NodeUpdateType.OBJECT;
  3525. }
  3526. element( indexNode ) {
  3527. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  3528. }
  3529. setGroup( group ) {
  3530. this.group = group;
  3531. return this;
  3532. }
  3533. label( name ) {
  3534. this.name = name;
  3535. return this;
  3536. }
  3537. setNodeType( uniformType ) {
  3538. let node = null;
  3539. if ( this.count !== null ) {
  3540. node = buffer( null, uniformType, this.count );
  3541. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  3542. node = uniformArray( null, uniformType );
  3543. } else if ( uniformType === 'texture' ) {
  3544. node = texture( null );
  3545. } else if ( uniformType === 'cubeTexture' ) {
  3546. node = cubeTexture( null );
  3547. } else {
  3548. node = uniform( null, uniformType );
  3549. }
  3550. if ( this.group !== null ) {
  3551. node.setGroup( this.group );
  3552. }
  3553. if ( this.name !== null ) node.label( this.name );
  3554. this.node = node.getSelf();
  3555. }
  3556. getNodeType( builder ) {
  3557. if ( this.node === null ) {
  3558. this.updateReference( builder );
  3559. this.updateValue();
  3560. }
  3561. return this.node.getNodeType( builder );
  3562. }
  3563. getValueFromReference( object = this.reference ) {
  3564. const { properties } = this;
  3565. let value = object[ properties[ 0 ] ];
  3566. for ( let i = 1; i < properties.length; i ++ ) {
  3567. value = value[ properties[ i ] ];
  3568. }
  3569. return value;
  3570. }
  3571. updateReference( state ) {
  3572. this.reference = this.object !== null ? this.object : state.object;
  3573. return this.reference;
  3574. }
  3575. setup() {
  3576. this.updateValue();
  3577. return this.node;
  3578. }
  3579. update( /*frame*/ ) {
  3580. this.updateValue();
  3581. }
  3582. updateValue() {
  3583. if ( this.node === null ) this.setNodeType( this.uniformType );
  3584. const value = this.getValueFromReference();
  3585. if ( Array.isArray( value ) ) {
  3586. this.node.array = value;
  3587. } else {
  3588. this.node.value = value;
  3589. }
  3590. }
  3591. }
  3592. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  3593. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  3594. class MaterialReferenceNode extends ReferenceNode {
  3595. static get type() {
  3596. return 'MaterialReferenceNode';
  3597. }
  3598. constructor( property, inputType, material = null ) {
  3599. super( property, inputType, material );
  3600. this.material = material;
  3601. //this.updateType = NodeUpdateType.RENDER;
  3602. this.isMaterialReferenceNode = true;
  3603. }
  3604. /*setNodeType( node ) {
  3605. super.setNodeType( node );
  3606. this.node.groupNode = renderGroup;
  3607. }*/
  3608. updateReference( state ) {
  3609. this.reference = this.material !== null ? this.material : state.material;
  3610. return this.reference;
  3611. }
  3612. }
  3613. const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  3614. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  3615. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  3616. builder.geometry.computeTangents();
  3617. }
  3618. return attribute( 'tangent', 'vec4' );
  3619. } )();
  3620. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  3621. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.varying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  3622. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).varying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  3623. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  3624. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  3625. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  3626. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  3627. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  3628. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  3629. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  3630. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  3631. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  3632. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  3633. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  3634. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  3635. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  3636. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  3637. let bentNormal = anisotropyB.cross( positionViewDirection );
  3638. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  3639. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  3640. return bentNormal;
  3641. } )();
  3642. // Normal Mapping Without Precomputed Tangents
  3643. // http://www.thetenthplanet.de/archives/1180
  3644. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  3645. const { eye_pos, surf_norm, mapN, uv } = inputs;
  3646. const q0 = eye_pos.dFdx();
  3647. const q1 = eye_pos.dFdy();
  3648. const st0 = uv.dFdx();
  3649. const st1 = uv.dFdy();
  3650. const N = surf_norm; // normalized
  3651. const q1perp = q1.cross( N );
  3652. const q0perp = N.cross( q0 );
  3653. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  3654. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  3655. const det = T.dot( T ).max( B.dot( B ) );
  3656. const scale = faceDirection.mul( det.inverseSqrt() );
  3657. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  3658. } );
  3659. class NormalMapNode extends TempNode {
  3660. static get type() {
  3661. return 'NormalMapNode';
  3662. }
  3663. constructor( node, scaleNode = null ) {
  3664. super( 'vec3' );
  3665. this.node = node;
  3666. this.scaleNode = scaleNode;
  3667. this.normalMapType = TangentSpaceNormalMap;
  3668. }
  3669. setup( builder ) {
  3670. const { normalMapType, scaleNode } = this;
  3671. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  3672. if ( scaleNode !== null ) {
  3673. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  3674. }
  3675. let outputNode = null;
  3676. if ( normalMapType === ObjectSpaceNormalMap ) {
  3677. outputNode = transformNormalToView( normalMap );
  3678. } else if ( normalMapType === TangentSpaceNormalMap ) {
  3679. const tangent = builder.hasGeometryAttribute( 'tangent' );
  3680. if ( tangent === true ) {
  3681. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  3682. } else {
  3683. outputNode = perturbNormal2Arb( {
  3684. eye_pos: positionView,
  3685. surf_norm: normalView,
  3686. mapN: normalMap,
  3687. uv: uv()
  3688. } );
  3689. }
  3690. }
  3691. return outputNode;
  3692. }
  3693. }
  3694. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  3695. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  3696. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  3697. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  3698. // It's used to preserve the same TextureNode instance
  3699. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  3700. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  3701. return vec2(
  3702. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  3703. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  3704. ).mul( bumpScale );
  3705. } );
  3706. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  3707. const perturbNormalArb = Fn( ( inputs ) => {
  3708. const { surf_pos, surf_norm, dHdxy } = inputs;
  3709. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  3710. const vSigmaX = surf_pos.dFdx().normalize();
  3711. const vSigmaY = surf_pos.dFdy().normalize();
  3712. const vN = surf_norm; // normalized
  3713. const R1 = vSigmaY.cross( vN );
  3714. const R2 = vN.cross( vSigmaX );
  3715. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  3716. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  3717. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  3718. } );
  3719. class BumpMapNode extends TempNode {
  3720. static get type() {
  3721. return 'BumpMapNode';
  3722. }
  3723. constructor( textureNode, scaleNode = null ) {
  3724. super( 'vec3' );
  3725. this.textureNode = textureNode;
  3726. this.scaleNode = scaleNode;
  3727. }
  3728. setup() {
  3729. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  3730. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  3731. return perturbNormalArb( {
  3732. surf_pos: positionView,
  3733. surf_norm: normalView,
  3734. dHdxy
  3735. } );
  3736. }
  3737. }
  3738. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  3739. const _propertyCache = new Map();
  3740. class MaterialNode extends Node {
  3741. static get type() {
  3742. return 'MaterialNode';
  3743. }
  3744. constructor( scope ) {
  3745. super();
  3746. this.scope = scope;
  3747. }
  3748. getCache( property, type ) {
  3749. let node = _propertyCache.get( property );
  3750. if ( node === undefined ) {
  3751. node = materialReference( property, type );
  3752. _propertyCache.set( property, node );
  3753. }
  3754. return node;
  3755. }
  3756. getFloat( property ) {
  3757. return this.getCache( property, 'float' );
  3758. }
  3759. getColor( property ) {
  3760. return this.getCache( property, 'color' );
  3761. }
  3762. getTexture( property ) {
  3763. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  3764. }
  3765. setup( builder ) {
  3766. const material = builder.context.material;
  3767. const scope = this.scope;
  3768. let node = null;
  3769. if ( scope === MaterialNode.COLOR ) {
  3770. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  3771. if ( material.map && material.map.isTexture === true ) {
  3772. node = colorNode.mul( this.getTexture( 'map' ) );
  3773. } else {
  3774. node = colorNode;
  3775. }
  3776. } else if ( scope === MaterialNode.OPACITY ) {
  3777. const opacityNode = this.getFloat( scope );
  3778. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  3779. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  3780. } else {
  3781. node = opacityNode;
  3782. }
  3783. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  3784. if ( material.specularMap && material.specularMap.isTexture === true ) {
  3785. node = this.getTexture( 'specular' ).r;
  3786. } else {
  3787. node = float( 1 );
  3788. }
  3789. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  3790. const specularIntensity = this.getFloat( scope );
  3791. if ( material.specularMap ) {
  3792. node = specularIntensity.mul( this.getTexture( scope ).a );
  3793. } else {
  3794. node = specularIntensity;
  3795. }
  3796. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  3797. const specularColorNode = this.getColor( scope );
  3798. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  3799. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  3800. } else {
  3801. node = specularColorNode;
  3802. }
  3803. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  3804. const roughnessNode = this.getFloat( scope );
  3805. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  3806. node = roughnessNode.mul( this.getTexture( scope ).g );
  3807. } else {
  3808. node = roughnessNode;
  3809. }
  3810. } else if ( scope === MaterialNode.METALNESS ) {
  3811. const metalnessNode = this.getFloat( scope );
  3812. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  3813. node = metalnessNode.mul( this.getTexture( scope ).b );
  3814. } else {
  3815. node = metalnessNode;
  3816. }
  3817. } else if ( scope === MaterialNode.EMISSIVE ) {
  3818. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  3819. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  3820. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  3821. node = emissiveNode.mul( this.getTexture( scope ) );
  3822. } else {
  3823. node = emissiveNode;
  3824. }
  3825. } else if ( scope === MaterialNode.NORMAL ) {
  3826. if ( material.normalMap ) {
  3827. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  3828. node.normalMapType = material.normalMapType;
  3829. } else if ( material.bumpMap ) {
  3830. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  3831. } else {
  3832. node = normalView;
  3833. }
  3834. } else if ( scope === MaterialNode.CLEARCOAT ) {
  3835. const clearcoatNode = this.getFloat( scope );
  3836. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  3837. node = clearcoatNode.mul( this.getTexture( scope ).r );
  3838. } else {
  3839. node = clearcoatNode;
  3840. }
  3841. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  3842. const clearcoatRoughnessNode = this.getFloat( scope );
  3843. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  3844. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  3845. } else {
  3846. node = clearcoatRoughnessNode;
  3847. }
  3848. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  3849. if ( material.clearcoatNormalMap ) {
  3850. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  3851. } else {
  3852. node = normalView;
  3853. }
  3854. } else if ( scope === MaterialNode.SHEEN ) {
  3855. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  3856. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  3857. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  3858. } else {
  3859. node = sheenNode;
  3860. }
  3861. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  3862. const sheenRoughnessNode = this.getFloat( scope );
  3863. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  3864. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  3865. } else {
  3866. node = sheenRoughnessNode;
  3867. }
  3868. node = node.clamp( 0.07, 1.0 );
  3869. } else if ( scope === MaterialNode.ANISOTROPY ) {
  3870. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  3871. const anisotropyPolar = this.getTexture( scope );
  3872. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  3873. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  3874. } else {
  3875. node = materialAnisotropyVector;
  3876. }
  3877. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  3878. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  3879. if ( material.iridescenceThicknessMap ) {
  3880. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  3881. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  3882. } else {
  3883. node = iridescenceThicknessMaximum;
  3884. }
  3885. } else if ( scope === MaterialNode.TRANSMISSION ) {
  3886. const transmissionNode = this.getFloat( scope );
  3887. if ( material.transmissionMap ) {
  3888. node = transmissionNode.mul( this.getTexture( scope ).r );
  3889. } else {
  3890. node = transmissionNode;
  3891. }
  3892. } else if ( scope === MaterialNode.THICKNESS ) {
  3893. const thicknessNode = this.getFloat( scope );
  3894. if ( material.thicknessMap ) {
  3895. node = thicknessNode.mul( this.getTexture( scope ).g );
  3896. } else {
  3897. node = thicknessNode;
  3898. }
  3899. } else if ( scope === MaterialNode.IOR ) {
  3900. node = this.getFloat( scope );
  3901. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  3902. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  3903. } else if ( scope === MaterialNode.AO_MAP ) {
  3904. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  3905. } else {
  3906. const outputType = this.getNodeType( builder );
  3907. node = this.getCache( scope, outputType );
  3908. }
  3909. return node;
  3910. }
  3911. }
  3912. MaterialNode.ALPHA_TEST = 'alphaTest';
  3913. MaterialNode.COLOR = 'color';
  3914. MaterialNode.OPACITY = 'opacity';
  3915. MaterialNode.SHININESS = 'shininess';
  3916. MaterialNode.SPECULAR = 'specular';
  3917. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  3918. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  3919. MaterialNode.SPECULAR_COLOR = 'specularColor';
  3920. MaterialNode.REFLECTIVITY = 'reflectivity';
  3921. MaterialNode.ROUGHNESS = 'roughness';
  3922. MaterialNode.METALNESS = 'metalness';
  3923. MaterialNode.NORMAL = 'normal';
  3924. MaterialNode.CLEARCOAT = 'clearcoat';
  3925. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  3926. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  3927. MaterialNode.EMISSIVE = 'emissive';
  3928. MaterialNode.ROTATION = 'rotation';
  3929. MaterialNode.SHEEN = 'sheen';
  3930. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  3931. MaterialNode.ANISOTROPY = 'anisotropy';
  3932. MaterialNode.IRIDESCENCE = 'iridescence';
  3933. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  3934. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  3935. MaterialNode.IOR = 'ior';
  3936. MaterialNode.TRANSMISSION = 'transmission';
  3937. MaterialNode.THICKNESS = 'thickness';
  3938. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  3939. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  3940. MaterialNode.LINE_SCALE = 'scale';
  3941. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  3942. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  3943. MaterialNode.LINE_WIDTH = 'linewidth';
  3944. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  3945. MaterialNode.POINT_WIDTH = 'pointWidth';
  3946. MaterialNode.DISPERSION = 'dispersion';
  3947. MaterialNode.LIGHT_MAP = 'light';
  3948. MaterialNode.AO_MAP = 'ao';
  3949. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  3950. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  3951. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  3952. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  3953. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  3954. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  3955. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  3956. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  3957. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  3958. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  3959. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  3960. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  3961. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL ).context( { getUV: null } );
  3962. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  3963. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  3964. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL ).context( { getUV: null } );
  3965. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  3966. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  3967. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  3968. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  3969. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  3970. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  3971. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  3972. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  3973. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  3974. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  3975. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  3976. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  3977. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  3978. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  3979. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  3980. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  3981. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  3982. const materialPointWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_WIDTH );
  3983. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  3984. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  3985. const materialAOMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO_MAP );
  3986. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  3987. return frame.material;
  3988. } ).onRenderUpdate( function ( { material } ) {
  3989. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  3990. } );
  3991. class ModelViewProjectionNode extends TempNode {
  3992. static get type() {
  3993. return 'ModelViewProjectionNode';
  3994. }
  3995. constructor( positionNode = null ) {
  3996. super( 'vec4' );
  3997. this.positionNode = positionNode;
  3998. }
  3999. setup( builder ) {
  4000. if ( builder.shaderStage === 'fragment' ) {
  4001. return varying( builder.context.mvp );
  4002. }
  4003. const position = this.positionNode || positionLocal;
  4004. const viewMatrix = builder.renderer.nodes.modelViewMatrix || modelViewMatrix;
  4005. return cameraProjectionMatrix.mul( viewMatrix ).mul( position );
  4006. }
  4007. }
  4008. const modelViewProjection = /*@__PURE__*/ nodeProxy( ModelViewProjectionNode );
  4009. class IndexNode extends Node {
  4010. static get type() {
  4011. return 'IndexNode';
  4012. }
  4013. constructor( scope ) {
  4014. super( 'uint' );
  4015. this.scope = scope;
  4016. this.isInstanceIndexNode = true;
  4017. }
  4018. generate( builder ) {
  4019. const nodeType = this.getNodeType( builder );
  4020. const scope = this.scope;
  4021. let propertyName;
  4022. if ( scope === IndexNode.VERTEX ) {
  4023. // The index of a vertex within a mesh.
  4024. propertyName = builder.getVertexIndex();
  4025. } else if ( scope === IndexNode.INSTANCE ) {
  4026. // The index of either a mesh instance or an invocation of a compute shader.
  4027. propertyName = builder.getInstanceIndex();
  4028. } else if ( scope === IndexNode.DRAW ) {
  4029. // The index of a draw call.
  4030. propertyName = builder.getDrawIndex();
  4031. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  4032. // The index of a compute invocation within the scope of a workgroup load.
  4033. propertyName = builder.getInvocationLocalIndex();
  4034. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  4035. // The index of a compute invocation within the scope of a subgroup.
  4036. propertyName = builder.getInvocationSubgroupIndex();
  4037. } else if ( scope === IndexNode.SUBGROUP ) {
  4038. // The index of the subgroup the current compute invocation belongs to.
  4039. propertyName = builder.getSubgroupIndex();
  4040. } else {
  4041. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  4042. }
  4043. let output;
  4044. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  4045. output = propertyName;
  4046. } else {
  4047. const nodeVarying = varying( this );
  4048. output = nodeVarying.build( builder, nodeType );
  4049. }
  4050. return output;
  4051. }
  4052. }
  4053. IndexNode.VERTEX = 'vertex';
  4054. IndexNode.INSTANCE = 'instance';
  4055. IndexNode.SUBGROUP = 'subgroup';
  4056. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  4057. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  4058. IndexNode.DRAW = 'draw';
  4059. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  4060. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  4061. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  4062. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  4063. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  4064. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  4065. class InstanceNode extends Node {
  4066. static get type() {
  4067. return 'InstanceNode';
  4068. }
  4069. constructor( count, instanceMatrix, instanceColor ) {
  4070. super( 'void' );
  4071. this.count = count;
  4072. this.instanceMatrix = instanceMatrix;
  4073. this.instanceColor = instanceColor;
  4074. this.instanceMatrixNode = null;
  4075. this.instanceColorNode = null;
  4076. this.updateType = NodeUpdateType.FRAME;
  4077. this.buffer = null;
  4078. this.bufferColor = null;
  4079. }
  4080. setup( builder ) {
  4081. const { count, instanceMatrix, instanceColor } = this;
  4082. let { instanceMatrixNode, instanceColorNode } = this;
  4083. if ( instanceMatrixNode === null ) {
  4084. // 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.
  4085. if ( count <= 1000 ) {
  4086. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  4087. } else {
  4088. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  4089. this.buffer = buffer;
  4090. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  4091. const instanceBuffers = [
  4092. // F.Signature -> bufferAttribute( array, type, stride, offset )
  4093. bufferFn( buffer, 'vec4', 16, 0 ),
  4094. bufferFn( buffer, 'vec4', 16, 4 ),
  4095. bufferFn( buffer, 'vec4', 16, 8 ),
  4096. bufferFn( buffer, 'vec4', 16, 12 )
  4097. ];
  4098. instanceMatrixNode = mat4( ...instanceBuffers );
  4099. }
  4100. this.instanceMatrixNode = instanceMatrixNode;
  4101. }
  4102. if ( instanceColor && instanceColorNode === null ) {
  4103. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  4104. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  4105. this.bufferColor = buffer;
  4106. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  4107. this.instanceColorNode = instanceColorNode;
  4108. }
  4109. // POSITION
  4110. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  4111. positionLocal.assign( instancePosition );
  4112. // NORMAL
  4113. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  4114. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  4115. // ASSIGNS
  4116. normalLocal.assign( instanceNormal );
  4117. }
  4118. // COLOR
  4119. if ( this.instanceColorNode !== null ) {
  4120. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  4121. }
  4122. }
  4123. update( /*frame*/ ) {
  4124. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer != null && this.instanceMatrix.version !== this.buffer.version ) {
  4125. this.buffer.version = this.instanceMatrix.version;
  4126. }
  4127. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor != null && this.instanceColor.version !== this.bufferColor.version ) {
  4128. this.bufferColor.version = this.instanceColor.version;
  4129. }
  4130. }
  4131. }
  4132. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  4133. class InstancedMeshNode extends InstanceNode {
  4134. static get type() {
  4135. return 'InstancedMeshNode';
  4136. }
  4137. constructor( instanceMesh ) {
  4138. const { count, instanceMatrix, instanceColor } = instanceMesh;
  4139. super( count, instanceMatrix, instanceColor );
  4140. this.instanceMesh = instanceMesh;
  4141. }
  4142. }
  4143. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode );
  4144. class BatchNode extends Node {
  4145. static get type() {
  4146. return 'BatchNode';
  4147. }
  4148. constructor( batchMesh ) {
  4149. super( 'void' );
  4150. this.batchMesh = batchMesh;
  4151. this.batchingIdNode = null;
  4152. }
  4153. setup( builder ) {
  4154. // POSITION
  4155. if ( this.batchingIdNode === null ) {
  4156. if ( builder.getDrawIndex() === null ) {
  4157. this.batchingIdNode = instanceIndex;
  4158. } else {
  4159. this.batchingIdNode = drawIndex;
  4160. }
  4161. }
  4162. const getIndirectIndex = Fn( ( [ id ] ) => {
  4163. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  4164. const x = int( id ).modInt( int( size ) );
  4165. const y = int( id ).div( int( size ) );
  4166. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  4167. } ).setLayout( {
  4168. name: 'getIndirectIndex',
  4169. type: 'uint',
  4170. inputs: [
  4171. { name: 'id', type: 'int' }
  4172. ]
  4173. } );
  4174. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  4175. const matricesTexture = this.batchMesh._matricesTexture;
  4176. const size = textureSize( textureLoad( matricesTexture ), 0 );
  4177. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  4178. const x = j.modInt( size );
  4179. const y = j.div( int( size ) );
  4180. const batchingMatrix = mat4(
  4181. textureLoad( matricesTexture, ivec2( x, y ) ),
  4182. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  4183. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  4184. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  4185. );
  4186. const colorsTexture = this.batchMesh._colorsTexture;
  4187. if ( colorsTexture !== null ) {
  4188. const getBatchingColor = Fn( ( [ id ] ) => {
  4189. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  4190. const j = id;
  4191. const x = j.modInt( size );
  4192. const y = j.div( size );
  4193. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  4194. } ).setLayout( {
  4195. name: 'getBatchingColor',
  4196. type: 'vec3',
  4197. inputs: [
  4198. { name: 'id', type: 'int' }
  4199. ]
  4200. } );
  4201. const color = getBatchingColor( indirectId );
  4202. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  4203. }
  4204. const bm = mat3( batchingMatrix );
  4205. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  4206. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  4207. const batchingNormal = bm.mul( transformedNormal ).xyz;
  4208. normalLocal.assign( batchingNormal );
  4209. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  4210. tangentLocal.mulAssign( bm );
  4211. }
  4212. }
  4213. }
  4214. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  4215. const _frameId = new WeakMap();
  4216. class SkinningNode extends Node {
  4217. static get type() {
  4218. return 'SkinningNode';
  4219. }
  4220. constructor( skinnedMesh, useReference = false ) {
  4221. super( 'void' );
  4222. this.skinnedMesh = skinnedMesh;
  4223. this.useReference = useReference;
  4224. this.updateType = NodeUpdateType.OBJECT;
  4225. //
  4226. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  4227. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  4228. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  4229. if ( useReference ) {
  4230. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  4231. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  4232. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  4233. } else {
  4234. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  4235. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  4236. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  4237. }
  4238. this.bindMatrixNode = bindMatrixNode;
  4239. this.bindMatrixInverseNode = bindMatrixInverseNode;
  4240. this.boneMatricesNode = boneMatricesNode;
  4241. this.previousBoneMatricesNode = null;
  4242. }
  4243. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  4244. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  4245. const boneMatX = boneMatrices.element( skinIndexNode.x );
  4246. const boneMatY = boneMatrices.element( skinIndexNode.y );
  4247. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  4248. const boneMatW = boneMatrices.element( skinIndexNode.w );
  4249. // POSITION
  4250. const skinVertex = bindMatrixNode.mul( position );
  4251. const skinned = add(
  4252. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  4253. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  4254. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  4255. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  4256. );
  4257. return bindMatrixInverseNode.mul( skinned ).xyz;
  4258. }
  4259. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  4260. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  4261. const boneMatX = boneMatrices.element( skinIndexNode.x );
  4262. const boneMatY = boneMatrices.element( skinIndexNode.y );
  4263. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  4264. const boneMatW = boneMatrices.element( skinIndexNode.w );
  4265. // NORMAL
  4266. let skinMatrix = add(
  4267. skinWeightNode.x.mul( boneMatX ),
  4268. skinWeightNode.y.mul( boneMatY ),
  4269. skinWeightNode.z.mul( boneMatZ ),
  4270. skinWeightNode.w.mul( boneMatW )
  4271. );
  4272. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  4273. return skinMatrix.transformDirection( normal ).xyz;
  4274. }
  4275. getPreviousSkinnedPosition( builder ) {
  4276. const skinnedMesh = builder.object;
  4277. if ( this.previousBoneMatricesNode === null ) {
  4278. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  4279. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  4280. }
  4281. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  4282. }
  4283. needsPreviousBoneMatrices( builder ) {
  4284. const mrt = builder.renderer.getMRT();
  4285. return mrt && mrt.has( 'velocity' );
  4286. }
  4287. setup( builder ) {
  4288. if ( this.needsPreviousBoneMatrices( builder ) ) {
  4289. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  4290. }
  4291. const skinPosition = this.getSkinnedPosition();
  4292. positionLocal.assign( skinPosition );
  4293. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  4294. const skinNormal = this.getSkinnedNormal();
  4295. normalLocal.assign( skinNormal );
  4296. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  4297. tangentLocal.assign( skinNormal );
  4298. }
  4299. }
  4300. }
  4301. generate( builder, output ) {
  4302. if ( output !== 'void' ) {
  4303. return positionLocal.build( builder, output );
  4304. }
  4305. }
  4306. update( frame ) {
  4307. const object = this.useReference ? frame.object : this.skinnedMesh;
  4308. const skeleton = object.skeleton;
  4309. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  4310. _frameId.set( skeleton, frame.frameId );
  4311. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  4312. skeleton.update();
  4313. }
  4314. }
  4315. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  4316. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  4317. class LoopNode extends Node {
  4318. static get type() {
  4319. return 'LoopNode';
  4320. }
  4321. constructor( params = [] ) {
  4322. super();
  4323. this.params = params;
  4324. }
  4325. getVarName( index ) {
  4326. return String.fromCharCode( 'i'.charCodeAt() + index );
  4327. }
  4328. getProperties( builder ) {
  4329. const properties = builder.getNodeProperties( this );
  4330. if ( properties.stackNode !== undefined ) return properties;
  4331. //
  4332. const inputs = {};
  4333. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  4334. const param = this.params[ i ];
  4335. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  4336. const type = ( param.isNode !== true && param.type ) || 'int';
  4337. inputs[ name ] = expression( name, type );
  4338. }
  4339. const stack = builder.addStack(); // TODO: cache() it
  4340. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  4341. properties.stackNode = stack;
  4342. builder.removeStack();
  4343. return properties;
  4344. }
  4345. getNodeType( builder ) {
  4346. const { returnsNode } = this.getProperties( builder );
  4347. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  4348. }
  4349. setup( builder ) {
  4350. // setup properties
  4351. this.getProperties( builder );
  4352. }
  4353. generate( builder ) {
  4354. const properties = this.getProperties( builder );
  4355. const params = this.params;
  4356. const stackNode = properties.stackNode;
  4357. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  4358. const param = params[ i ];
  4359. let start = null, end = null, name = null, type = null, condition = null, update = null;
  4360. if ( param.isNode ) {
  4361. type = 'int';
  4362. name = this.getVarName( i );
  4363. start = '0';
  4364. end = param.build( builder, type );
  4365. condition = '<';
  4366. } else {
  4367. type = param.type || 'int';
  4368. name = param.name || this.getVarName( i );
  4369. start = param.start;
  4370. end = param.end;
  4371. condition = param.condition;
  4372. update = param.update;
  4373. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  4374. else if ( start && start.isNode ) start = start.build( builder, type );
  4375. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  4376. else if ( end && end.isNode ) end = end.build( builder, type );
  4377. if ( start !== undefined && end === undefined ) {
  4378. start = start + ' - 1';
  4379. end = '0';
  4380. condition = '>=';
  4381. } else if ( end !== undefined && start === undefined ) {
  4382. start = '0';
  4383. condition = '<';
  4384. }
  4385. if ( condition === undefined ) {
  4386. if ( Number( start ) > Number( end ) ) {
  4387. condition = '>=';
  4388. } else {
  4389. condition = '<';
  4390. }
  4391. }
  4392. }
  4393. const internalParam = { start, end, condition };
  4394. //
  4395. const startSnippet = internalParam.start;
  4396. const endSnippet = internalParam.end;
  4397. let declarationSnippet = '';
  4398. let conditionalSnippet = '';
  4399. let updateSnippet = '';
  4400. if ( ! update ) {
  4401. if ( type === 'int' || type === 'uint' ) {
  4402. if ( condition.includes( '<' ) ) update = '++';
  4403. else update = '--';
  4404. } else {
  4405. if ( condition.includes( '<' ) ) update = '+= 1.';
  4406. else update = '-= 1.';
  4407. }
  4408. }
  4409. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  4410. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  4411. updateSnippet += name + ' ' + update;
  4412. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  4413. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  4414. }
  4415. const stackSnippet = stackNode.build( builder, 'void' );
  4416. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  4417. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  4418. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  4419. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  4420. }
  4421. builder.addFlowTab();
  4422. return returnsSnippet;
  4423. }
  4424. }
  4425. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  4426. const Continue = () => expression( 'continue' ).append();
  4427. const Break = () => expression( 'break' ).append();
  4428. //
  4429. const loop = ( ...params ) => { // @deprecated, r168
  4430. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  4431. return Loop( ...params );
  4432. };
  4433. const _morphTextures = /*@__PURE__*/ new WeakMap();
  4434. const _morphVec4 = /*@__PURE__*/ new Vector4();
  4435. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  4436. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  4437. const y = texelIndex.div( width );
  4438. const x = texelIndex.sub( y.mul( width ) );
  4439. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  4440. return bufferAttrib.mul( influence );
  4441. } );
  4442. function getEntry( geometry ) {
  4443. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  4444. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  4445. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  4446. // instead of using attributes, the WebGL 2 code path encodes morph targets
  4447. // into an array of data textures. Each layer represents a single morph target.
  4448. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  4449. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  4450. let entry = _morphTextures.get( geometry );
  4451. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  4452. if ( entry !== undefined ) entry.texture.dispose();
  4453. const morphTargets = geometry.morphAttributes.position || [];
  4454. const morphNormals = geometry.morphAttributes.normal || [];
  4455. const morphColors = geometry.morphAttributes.color || [];
  4456. let vertexDataCount = 0;
  4457. if ( hasMorphPosition === true ) vertexDataCount = 1;
  4458. if ( hasMorphNormals === true ) vertexDataCount = 2;
  4459. if ( hasMorphColors === true ) vertexDataCount = 3;
  4460. let width = geometry.attributes.position.count * vertexDataCount;
  4461. let height = 1;
  4462. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  4463. if ( width > maxTextureSize ) {
  4464. height = Math.ceil( width / maxTextureSize );
  4465. width = maxTextureSize;
  4466. }
  4467. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  4468. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  4469. bufferTexture.type = FloatType;
  4470. bufferTexture.needsUpdate = true;
  4471. // fill buffer
  4472. const vertexDataStride = vertexDataCount * 4;
  4473. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  4474. const morphTarget = morphTargets[ i ];
  4475. const morphNormal = morphNormals[ i ];
  4476. const morphColor = morphColors[ i ];
  4477. const offset = width * height * 4 * i;
  4478. for ( let j = 0; j < morphTarget.count; j ++ ) {
  4479. const stride = j * vertexDataStride;
  4480. if ( hasMorphPosition === true ) {
  4481. _morphVec4.fromBufferAttribute( morphTarget, j );
  4482. buffer[ offset + stride + 0 ] = _morphVec4.x;
  4483. buffer[ offset + stride + 1 ] = _morphVec4.y;
  4484. buffer[ offset + stride + 2 ] = _morphVec4.z;
  4485. buffer[ offset + stride + 3 ] = 0;
  4486. }
  4487. if ( hasMorphNormals === true ) {
  4488. _morphVec4.fromBufferAttribute( morphNormal, j );
  4489. buffer[ offset + stride + 4 ] = _morphVec4.x;
  4490. buffer[ offset + stride + 5 ] = _morphVec4.y;
  4491. buffer[ offset + stride + 6 ] = _morphVec4.z;
  4492. buffer[ offset + stride + 7 ] = 0;
  4493. }
  4494. if ( hasMorphColors === true ) {
  4495. _morphVec4.fromBufferAttribute( morphColor, j );
  4496. buffer[ offset + stride + 8 ] = _morphVec4.x;
  4497. buffer[ offset + stride + 9 ] = _morphVec4.y;
  4498. buffer[ offset + stride + 10 ] = _morphVec4.z;
  4499. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  4500. }
  4501. }
  4502. }
  4503. entry = {
  4504. count: morphTargetsCount,
  4505. texture: bufferTexture,
  4506. stride: vertexDataCount,
  4507. size: new Vector2( width, height )
  4508. };
  4509. _morphTextures.set( geometry, entry );
  4510. function disposeTexture() {
  4511. bufferTexture.dispose();
  4512. _morphTextures.delete( geometry );
  4513. geometry.removeEventListener( 'dispose', disposeTexture );
  4514. }
  4515. geometry.addEventListener( 'dispose', disposeTexture );
  4516. }
  4517. return entry;
  4518. }
  4519. class MorphNode extends Node {
  4520. static get type() {
  4521. return 'MorphNode';
  4522. }
  4523. constructor( mesh ) {
  4524. super( 'void' );
  4525. this.mesh = mesh;
  4526. this.morphBaseInfluence = uniform( 1 );
  4527. this.updateType = NodeUpdateType.OBJECT;
  4528. }
  4529. setup( builder ) {
  4530. const { geometry } = builder;
  4531. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  4532. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  4533. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  4534. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  4535. // nodes
  4536. const { texture: bufferMap, stride, size } = getEntry( geometry );
  4537. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  4538. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  4539. const width = int( size.width );
  4540. Loop( morphTargetsCount, ( { i } ) => {
  4541. const influence = float( 0 ).toVar();
  4542. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  4543. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  4544. } else {
  4545. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  4546. }
  4547. if ( hasMorphPosition === true ) {
  4548. positionLocal.addAssign( getMorph( {
  4549. bufferMap,
  4550. influence,
  4551. stride,
  4552. width,
  4553. depth: i,
  4554. offset: int( 0 )
  4555. } ) );
  4556. }
  4557. if ( hasMorphNormals === true ) {
  4558. normalLocal.addAssign( getMorph( {
  4559. bufferMap,
  4560. influence,
  4561. stride,
  4562. width,
  4563. depth: i,
  4564. offset: int( 1 )
  4565. } ) );
  4566. }
  4567. } );
  4568. }
  4569. update() {
  4570. const morphBaseInfluence = this.morphBaseInfluence;
  4571. if ( this.mesh.geometry.morphTargetsRelative ) {
  4572. morphBaseInfluence.value = 1;
  4573. } else {
  4574. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  4575. }
  4576. }
  4577. }
  4578. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  4579. class LightingNode extends Node {
  4580. static get type() {
  4581. return 'LightingNode';
  4582. }
  4583. constructor() {
  4584. super( 'vec3' );
  4585. this.isLightingNode = true;
  4586. }
  4587. generate( /*builder*/ ) {
  4588. console.warn( 'Abstract function.' );
  4589. }
  4590. }
  4591. class AONode extends LightingNode {
  4592. static get type() {
  4593. return 'AONode';
  4594. }
  4595. constructor( aoNode = null ) {
  4596. super();
  4597. this.aoNode = aoNode;
  4598. }
  4599. setup( builder ) {
  4600. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  4601. }
  4602. }
  4603. class LightingContextNode extends ContextNode {
  4604. static get type() {
  4605. return 'LightingContextNode';
  4606. }
  4607. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  4608. super( node );
  4609. this.lightingModel = lightingModel;
  4610. this.backdropNode = backdropNode;
  4611. this.backdropAlphaNode = backdropAlphaNode;
  4612. this._value = null;
  4613. }
  4614. getContext() {
  4615. const { backdropNode, backdropAlphaNode } = this;
  4616. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  4617. directSpecular = vec3().toVar( 'directSpecular' ),
  4618. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  4619. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  4620. const reflectedLight = {
  4621. directDiffuse,
  4622. directSpecular,
  4623. indirectDiffuse,
  4624. indirectSpecular
  4625. };
  4626. const context = {
  4627. radiance: vec3().toVar( 'radiance' ),
  4628. irradiance: vec3().toVar( 'irradiance' ),
  4629. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  4630. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  4631. reflectedLight,
  4632. backdrop: backdropNode,
  4633. backdropAlpha: backdropAlphaNode
  4634. };
  4635. return context;
  4636. }
  4637. setup( builder ) {
  4638. this.value = this._value || ( this._value = this.getContext() );
  4639. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  4640. return super.setup( builder );
  4641. }
  4642. }
  4643. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  4644. class IrradianceNode extends LightingNode {
  4645. static get type() {
  4646. return 'IrradianceNode';
  4647. }
  4648. constructor( node ) {
  4649. super();
  4650. this.node = node;
  4651. }
  4652. setup( builder ) {
  4653. builder.context.irradiance.addAssign( this.node );
  4654. }
  4655. }
  4656. let screenSizeVec, viewportVec;
  4657. class ScreenNode extends Node {
  4658. static get type() {
  4659. return 'ScreenNode';
  4660. }
  4661. constructor( scope ) {
  4662. super();
  4663. this.scope = scope;
  4664. this.isViewportNode = true;
  4665. }
  4666. getNodeType() {
  4667. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  4668. else return 'vec2';
  4669. }
  4670. getUpdateType() {
  4671. let updateType = NodeUpdateType.NONE;
  4672. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  4673. updateType = NodeUpdateType.RENDER;
  4674. }
  4675. this.updateType = updateType;
  4676. return updateType;
  4677. }
  4678. update( { renderer } ) {
  4679. const renderTarget = renderer.getRenderTarget();
  4680. if ( this.scope === ScreenNode.VIEWPORT ) {
  4681. if ( renderTarget !== null ) {
  4682. viewportVec.copy( renderTarget.viewport );
  4683. } else {
  4684. renderer.getViewport( viewportVec );
  4685. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  4686. }
  4687. } else {
  4688. if ( renderTarget !== null ) {
  4689. screenSizeVec.width = renderTarget.width;
  4690. screenSizeVec.height = renderTarget.height;
  4691. } else {
  4692. renderer.getDrawingBufferSize( screenSizeVec );
  4693. }
  4694. }
  4695. }
  4696. setup( /*builder*/ ) {
  4697. const scope = this.scope;
  4698. let output = null;
  4699. if ( scope === ScreenNode.SIZE ) {
  4700. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  4701. } else if ( scope === ScreenNode.VIEWPORT ) {
  4702. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  4703. } else {
  4704. output = vec2( screenCoordinate.div( screenSize ) );
  4705. }
  4706. return output;
  4707. }
  4708. generate( builder ) {
  4709. if ( this.scope === ScreenNode.COORDINATE ) {
  4710. let coord = builder.getFragCoord();
  4711. if ( builder.isFlipY() ) {
  4712. // follow webgpu standards
  4713. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  4714. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  4715. }
  4716. return coord;
  4717. }
  4718. return super.generate( builder );
  4719. }
  4720. }
  4721. ScreenNode.COORDINATE = 'coordinate';
  4722. ScreenNode.VIEWPORT = 'viewport';
  4723. ScreenNode.SIZE = 'size';
  4724. ScreenNode.UV = 'uv';
  4725. // Screen
  4726. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  4727. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  4728. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  4729. // Viewport
  4730. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  4731. const viewportSize = viewport.zw;
  4732. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  4733. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  4734. // Deprecated
  4735. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  4736. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  4737. return screenSize;
  4738. }, 'vec2' ).once() )();
  4739. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  4740. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  4741. return screenUV;
  4742. }, 'vec2' ).once() )();
  4743. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  4744. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  4745. return screenUV.flipY();
  4746. }, 'vec2' ).once() )();
  4747. const _size$4 = /*@__PURE__*/ new Vector2();
  4748. class ViewportTextureNode extends TextureNode {
  4749. static get type() {
  4750. return 'ViewportTextureNode';
  4751. }
  4752. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  4753. if ( framebufferTexture === null ) {
  4754. framebufferTexture = new FramebufferTexture();
  4755. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  4756. }
  4757. super( framebufferTexture, uvNode, levelNode );
  4758. this.generateMipmaps = false;
  4759. this.isOutputTextureNode = true;
  4760. this.updateBeforeType = NodeUpdateType.FRAME;
  4761. }
  4762. updateBefore( frame ) {
  4763. const renderer = frame.renderer;
  4764. renderer.getDrawingBufferSize( _size$4 );
  4765. //
  4766. const framebufferTexture = this.value;
  4767. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  4768. framebufferTexture.image.width = _size$4.width;
  4769. framebufferTexture.image.height = _size$4.height;
  4770. framebufferTexture.needsUpdate = true;
  4771. }
  4772. //
  4773. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  4774. framebufferTexture.generateMipmaps = this.generateMipmaps;
  4775. renderer.copyFramebufferToTexture( framebufferTexture );
  4776. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  4777. }
  4778. clone() {
  4779. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  4780. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  4781. return viewportTextureNode;
  4782. }
  4783. }
  4784. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  4785. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  4786. let sharedDepthbuffer = null;
  4787. class ViewportDepthTextureNode extends ViewportTextureNode {
  4788. static get type() {
  4789. return 'ViewportDepthTextureNode';
  4790. }
  4791. constructor( uvNode = screenUV, levelNode = null ) {
  4792. if ( sharedDepthbuffer === null ) {
  4793. sharedDepthbuffer = new DepthTexture();
  4794. }
  4795. super( uvNode, levelNode, sharedDepthbuffer );
  4796. }
  4797. }
  4798. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  4799. class ViewportDepthNode extends Node {
  4800. static get type() {
  4801. return 'ViewportDepthNode';
  4802. }
  4803. constructor( scope, valueNode = null ) {
  4804. super( 'float' );
  4805. this.scope = scope;
  4806. this.valueNode = valueNode;
  4807. this.isViewportDepthNode = true;
  4808. }
  4809. generate( builder ) {
  4810. const { scope } = this;
  4811. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  4812. return builder.getFragDepth();
  4813. }
  4814. return super.generate( builder );
  4815. }
  4816. setup( { camera } ) {
  4817. const { scope } = this;
  4818. const value = this.valueNode;
  4819. let node = null;
  4820. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  4821. if ( value !== null ) {
  4822. node = depthBase().assign( value );
  4823. }
  4824. } else if ( scope === ViewportDepthNode.DEPTH ) {
  4825. if ( camera.isPerspectiveCamera ) {
  4826. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  4827. } else {
  4828. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  4829. }
  4830. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  4831. if ( value !== null ) {
  4832. if ( camera.isPerspectiveCamera ) {
  4833. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  4834. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  4835. } else {
  4836. node = value;
  4837. }
  4838. } else {
  4839. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  4840. }
  4841. }
  4842. return node;
  4843. }
  4844. }
  4845. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  4846. ViewportDepthNode.DEPTH = 'depth';
  4847. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  4848. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  4849. // -near maps to 0; -far maps to 1
  4850. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  4851. // maps orthographic depth in [ 0, 1 ] to viewZ
  4852. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  4853. // NOTE: https://twitter.com/gonnavis/status/1377183786949959682
  4854. // -near maps to 0; -far maps to 1
  4855. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  4856. // maps perspective depth in [ 0, 1 ] to viewZ
  4857. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  4858. // -near maps to 0; -far maps to 1
  4859. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  4860. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  4861. // The final logarithmic depth formula used here is adapted from one described in an
  4862. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  4863. // which was an improvement upon an earlier formula one described in an
  4864. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  4865. // Ulrich's formula is the following:
  4866. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  4867. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  4868. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  4869. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  4870. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  4871. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  4872. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  4873. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  4874. // be used, and ultimately Ulrich's "near plane" version was chosen.
  4875. // Outerra eventually made another improvement to their original "C-constant" variant,
  4876. // but it still does not incorporate the camera near plane (for this version,
  4877. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  4878. // Here we make 4 changes to Ulrich's formula:
  4879. // 1. Clamp the camera near plane so we don't divide by 0.
  4880. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  4881. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  4882. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  4883. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  4884. // so we do the same here, hence the 'viewZ.negate()' call.
  4885. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  4886. near = near.max( 1e-6 ).toVar();
  4887. const numerator = log2( viewZ.negate().div( near ) );
  4888. const denominator = log2( far.div( near ) );
  4889. return numerator.div( denominator );
  4890. };
  4891. // maps logarithmic depth in [ 0, 1 ] to viewZ
  4892. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  4893. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  4894. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  4895. // a negative viewZ).
  4896. const exponent = depth.mul( log( far.div( near ) ) );
  4897. return float( Math.E ).pow( exponent ).mul( near ).negate();
  4898. };
  4899. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  4900. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  4901. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  4902. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  4903. depth.assign = ( value ) => depthBase( value );
  4904. class BuiltinNode extends Node {
  4905. constructor( name ) {
  4906. super( 'float' );
  4907. this.name = name;
  4908. this.isBuiltinNode = true;
  4909. }
  4910. generate( /* builder */ ) {
  4911. return this.name;
  4912. }
  4913. }
  4914. const builtin = nodeProxy( BuiltinNode );
  4915. class ClippingNode extends Node {
  4916. static get type() {
  4917. return 'ClippingNode';
  4918. }
  4919. constructor( scope = ClippingNode.DEFAULT ) {
  4920. super();
  4921. this.scope = scope;
  4922. }
  4923. setup( builder ) {
  4924. super.setup( builder );
  4925. const clippingContext = builder.clippingContext;
  4926. const { intersectionPlanes, unionPlanes } = clippingContext;
  4927. this.hardwareClipping = builder.material.hardwareClipping;
  4928. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  4929. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  4930. } else if ( this.scope === ClippingNode.HARDWARE ) {
  4931. return this.setupHardwareClipping( unionPlanes, builder );
  4932. } else {
  4933. return this.setupDefault( intersectionPlanes, unionPlanes );
  4934. }
  4935. }
  4936. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  4937. return Fn( () => {
  4938. const distanceToPlane = float().toVar( 'distanceToPlane' );
  4939. const distanceGradient = float().toVar( 'distanceToGradient' );
  4940. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  4941. const numUnionPlanes = unionPlanes.length;
  4942. if ( ! this.hardwareClipping && numUnionPlanes > 0 ) {
  4943. const clippingPlanes = uniformArray( unionPlanes );
  4944. Loop( numUnionPlanes, ( { i } ) => {
  4945. const plane = clippingPlanes.element( i );
  4946. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  4947. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  4948. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  4949. } );
  4950. }
  4951. const numIntersectionPlanes = intersectionPlanes.length;
  4952. if ( numIntersectionPlanes > 0 ) {
  4953. const clippingPlanes = uniformArray( intersectionPlanes );
  4954. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  4955. Loop( numIntersectionPlanes, ( { i } ) => {
  4956. const plane = clippingPlanes.element( i );
  4957. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  4958. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  4959. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  4960. } );
  4961. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  4962. }
  4963. diffuseColor.a.mulAssign( clipOpacity );
  4964. diffuseColor.a.equal( 0.0 ).discard();
  4965. } )();
  4966. }
  4967. setupDefault( intersectionPlanes, unionPlanes ) {
  4968. return Fn( () => {
  4969. const numUnionPlanes = unionPlanes.length;
  4970. if ( ! this.hardwareClipping && numUnionPlanes > 0 ) {
  4971. const clippingPlanes = uniformArray( unionPlanes );
  4972. Loop( numUnionPlanes, ( { i } ) => {
  4973. const plane = clippingPlanes.element( i );
  4974. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  4975. } );
  4976. }
  4977. const numIntersectionPlanes = intersectionPlanes.length;
  4978. if ( numIntersectionPlanes > 0 ) {
  4979. const clippingPlanes = uniformArray( intersectionPlanes );
  4980. const clipped = bool( true ).toVar( 'clipped' );
  4981. Loop( numIntersectionPlanes, ( { i } ) => {
  4982. const plane = clippingPlanes.element( i );
  4983. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  4984. } );
  4985. clipped.discard();
  4986. }
  4987. } )();
  4988. }
  4989. setupHardwareClipping( unionPlanes, builder ) {
  4990. const numUnionPlanes = unionPlanes.length;
  4991. builder.enableHardwareClipping( numUnionPlanes );
  4992. return Fn( () => {
  4993. const clippingPlanes = uniformArray( unionPlanes );
  4994. const hw_clip_distances = builtin( builder.getClipDistance() );
  4995. Loop( numUnionPlanes, ( { i } ) => {
  4996. const plane = clippingPlanes.element( i );
  4997. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  4998. hw_clip_distances.element( i ).assign( distance );
  4999. } );
  5000. } )();
  5001. }
  5002. }
  5003. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  5004. ClippingNode.DEFAULT = 'default';
  5005. ClippingNode.HARDWARE = 'hardware';
  5006. const clipping = () => nodeObject( new ClippingNode() );
  5007. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  5008. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  5009. /**
  5010. * See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  5011. */
  5012. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  5013. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  5014. 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 ) ) ) ) ) );
  5015. } );
  5016. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  5017. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  5018. } );
  5019. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  5020. // Find the discretized derivatives of our coordinates
  5021. const maxDeriv = max$1(
  5022. length( dFdx( position.xyz ) ),
  5023. length( dFdy( position.xyz ) )
  5024. );
  5025. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  5026. // Find two nearest log-discretized noise scales
  5027. const pixScales = vec2(
  5028. exp2( floor( log2( pixScale ) ) ),
  5029. exp2( ceil( log2( pixScale ) ) )
  5030. );
  5031. // Compute alpha thresholds at our two noise scales
  5032. const alpha = vec2(
  5033. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  5034. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  5035. );
  5036. // Factor to interpolate lerp with
  5037. const lerpFactor = fract( log2( pixScale ) );
  5038. // Interpolate alpha threshold from noise at two scales
  5039. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  5040. // Pass into CDF to compute uniformly distrib threshold
  5041. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  5042. const cases = vec3(
  5043. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  5044. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  5045. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  5046. // Find our final, uniformly distributed alpha threshold (ατ)
  5047. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  5048. // Avoids ατ == 0. Could also do ατ =1-ατ
  5049. return clamp( threshold, 1.0e-6, 1.0 );
  5050. } ).setLayout( {
  5051. name: 'getAlphaHashThreshold',
  5052. type: 'float',
  5053. inputs: [
  5054. { name: 'position', type: 'vec3' }
  5055. ]
  5056. } );
  5057. class NodeMaterial extends Material {
  5058. static get type() {
  5059. return 'NodeMaterial';
  5060. }
  5061. get type() {
  5062. return this.constructor.type;
  5063. }
  5064. set type( _value ) { /* */ }
  5065. constructor() {
  5066. super();
  5067. this.isNodeMaterial = true;
  5068. this.forceSinglePass = false;
  5069. this.fog = true;
  5070. this.lights = false;
  5071. this.hardwareClipping = false;
  5072. this.lightsNode = null;
  5073. this.envNode = null;
  5074. this.aoNode = null;
  5075. this.colorNode = null;
  5076. this.normalNode = null;
  5077. this.opacityNode = null;
  5078. this.backdropNode = null;
  5079. this.backdropAlphaNode = null;
  5080. this.alphaTestNode = null;
  5081. this.positionNode = null;
  5082. this.geometryNode = null;
  5083. this.depthNode = null;
  5084. this.shadowPositionNode = null;
  5085. this.receivedShadowNode = null;
  5086. this.castShadowNode = null;
  5087. this.outputNode = null;
  5088. this.mrtNode = null;
  5089. this.fragmentNode = null;
  5090. this.vertexNode = null;
  5091. }
  5092. customProgramCacheKey() {
  5093. return this.type + getCacheKey$1( this );
  5094. }
  5095. build( builder ) {
  5096. this.setup( builder );
  5097. }
  5098. setupObserver( builder ) {
  5099. return new NodeMaterialObserver( builder );
  5100. }
  5101. setup( builder ) {
  5102. builder.context.setupNormal = () => this.setupNormal( builder );
  5103. const renderer = builder.renderer;
  5104. const renderTarget = renderer.getRenderTarget();
  5105. // < VERTEX STAGE >
  5106. builder.addStack();
  5107. builder.stack.outputNode = this.vertexNode || this.setupPosition( builder );
  5108. if ( this.geometryNode !== null ) {
  5109. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  5110. }
  5111. builder.addFlow( 'vertex', builder.removeStack() );
  5112. // < FRAGMENT STAGE >
  5113. builder.addStack();
  5114. let resultNode;
  5115. const clippingNode = this.setupClipping( builder );
  5116. if ( this.depthWrite === true ) {
  5117. // only write depth if depth buffer is configured
  5118. if ( renderTarget !== null ) {
  5119. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  5120. } else {
  5121. if ( renderer.depth === true ) this.setupDepth( builder );
  5122. }
  5123. }
  5124. if ( this.fragmentNode === null ) {
  5125. this.setupDiffuseColor( builder );
  5126. this.setupVariants( builder );
  5127. const outgoingLightNode = this.setupLighting( builder );
  5128. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  5129. // force unsigned floats - useful for RenderTargets
  5130. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  5131. resultNode = this.setupOutput( builder, basicOutput );
  5132. // OUTPUT NODE
  5133. output.assign( resultNode );
  5134. //
  5135. if ( this.outputNode !== null ) resultNode = this.outputNode;
  5136. // MRT
  5137. if ( renderTarget !== null ) {
  5138. const mrt = renderer.getMRT();
  5139. const materialMRT = this.mrtNode;
  5140. if ( mrt !== null ) {
  5141. resultNode = mrt;
  5142. if ( materialMRT !== null ) {
  5143. resultNode = mrt.merge( materialMRT );
  5144. }
  5145. } else if ( materialMRT !== null ) {
  5146. resultNode = materialMRT;
  5147. }
  5148. }
  5149. } else {
  5150. let fragmentNode = this.fragmentNode;
  5151. if ( fragmentNode.isOutputStructNode !== true ) {
  5152. fragmentNode = vec4( fragmentNode );
  5153. }
  5154. resultNode = this.setupOutput( builder, fragmentNode );
  5155. }
  5156. builder.stack.outputNode = resultNode;
  5157. builder.addFlow( 'fragment', builder.removeStack() );
  5158. // < MONITOR >
  5159. builder.monitor = this.setupObserver( builder );
  5160. }
  5161. setupClipping( builder ) {
  5162. if ( builder.clippingContext === null ) return null;
  5163. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  5164. let result = null;
  5165. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  5166. const samples = builder.renderer.samples;
  5167. if ( this.alphaToCoverage && samples > 1 ) {
  5168. // to be added to flow when the color/alpha value has been determined
  5169. result = clippingAlpha();
  5170. } else {
  5171. builder.stack.add( clipping() );
  5172. }
  5173. }
  5174. return result;
  5175. }
  5176. setupHardwareClipping( builder ) {
  5177. this.hardwareClipping = false;
  5178. if ( builder.clippingContext === null ) return;
  5179. const candidateCount = builder.clippingContext.unionPlanes.length;
  5180. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  5181. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  5182. builder.stack.add( hardwareClipping() );
  5183. this.hardwareClipping = true;
  5184. }
  5185. return;
  5186. }
  5187. setupDepth( builder ) {
  5188. const { renderer, camera } = builder;
  5189. // Depth
  5190. let depthNode = this.depthNode;
  5191. if ( depthNode === null ) {
  5192. const mrt = renderer.getMRT();
  5193. if ( mrt && mrt.has( 'depth' ) ) {
  5194. depthNode = mrt.get( 'depth' );
  5195. } else if ( renderer.logarithmicDepthBuffer === true ) {
  5196. if ( camera.isPerspectiveCamera ) {
  5197. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  5198. } else {
  5199. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  5200. }
  5201. }
  5202. }
  5203. if ( depthNode !== null ) {
  5204. depth.assign( depthNode ).append();
  5205. }
  5206. }
  5207. setupPosition( builder ) {
  5208. const { object } = builder;
  5209. const geometry = object.geometry;
  5210. builder.addStack();
  5211. // Vertex
  5212. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  5213. morphReference( object ).append();
  5214. }
  5215. if ( object.isSkinnedMesh === true ) {
  5216. skinningReference( object ).append();
  5217. }
  5218. if ( this.displacementMap ) {
  5219. const displacementMap = materialReference( 'displacementMap', 'texture' );
  5220. const displacementScale = materialReference( 'displacementScale', 'float' );
  5221. const displacementBias = materialReference( 'displacementBias', 'float' );
  5222. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  5223. }
  5224. if ( object.isBatchedMesh ) {
  5225. batch( object ).append();
  5226. }
  5227. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  5228. instancedMesh( object ).append();
  5229. }
  5230. if ( this.positionNode !== null ) {
  5231. positionLocal.assign( this.positionNode );
  5232. }
  5233. this.setupHardwareClipping( builder );
  5234. const mvp = modelViewProjection();
  5235. builder.context.vertex = builder.removeStack();
  5236. builder.context.mvp = mvp;
  5237. return mvp;
  5238. }
  5239. setupDiffuseColor( { object, geometry } ) {
  5240. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  5241. // VERTEX COLORS
  5242. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  5243. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  5244. }
  5245. // Instanced colors
  5246. if ( object.instanceColor ) {
  5247. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  5248. colorNode = instanceColor.mul( colorNode );
  5249. }
  5250. if ( object.isBatchedMesh && object._colorsTexture ) {
  5251. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  5252. colorNode = batchColor.mul( colorNode );
  5253. }
  5254. // COLOR
  5255. diffuseColor.assign( colorNode );
  5256. // OPACITY
  5257. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  5258. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  5259. // ALPHA TEST
  5260. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  5261. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  5262. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  5263. }
  5264. // ALPHA HASH
  5265. if ( this.alphaHash === true ) {
  5266. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  5267. }
  5268. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  5269. diffuseColor.a.assign( 1.0 );
  5270. }
  5271. }
  5272. setupVariants( /*builder*/ ) {
  5273. // Interface function.
  5274. }
  5275. setupOutgoingLight() {
  5276. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  5277. }
  5278. setupNormal() {
  5279. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  5280. }
  5281. setupEnvironment( /*builder*/ ) {
  5282. let node = null;
  5283. if ( this.envNode ) {
  5284. node = this.envNode;
  5285. } else if ( this.envMap ) {
  5286. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  5287. }
  5288. return node;
  5289. }
  5290. setupLightMap( builder ) {
  5291. let node = null;
  5292. if ( builder.material.lightMap ) {
  5293. node = new IrradianceNode( materialLightMap );
  5294. }
  5295. return node;
  5296. }
  5297. setupLights( builder ) {
  5298. const materialLightsNode = [];
  5299. //
  5300. const envNode = this.setupEnvironment( builder );
  5301. if ( envNode && envNode.isLightingNode ) {
  5302. materialLightsNode.push( envNode );
  5303. }
  5304. const lightMapNode = this.setupLightMap( builder );
  5305. if ( lightMapNode && lightMapNode.isLightingNode ) {
  5306. materialLightsNode.push( lightMapNode );
  5307. }
  5308. if ( this.aoNode !== null || builder.material.aoMap ) {
  5309. const aoNode = this.aoNode !== null ? this.aoNode : materialAOMap;
  5310. materialLightsNode.push( new AONode( aoNode ) );
  5311. }
  5312. let lightsN = this.lightsNode || builder.lightsNode;
  5313. if ( materialLightsNode.length > 0 ) {
  5314. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  5315. }
  5316. return lightsN;
  5317. }
  5318. setupLightingModel( /*builder*/ ) {
  5319. // Interface function.
  5320. }
  5321. setupLighting( builder ) {
  5322. const { material } = builder;
  5323. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  5324. // OUTGOING LIGHT
  5325. const lights = this.lights === true || this.lightsNode !== null;
  5326. const lightsNode = lights ? this.setupLights( builder ) : null;
  5327. let outgoingLightNode = this.setupOutgoingLight( builder );
  5328. if ( lightsNode && lightsNode.getScope().hasLights ) {
  5329. const lightingModel = this.setupLightingModel( builder );
  5330. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  5331. } else if ( backdropNode !== null ) {
  5332. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  5333. }
  5334. // EMISSIVE
  5335. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  5336. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  5337. outgoingLightNode = outgoingLightNode.add( emissive );
  5338. }
  5339. return outgoingLightNode;
  5340. }
  5341. setupOutput( builder, outputNode ) {
  5342. // FOG
  5343. if ( this.fog === true ) {
  5344. const fogNode = builder.fogNode;
  5345. if ( fogNode ) outputNode = vec4( fogNode.mix( outputNode.rgb, fogNode.colorNode ), outputNode.a );
  5346. }
  5347. return outputNode;
  5348. }
  5349. setDefaultValues( material ) {
  5350. // This approach is to reuse the native refreshUniforms*
  5351. // and turn available the use of features like transmission and environment in core
  5352. for ( const property in material ) {
  5353. const value = material[ property ];
  5354. if ( this[ property ] === undefined ) {
  5355. this[ property ] = value;
  5356. if ( value && value.clone ) this[ property ] = value.clone();
  5357. }
  5358. }
  5359. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  5360. for ( const key in descriptors ) {
  5361. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  5362. descriptors[ key ].get !== undefined ) {
  5363. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  5364. }
  5365. }
  5366. }
  5367. toJSON( meta ) {
  5368. const isRoot = ( meta === undefined || typeof meta === 'string' );
  5369. if ( isRoot ) {
  5370. meta = {
  5371. textures: {},
  5372. images: {},
  5373. nodes: {}
  5374. };
  5375. }
  5376. const data = Material.prototype.toJSON.call( this, meta );
  5377. const nodeChildren = getNodeChildren( this );
  5378. data.inputNodes = {};
  5379. for ( const { property, childNode } of nodeChildren ) {
  5380. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  5381. }
  5382. // TODO: Copied from Object3D.toJSON
  5383. function extractFromCache( cache ) {
  5384. const values = [];
  5385. for ( const key in cache ) {
  5386. const data = cache[ key ];
  5387. delete data.metadata;
  5388. values.push( data );
  5389. }
  5390. return values;
  5391. }
  5392. if ( isRoot ) {
  5393. const textures = extractFromCache( meta.textures );
  5394. const images = extractFromCache( meta.images );
  5395. const nodes = extractFromCache( meta.nodes );
  5396. if ( textures.length > 0 ) data.textures = textures;
  5397. if ( images.length > 0 ) data.images = images;
  5398. if ( nodes.length > 0 ) data.nodes = nodes;
  5399. }
  5400. return data;
  5401. }
  5402. copy( source ) {
  5403. this.lightsNode = source.lightsNode;
  5404. this.envNode = source.envNode;
  5405. this.colorNode = source.colorNode;
  5406. this.normalNode = source.normalNode;
  5407. this.opacityNode = source.opacityNode;
  5408. this.backdropNode = source.backdropNode;
  5409. this.backdropAlphaNode = source.backdropAlphaNode;
  5410. this.alphaTestNode = source.alphaTestNode;
  5411. this.positionNode = source.positionNode;
  5412. this.geometryNode = source.geometryNode;
  5413. this.depthNode = source.depthNode;
  5414. this.shadowPositionNode = source.shadowPositionNode;
  5415. this.receivedShadowNode = source.receivedShadowNode;
  5416. this.castShadowNode = source.castShadowNode;
  5417. this.outputNode = source.outputNode;
  5418. this.mrtNode = source.mrtNode;
  5419. this.fragmentNode = source.fragmentNode;
  5420. this.vertexNode = source.vertexNode;
  5421. return super.copy( source );
  5422. }
  5423. }
  5424. const _defaultValues$e = /*@__PURE__*/ new PointsMaterial();
  5425. class InstancedPointsNodeMaterial extends NodeMaterial {
  5426. static get type() {
  5427. return 'InstancedPointsNodeMaterial';
  5428. }
  5429. constructor( params = {} ) {
  5430. super();
  5431. this.lights = false;
  5432. this.useAlphaToCoverage = true;
  5433. this.useColor = params.vertexColors;
  5434. this.pointWidth = 1;
  5435. this.pointColorNode = null;
  5436. this.pointWidthNode = null;
  5437. this.setDefaultValues( _defaultValues$e );
  5438. this.setValues( params );
  5439. }
  5440. setup( builder ) {
  5441. this.setupShaders( builder );
  5442. super.setup( builder );
  5443. }
  5444. setupShaders( { renderer } ) {
  5445. const useAlphaToCoverage = this.alphaToCoverage;
  5446. const useColor = this.useColor;
  5447. this.vertexNode = Fn( () => {
  5448. const instancePosition = attribute( 'instancePosition' ).xyz;
  5449. // camera space
  5450. const mvPos = vec4( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  5451. const aspect = viewport.z.div( viewport.w );
  5452. // clip space
  5453. const clipPos = cameraProjectionMatrix.mul( mvPos );
  5454. // offset in ndc space
  5455. const offset = positionGeometry.xy.toVar();
  5456. offset.mulAssign( this.pointWidthNode ? this.pointWidthNode : materialPointWidth );
  5457. offset.assign( offset.div( viewport.z ) );
  5458. offset.y.assign( offset.y.mul( aspect ) );
  5459. // back to clip space
  5460. offset.assign( offset.mul( clipPos.w ) );
  5461. //clipPos.xy += offset;
  5462. clipPos.addAssign( vec4( offset, 0, 0 ) );
  5463. return clipPos;
  5464. } )();
  5465. this.fragmentNode = Fn( () => {
  5466. const alpha = float( 1 ).toVar();
  5467. const len2 = lengthSq( uv().mul( 2 ).sub( 1 ) );
  5468. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  5469. const dlen = float( len2.fwidth() ).toVar();
  5470. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  5471. } else {
  5472. len2.greaterThan( 1.0 ).discard();
  5473. }
  5474. let pointColorNode;
  5475. if ( this.pointColorNode ) {
  5476. pointColorNode = this.pointColorNode;
  5477. } else {
  5478. if ( useColor ) {
  5479. const instanceColor = attribute( 'instanceColor' );
  5480. pointColorNode = instanceColor.mul( materialColor );
  5481. } else {
  5482. pointColorNode = materialColor;
  5483. }
  5484. }
  5485. alpha.mulAssign( materialOpacity );
  5486. return vec4( pointColorNode, alpha );
  5487. } )();
  5488. }
  5489. get alphaToCoverage() {
  5490. return this.useAlphaToCoverage;
  5491. }
  5492. set alphaToCoverage( value ) {
  5493. if ( this.useAlphaToCoverage !== value ) {
  5494. this.useAlphaToCoverage = value;
  5495. this.needsUpdate = true;
  5496. }
  5497. }
  5498. }
  5499. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  5500. class LineBasicNodeMaterial extends NodeMaterial {
  5501. static get type() {
  5502. return 'LineBasicNodeMaterial';
  5503. }
  5504. constructor( parameters ) {
  5505. super();
  5506. this.isLineBasicNodeMaterial = true;
  5507. this.lights = false;
  5508. this.setDefaultValues( _defaultValues$d );
  5509. this.setValues( parameters );
  5510. }
  5511. }
  5512. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  5513. class LineDashedNodeMaterial extends NodeMaterial {
  5514. static get type() {
  5515. return 'LineDashedNodeMaterial';
  5516. }
  5517. constructor( parameters ) {
  5518. super();
  5519. this.isLineDashedNodeMaterial = true;
  5520. this.lights = false;
  5521. this.setDefaultValues( _defaultValues$c );
  5522. this.dashOffset = 0;
  5523. this.offsetNode = null;
  5524. this.dashScaleNode = null;
  5525. this.dashSizeNode = null;
  5526. this.gapSizeNode = null;
  5527. this.setValues( parameters );
  5528. }
  5529. setupVariants() {
  5530. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  5531. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  5532. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  5533. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  5534. dashSize.assign( dashSizeNode );
  5535. gapSize.assign( gapSizeNode );
  5536. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  5537. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  5538. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  5539. }
  5540. }
  5541. let _sharedFramebuffer = null;
  5542. class ViewportSharedTextureNode extends ViewportTextureNode {
  5543. static get type() {
  5544. return 'ViewportSharedTextureNode';
  5545. }
  5546. constructor( uvNode = screenUV, levelNode = null ) {
  5547. if ( _sharedFramebuffer === null ) {
  5548. _sharedFramebuffer = new FramebufferTexture();
  5549. }
  5550. super( uvNode, levelNode, _sharedFramebuffer );
  5551. }
  5552. updateReference() {
  5553. return this;
  5554. }
  5555. }
  5556. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  5557. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  5558. class Line2NodeMaterial extends NodeMaterial {
  5559. static get type() {
  5560. return 'Line2NodeMaterial';
  5561. }
  5562. constructor( params = {} ) {
  5563. super();
  5564. this.lights = false;
  5565. this.setDefaultValues( _defaultValues$b );
  5566. this.useAlphaToCoverage = true;
  5567. this.useColor = params.vertexColors;
  5568. this.useDash = params.dashed;
  5569. this.useWorldUnits = false;
  5570. this.dashOffset = 0;
  5571. this.lineWidth = 1;
  5572. this.lineColorNode = null;
  5573. this.offsetNode = null;
  5574. this.dashScaleNode = null;
  5575. this.dashSizeNode = null;
  5576. this.gapSizeNode = null;
  5577. this.blending = NoBlending;
  5578. this.setValues( params );
  5579. }
  5580. setup( builder ) {
  5581. this.setupShaders( builder );
  5582. super.setup( builder );
  5583. }
  5584. setupShaders( { renderer } ) {
  5585. const useAlphaToCoverage = this.alphaToCoverage;
  5586. const useColor = this.useColor;
  5587. const useDash = this.dashed;
  5588. const useWorldUnits = this.worldUnits;
  5589. const trimSegment = Fn( ( { start, end } ) => {
  5590. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  5591. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  5592. const nearEstimate = b.mul( - 0.5 ).div( a );
  5593. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  5594. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  5595. } ).setLayout( {
  5596. name: 'trimSegment',
  5597. type: 'vec4',
  5598. inputs: [
  5599. { name: 'start', type: 'vec4' },
  5600. { name: 'end', type: 'vec4' }
  5601. ]
  5602. } );
  5603. this.vertexNode = Fn( () => {
  5604. const instanceStart = attribute( 'instanceStart' );
  5605. const instanceEnd = attribute( 'instanceEnd' );
  5606. // camera space
  5607. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  5608. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  5609. if ( useDash ) {
  5610. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  5611. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  5612. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  5613. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  5614. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  5615. lineDistance = lineDistance.add( offsetNode );
  5616. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  5617. }
  5618. if ( useWorldUnits ) {
  5619. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  5620. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  5621. }
  5622. const aspect = viewport.z.div( viewport.w );
  5623. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  5624. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  5625. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  5626. // perhaps there is a more elegant solution -- WestLangley
  5627. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  5628. If( perspective, () => {
  5629. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  5630. end.assign( trimSegment( { start: start, end: end } ) );
  5631. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  5632. start.assign( trimSegment( { start: end, end: start } ) );
  5633. } );
  5634. } );
  5635. // clip space
  5636. const clipStart = cameraProjectionMatrix.mul( start );
  5637. const clipEnd = cameraProjectionMatrix.mul( end );
  5638. // ndc space
  5639. const ndcStart = clipStart.xyz.div( clipStart.w );
  5640. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  5641. // direction
  5642. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  5643. // account for clip-space aspect ratio
  5644. dir.x.assign( dir.x.mul( aspect ) );
  5645. dir.assign( dir.normalize() );
  5646. const clip = vec4().toVar();
  5647. if ( useWorldUnits ) {
  5648. // get the offset direction as perpendicular to the view vector
  5649. const worldDir = end.xyz.sub( start.xyz ).normalize();
  5650. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  5651. const worldUp = worldDir.cross( tmpFwd ).normalize();
  5652. const worldFwd = worldDir.cross( worldUp );
  5653. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  5654. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  5655. // height offset
  5656. const hw = materialLineWidth.mul( 0.5 );
  5657. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  5658. // don't extend the line if we're rendering dashes because we
  5659. // won't be rendering the endcaps
  5660. if ( ! useDash ) {
  5661. // cap extension
  5662. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  5663. // add width to the box
  5664. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  5665. // endcaps
  5666. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  5667. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  5668. } );
  5669. }
  5670. // project the worldpos
  5671. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  5672. // shift the depth of the projected points so the line
  5673. // segments overlap neatly
  5674. const clipPose = vec3().toVar();
  5675. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  5676. clip.z.assign( clipPose.z.mul( clip.w ) );
  5677. } else {
  5678. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  5679. // undo aspect ratio adjustment
  5680. dir.x.assign( dir.x.div( aspect ) );
  5681. offset.x.assign( offset.x.div( aspect ) );
  5682. // sign flip
  5683. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  5684. // endcaps
  5685. If( positionGeometry.y.lessThan( 0.0 ), () => {
  5686. offset.assign( offset.sub( dir ) );
  5687. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  5688. offset.assign( offset.add( dir ) );
  5689. } );
  5690. // adjust for linewidth
  5691. offset.assign( offset.mul( materialLineWidth ) );
  5692. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  5693. offset.assign( offset.div( viewport.w ) );
  5694. // select end
  5695. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  5696. // back to clip space
  5697. offset.assign( offset.mul( clip.w ) );
  5698. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  5699. }
  5700. return clip;
  5701. } )();
  5702. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  5703. const p13 = p1.sub( p3 );
  5704. const p43 = p4.sub( p3 );
  5705. const p21 = p2.sub( p1 );
  5706. const d1343 = p13.dot( p43 );
  5707. const d4321 = p43.dot( p21 );
  5708. const d1321 = p13.dot( p21 );
  5709. const d4343 = p43.dot( p43 );
  5710. const d2121 = p21.dot( p21 );
  5711. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  5712. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  5713. const mua = numer.div( denom ).clamp();
  5714. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  5715. return vec2( mua, mub );
  5716. } );
  5717. this.colorNode = Fn( () => {
  5718. const vUv = uv();
  5719. if ( useDash ) {
  5720. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  5721. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  5722. dashSize.assign( dashSizeNode );
  5723. gapSize.assign( gapSizeNode );
  5724. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  5725. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  5726. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  5727. }
  5728. const alpha = float( 1 ).toVar( 'alpha' );
  5729. if ( useWorldUnits ) {
  5730. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  5731. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  5732. // Find the closest points on the view ray and the line segment
  5733. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  5734. const lineDir = worldEnd.sub( worldStart );
  5735. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  5736. const p1 = worldStart.add( lineDir.mul( params.x ) );
  5737. const p2 = rayEnd.mul( params.y );
  5738. const delta = p1.sub( p2 );
  5739. const len = delta.length();
  5740. const norm = len.div( materialLineWidth );
  5741. if ( ! useDash ) {
  5742. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  5743. const dnorm = norm.fwidth();
  5744. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  5745. } else {
  5746. norm.greaterThan( 0.5 ).discard();
  5747. }
  5748. }
  5749. } else {
  5750. // round endcaps
  5751. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  5752. const a = vUv.x;
  5753. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  5754. const len2 = a.mul( a ).add( b.mul( b ) );
  5755. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  5756. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  5757. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  5758. } );
  5759. } else {
  5760. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  5761. const a = vUv.x;
  5762. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  5763. const len2 = a.mul( a ).add( b.mul( b ) );
  5764. len2.greaterThan( 1.0 ).discard();
  5765. } );
  5766. }
  5767. }
  5768. let lineColorNode;
  5769. if ( this.lineColorNode ) {
  5770. lineColorNode = this.lineColorNode;
  5771. } else {
  5772. if ( useColor ) {
  5773. const instanceColorStart = attribute( 'instanceColorStart' );
  5774. const instanceColorEnd = attribute( 'instanceColorEnd' );
  5775. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  5776. lineColorNode = instanceColor.mul( materialColor );
  5777. } else {
  5778. lineColorNode = materialColor;
  5779. }
  5780. }
  5781. return vec4( lineColorNode, alpha );
  5782. } )();
  5783. if ( this.transparent ) {
  5784. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  5785. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  5786. }
  5787. }
  5788. get worldUnits() {
  5789. return this.useWorldUnits;
  5790. }
  5791. set worldUnits( value ) {
  5792. if ( this.useWorldUnits !== value ) {
  5793. this.useWorldUnits = value;
  5794. this.needsUpdate = true;
  5795. }
  5796. }
  5797. get dashed() {
  5798. return this.useDash;
  5799. }
  5800. set dashed( value ) {
  5801. if ( this.useDash !== value ) {
  5802. this.useDash = value;
  5803. this.needsUpdate = true;
  5804. }
  5805. }
  5806. get alphaToCoverage() {
  5807. return this.useAlphaToCoverage;
  5808. }
  5809. set alphaToCoverage( value ) {
  5810. if ( this.useAlphaToCoverage !== value ) {
  5811. this.useAlphaToCoverage = value;
  5812. this.needsUpdate = true;
  5813. }
  5814. }
  5815. }
  5816. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  5817. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  5818. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  5819. class MeshNormalNodeMaterial extends NodeMaterial {
  5820. static get type() {
  5821. return 'MeshNormalNodeMaterial';
  5822. }
  5823. constructor( parameters ) {
  5824. super();
  5825. this.lights = false;
  5826. this.isMeshNormalNodeMaterial = true;
  5827. this.setDefaultValues( _defaultValues$a );
  5828. this.setValues( parameters );
  5829. }
  5830. setupDiffuseColor() {
  5831. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  5832. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  5833. }
  5834. }
  5835. class EquirectUVNode extends TempNode {
  5836. static get type() {
  5837. return 'EquirectUVNode';
  5838. }
  5839. constructor( dirNode = positionWorldDirection ) {
  5840. super( 'vec2' );
  5841. this.dirNode = dirNode;
  5842. }
  5843. setup() {
  5844. const dir = this.dirNode;
  5845. const u = dir.z.atan2( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  5846. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  5847. return vec2( u, v );
  5848. }
  5849. }
  5850. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  5851. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  5852. class CubeRenderTarget extends WebGLCubeRenderTarget {
  5853. constructor( size = 1, options = {} ) {
  5854. super( size, options );
  5855. this.isCubeRenderTarget = true;
  5856. }
  5857. fromEquirectangularTexture( renderer, texture$1 ) {
  5858. const currentMinFilter = texture$1.minFilter;
  5859. const currentGenerateMipmaps = texture$1.generateMipmaps;
  5860. texture$1.generateMipmaps = true;
  5861. this.texture.type = texture$1.type;
  5862. this.texture.colorSpace = texture$1.colorSpace;
  5863. this.texture.generateMipmaps = texture$1.generateMipmaps;
  5864. this.texture.minFilter = texture$1.minFilter;
  5865. this.texture.magFilter = texture$1.magFilter;
  5866. const geometry = new BoxGeometry( 5, 5, 5 );
  5867. const uvNode = equirectUV( positionWorldDirection );
  5868. const material = new NodeMaterial();
  5869. material.colorNode = texture( texture$1, uvNode, 0 );
  5870. material.side = BackSide;
  5871. material.blending = NoBlending;
  5872. const mesh = new Mesh( geometry, material );
  5873. const scene = new Scene();
  5874. scene.add( mesh );
  5875. // Avoid blurred poles
  5876. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  5877. const camera = new CubeCamera( 1, 10, this );
  5878. const currentMRT = renderer.getMRT();
  5879. renderer.setMRT( null );
  5880. camera.update( renderer, scene );
  5881. renderer.setMRT( currentMRT );
  5882. texture$1.minFilter = currentMinFilter;
  5883. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  5884. mesh.geometry.dispose();
  5885. mesh.material.dispose();
  5886. return this;
  5887. }
  5888. }
  5889. const _cache$1 = new WeakMap();
  5890. class CubeMapNode extends TempNode {
  5891. static get type() {
  5892. return 'CubeMapNode';
  5893. }
  5894. constructor( envNode ) {
  5895. super( 'vec3' );
  5896. this.envNode = envNode;
  5897. this._cubeTexture = null;
  5898. this._cubeTextureNode = cubeTexture();
  5899. const defaultTexture = new CubeTexture();
  5900. defaultTexture.isRenderTargetTexture = true;
  5901. this._defaultTexture = defaultTexture;
  5902. this.updateBeforeType = NodeUpdateType.RENDER;
  5903. }
  5904. updateBefore( frame ) {
  5905. const { renderer, material } = frame;
  5906. const envNode = this.envNode;
  5907. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  5908. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  5909. if ( texture && texture.isTexture ) {
  5910. const mapping = texture.mapping;
  5911. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  5912. // check for converted cubemap map
  5913. if ( _cache$1.has( texture ) ) {
  5914. const cubeMap = _cache$1.get( texture );
  5915. mapTextureMapping( cubeMap, texture.mapping );
  5916. this._cubeTexture = cubeMap;
  5917. } else {
  5918. // create cube map from equirectangular map
  5919. const image = texture.image;
  5920. if ( isEquirectangularMapReady$1( image ) ) {
  5921. const renderTarget = new CubeRenderTarget( image.height );
  5922. renderTarget.fromEquirectangularTexture( renderer, texture );
  5923. mapTextureMapping( renderTarget.texture, texture.mapping );
  5924. this._cubeTexture = renderTarget.texture;
  5925. _cache$1.set( texture, renderTarget.texture );
  5926. texture.addEventListener( 'dispose', onTextureDispose );
  5927. } else {
  5928. // default cube texture as fallback when equirectangular texture is not yet loaded
  5929. this._cubeTexture = this._defaultTexture;
  5930. }
  5931. }
  5932. //
  5933. this._cubeTextureNode.value = this._cubeTexture;
  5934. } else {
  5935. // envNode already refers to a cube map
  5936. this._cubeTextureNode = this.envNode;
  5937. }
  5938. }
  5939. }
  5940. }
  5941. setup( builder ) {
  5942. this.updateBefore( builder );
  5943. return this._cubeTextureNode;
  5944. }
  5945. }
  5946. function isEquirectangularMapReady$1( image ) {
  5947. if ( image === null || image === undefined ) return false;
  5948. return image.height > 0;
  5949. }
  5950. function onTextureDispose( event ) {
  5951. const texture = event.target;
  5952. texture.removeEventListener( 'dispose', onTextureDispose );
  5953. const renderTarget = _cache$1.get( texture );
  5954. if ( renderTarget !== undefined ) {
  5955. _cache$1.delete( texture );
  5956. renderTarget.dispose();
  5957. }
  5958. }
  5959. function mapTextureMapping( texture, mapping ) {
  5960. if ( mapping === EquirectangularReflectionMapping ) {
  5961. texture.mapping = CubeReflectionMapping;
  5962. } else if ( mapping === EquirectangularRefractionMapping ) {
  5963. texture.mapping = CubeRefractionMapping;
  5964. }
  5965. }
  5966. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  5967. class BasicEnvironmentNode extends LightingNode {
  5968. static get type() {
  5969. return 'BasicEnvironmentNode';
  5970. }
  5971. constructor( envNode = null ) {
  5972. super();
  5973. this.envNode = envNode;
  5974. }
  5975. setup( builder ) {
  5976. // environment property is used in the finish() method of BasicLightingModel
  5977. builder.context.environment = cubeMapNode( this.envNode );
  5978. }
  5979. }
  5980. class BasicLightMapNode extends LightingNode {
  5981. static get type() {
  5982. return 'BasicLightMapNode';
  5983. }
  5984. constructor( lightMapNode = null ) {
  5985. super();
  5986. this.lightMapNode = lightMapNode;
  5987. }
  5988. setup( builder ) {
  5989. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  5990. const RECIPROCAL_PI = float( 1 / Math.PI );
  5991. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  5992. }
  5993. }
  5994. class LightingModel {
  5995. start( /*input, stack, builder*/ ) { }
  5996. finish( /*input, stack, builder*/ ) { }
  5997. direct( /*input, stack, builder*/ ) { }
  5998. directRectArea( /*input, stack, builder*/ ) {}
  5999. indirect( /*input, stack, builder*/ ) { }
  6000. ambientOcclusion( /*input, stack, builder*/ ) { }
  6001. }
  6002. class BasicLightingModel extends LightingModel {
  6003. constructor() {
  6004. super();
  6005. }
  6006. indirect( context, stack, builder ) {
  6007. const ambientOcclusion = context.ambientOcclusion;
  6008. const reflectedLight = context.reflectedLight;
  6009. const irradianceLightMap = builder.context.irradianceLightMap;
  6010. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  6011. // accumulation (baked indirect lighting only)
  6012. if ( irradianceLightMap ) {
  6013. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  6014. } else {
  6015. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  6016. }
  6017. // modulation
  6018. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  6019. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  6020. }
  6021. finish( context, stack, builder ) {
  6022. const material = builder.material;
  6023. const outgoingLight = context.outgoingLight;
  6024. const envNode = builder.context.environment;
  6025. if ( envNode ) {
  6026. switch ( material.combine ) {
  6027. case MultiplyOperation:
  6028. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  6029. break;
  6030. case MixOperation:
  6031. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  6032. break;
  6033. case AddOperation:
  6034. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  6035. break;
  6036. default:
  6037. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  6038. break;
  6039. }
  6040. }
  6041. }
  6042. }
  6043. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  6044. class MeshBasicNodeMaterial extends NodeMaterial {
  6045. static get type() {
  6046. return 'MeshBasicNodeMaterial';
  6047. }
  6048. constructor( parameters ) {
  6049. super();
  6050. this.isMeshBasicNodeMaterial = true;
  6051. this.lights = true;
  6052. this.setDefaultValues( _defaultValues$9 );
  6053. this.setValues( parameters );
  6054. }
  6055. setupNormal() {
  6056. return normalView; // see #28839
  6057. }
  6058. setupEnvironment( builder ) {
  6059. const envNode = super.setupEnvironment( builder );
  6060. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  6061. }
  6062. setupLightMap( builder ) {
  6063. let node = null;
  6064. if ( builder.material.lightMap ) {
  6065. node = new BasicLightMapNode( materialLightMap );
  6066. }
  6067. return node;
  6068. }
  6069. setupOutgoingLight() {
  6070. return diffuseColor.rgb;
  6071. }
  6072. setupLightingModel() {
  6073. return new BasicLightingModel();
  6074. }
  6075. }
  6076. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  6077. // Original approximation by Christophe Schlick '94
  6078. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  6079. // Optimized variant (presented by Epic at SIGGRAPH '13)
  6080. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  6081. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  6082. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  6083. } ); // validated
  6084. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  6085. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  6086. } ); // validated
  6087. const G_BlinnPhong_Implicit = () => float( 0.25 );
  6088. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  6089. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  6090. } );
  6091. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  6092. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  6093. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  6094. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  6095. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  6096. const G = G_BlinnPhong_Implicit();
  6097. const D = D_BlinnPhong( { dotNH } );
  6098. return F.mul( G ).mul( D );
  6099. } );
  6100. class PhongLightingModel extends BasicLightingModel {
  6101. constructor( specular = true ) {
  6102. super();
  6103. this.specular = specular;
  6104. }
  6105. direct( { lightDirection, lightColor, reflectedLight } ) {
  6106. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  6107. const irradiance = dotNL.mul( lightColor );
  6108. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  6109. if ( this.specular === true ) {
  6110. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  6111. }
  6112. }
  6113. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  6114. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  6115. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  6116. }
  6117. }
  6118. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  6119. class MeshLambertNodeMaterial extends NodeMaterial {
  6120. static get type() {
  6121. return 'MeshLambertNodeMaterial';
  6122. }
  6123. constructor( parameters ) {
  6124. super();
  6125. this.isMeshLambertNodeMaterial = true;
  6126. this.lights = true;
  6127. this.setDefaultValues( _defaultValues$8 );
  6128. this.setValues( parameters );
  6129. }
  6130. setupEnvironment( builder ) {
  6131. const envNode = super.setupEnvironment( builder );
  6132. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  6133. }
  6134. setupLightingModel( /*builder*/ ) {
  6135. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  6136. }
  6137. }
  6138. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  6139. class MeshPhongNodeMaterial extends NodeMaterial {
  6140. static get type() {
  6141. return 'MeshPhongNodeMaterial';
  6142. }
  6143. constructor( parameters ) {
  6144. super();
  6145. this.isMeshPhongNodeMaterial = true;
  6146. this.lights = true;
  6147. this.shininessNode = null;
  6148. this.specularNode = null;
  6149. this.setDefaultValues( _defaultValues$7 );
  6150. this.setValues( parameters );
  6151. }
  6152. setupEnvironment( builder ) {
  6153. const envNode = super.setupEnvironment( builder );
  6154. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  6155. }
  6156. setupLightingModel( /*builder*/ ) {
  6157. return new PhongLightingModel();
  6158. }
  6159. setupVariants() {
  6160. // SHININESS
  6161. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  6162. shininess.assign( shininessNode );
  6163. // SPECULAR COLOR
  6164. const specularNode = this.specularNode || materialSpecular;
  6165. specularColor.assign( specularNode );
  6166. }
  6167. copy( source ) {
  6168. this.shininessNode = source.shininessNode;
  6169. this.specularNode = source.specularNode;
  6170. return super.copy( source );
  6171. }
  6172. }
  6173. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  6174. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  6175. return float( 0 );
  6176. }
  6177. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  6178. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  6179. return geometryRoughness;
  6180. } );
  6181. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  6182. const { roughness } = inputs;
  6183. const geometryRoughness = getGeometryRoughness();
  6184. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  6185. roughnessFactor = roughnessFactor.add( geometryRoughness );
  6186. roughnessFactor = roughnessFactor.min( 1.0 );
  6187. return roughnessFactor;
  6188. } );
  6189. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  6190. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  6191. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  6192. const a2 = alpha.pow2();
  6193. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  6194. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  6195. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  6196. } ).setLayout( {
  6197. name: 'V_GGX_SmithCorrelated',
  6198. type: 'float',
  6199. inputs: [
  6200. { name: 'alpha', type: 'float' },
  6201. { name: 'dotNL', type: 'float' },
  6202. { name: 'dotNV', type: 'float' }
  6203. ]
  6204. } ); // validated
  6205. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  6206. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  6207. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  6208. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  6209. const v = div( 0.5, gv.add( gl ) );
  6210. return v.saturate();
  6211. } ).setLayout( {
  6212. name: 'V_GGX_SmithCorrelated_Anisotropic',
  6213. type: 'float',
  6214. inputs: [
  6215. { name: 'alphaT', type: 'float', qualifier: 'in' },
  6216. { name: 'alphaB', type: 'float', qualifier: 'in' },
  6217. { name: 'dotTV', type: 'float', qualifier: 'in' },
  6218. { name: 'dotBV', type: 'float', qualifier: 'in' },
  6219. { name: 'dotTL', type: 'float', qualifier: 'in' },
  6220. { name: 'dotBL', type: 'float', qualifier: 'in' },
  6221. { name: 'dotNV', type: 'float', qualifier: 'in' },
  6222. { name: 'dotNL', type: 'float', qualifier: 'in' }
  6223. ]
  6224. } );
  6225. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  6226. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  6227. // alpha is "roughness squared" in Disney’s reparameterization
  6228. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  6229. const a2 = alpha.pow2();
  6230. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  6231. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  6232. } ).setLayout( {
  6233. name: 'D_GGX',
  6234. type: 'float',
  6235. inputs: [
  6236. { name: 'alpha', type: 'float' },
  6237. { name: 'dotNH', type: 'float' }
  6238. ]
  6239. } ); // validated
  6240. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  6241. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  6242. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  6243. const a2 = alphaT.mul( alphaB );
  6244. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  6245. const v2 = v.dot( v );
  6246. const w2 = a2.div( v2 );
  6247. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  6248. } ).setLayout( {
  6249. name: 'D_GGX_Anisotropic',
  6250. type: 'float',
  6251. inputs: [
  6252. { name: 'alphaT', type: 'float', qualifier: 'in' },
  6253. { name: 'alphaB', type: 'float', qualifier: 'in' },
  6254. { name: 'dotNH', type: 'float', qualifier: 'in' },
  6255. { name: 'dotTH', type: 'float', qualifier: 'in' },
  6256. { name: 'dotBH', type: 'float', qualifier: 'in' }
  6257. ]
  6258. } );
  6259. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  6260. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  6261. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  6262. const normalView = inputs.normalView || transformedNormalView;
  6263. const alpha = roughness.pow2(); // UE4's roughness
  6264. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  6265. const dotNL = normalView.dot( lightDirection ).clamp();
  6266. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  6267. const dotNH = normalView.dot( halfDir ).clamp();
  6268. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  6269. let F = F_Schlick( { f0, f90, dotVH } );
  6270. let V, D;
  6271. if ( defined( USE_IRIDESCENCE ) ) {
  6272. F = iridescence.mix( F, f );
  6273. }
  6274. if ( defined( USE_ANISOTROPY ) ) {
  6275. const dotTL = anisotropyT.dot( lightDirection );
  6276. const dotTV = anisotropyT.dot( positionViewDirection );
  6277. const dotTH = anisotropyT.dot( halfDir );
  6278. const dotBL = anisotropyB.dot( lightDirection );
  6279. const dotBV = anisotropyB.dot( positionViewDirection );
  6280. const dotBH = anisotropyB.dot( halfDir );
  6281. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  6282. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  6283. } else {
  6284. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  6285. D = D_GGX( { alpha, dotNH } );
  6286. }
  6287. return F.mul( V ).mul( D );
  6288. } ); // validated
  6289. // Analytical approximation of the DFG LUT, one half of the
  6290. // split-sum approximation used in indirect specular lighting.
  6291. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  6292. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  6293. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  6294. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  6295. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  6296. const r = roughness.mul( c0 ).add( c1 );
  6297. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  6298. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  6299. return fab;
  6300. } ).setLayout( {
  6301. name: 'DFGApprox',
  6302. type: 'vec2',
  6303. inputs: [
  6304. { name: 'roughness', type: 'float' },
  6305. { name: 'dotNV', type: 'vec3' }
  6306. ]
  6307. } );
  6308. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  6309. const { dotNV, specularColor, specularF90, roughness } = inputs;
  6310. const fab = DFGApprox( { dotNV, roughness } );
  6311. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  6312. } );
  6313. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  6314. const x = dotVH.oneMinus().saturate();
  6315. const x2 = x.mul( x );
  6316. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  6317. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  6318. } ).setLayout( {
  6319. name: 'Schlick_to_F0',
  6320. type: 'vec3',
  6321. inputs: [
  6322. { name: 'f', type: 'vec3' },
  6323. { name: 'f90', type: 'float' },
  6324. { name: 'dotVH', type: 'float' }
  6325. ]
  6326. } );
  6327. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  6328. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  6329. const alpha = roughness.pow2();
  6330. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  6331. const invAlpha = float( 1.0 ).div( alpha );
  6332. const cos2h = dotNH.pow2();
  6333. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  6334. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  6335. } ).setLayout( {
  6336. name: 'D_Charlie',
  6337. type: 'float',
  6338. inputs: [
  6339. { name: 'roughness', type: 'float' },
  6340. { name: 'dotNH', type: 'float' }
  6341. ]
  6342. } );
  6343. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  6344. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  6345. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  6346. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  6347. } ).setLayout( {
  6348. name: 'V_Neubelt',
  6349. type: 'float',
  6350. inputs: [
  6351. { name: 'dotNV', type: 'float' },
  6352. { name: 'dotNL', type: 'float' }
  6353. ]
  6354. } );
  6355. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  6356. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  6357. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  6358. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  6359. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  6360. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  6361. const V = V_Neubelt( { dotNV, dotNL } );
  6362. return sheen.mul( D ).mul( V );
  6363. } );
  6364. // Rect Area Light
  6365. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  6366. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  6367. // code: https://github.com/selfshadow/ltc_code/
  6368. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  6369. const LUT_SIZE = 64.0;
  6370. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  6371. const LUT_BIAS = 0.5 / LUT_SIZE;
  6372. const dotNV = N.dot( V ).saturate();
  6373. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  6374. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  6375. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  6376. return uv;
  6377. } ).setLayout( {
  6378. name: 'LTC_Uv',
  6379. type: 'vec2',
  6380. inputs: [
  6381. { name: 'N', type: 'vec3' },
  6382. { name: 'V', type: 'vec3' },
  6383. { name: 'roughness', type: 'float' }
  6384. ]
  6385. } );
  6386. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  6387. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  6388. // An approximation of the form factor of a horizon-clipped rectangle.
  6389. const l = f.length();
  6390. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  6391. } ).setLayout( {
  6392. name: 'LTC_ClippedSphereFormFactor',
  6393. type: 'float',
  6394. inputs: [
  6395. { name: 'f', type: 'vec3' }
  6396. ]
  6397. } );
  6398. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  6399. const x = v1.dot( v2 );
  6400. const y = x.abs().toVar();
  6401. // rational polynomial approximation to theta / sin( theta ) / 2PI
  6402. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  6403. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  6404. const v = a.div( b );
  6405. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  6406. return v1.cross( v2 ).mul( theta_sintheta );
  6407. } ).setLayout( {
  6408. name: 'LTC_EdgeVectorFormFactor',
  6409. type: 'vec3',
  6410. inputs: [
  6411. { name: 'v1', type: 'vec3' },
  6412. { name: 'v2', type: 'vec3' }
  6413. ]
  6414. } );
  6415. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  6416. // bail if point is on back side of plane of light
  6417. // assumes ccw winding order of light vertices
  6418. const v1 = p1.sub( p0 ).toVar();
  6419. const v2 = p3.sub( p0 ).toVar();
  6420. const lightNormal = v1.cross( v2 );
  6421. const result = vec3().toVar();
  6422. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  6423. // construct orthonormal basis around N
  6424. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  6425. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  6426. // compute transform
  6427. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  6428. // transform rect
  6429. // & project rect onto sphere
  6430. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  6431. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  6432. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  6433. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  6434. // calculate vector form factor
  6435. const vectorFormFactor = vec3( 0 ).toVar();
  6436. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  6437. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  6438. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  6439. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  6440. // adjust for horizon clipping
  6441. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  6442. } );
  6443. return result;
  6444. } ).setLayout( {
  6445. name: 'LTC_Evaluate',
  6446. type: 'vec3',
  6447. inputs: [
  6448. { name: 'N', type: 'vec3' },
  6449. { name: 'V', type: 'vec3' },
  6450. { name: 'P', type: 'vec3' },
  6451. { name: 'mInv', type: 'mat3' },
  6452. { name: 'p0', type: 'vec3' },
  6453. { name: 'p1', type: 'vec3' },
  6454. { name: 'p2', type: 'vec3' },
  6455. { name: 'p3', type: 'vec3' }
  6456. ]
  6457. } );
  6458. // Mipped Bicubic Texture Filtering by N8
  6459. // https://www.shadertoy.com/view/Dl2SDW
  6460. const bC = 1.0 / 6.0;
  6461. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  6462. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  6463. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  6464. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  6465. const g0 = ( a ) => w0( a ).add( w1( a ) );
  6466. const g1 = ( a ) => w2( a ).add( w3( a ) );
  6467. // h0 and h1 are the two offset functions
  6468. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  6469. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  6470. const bicubic = ( textureNode, texelSize, lod ) => {
  6471. const uv = textureNode.uvNode;
  6472. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  6473. const iuv = floor( uvScaled );
  6474. const fuv = fract( uvScaled );
  6475. const g0x = g0( fuv.x );
  6476. const g1x = g1( fuv.x );
  6477. const h0x = h0( fuv.x );
  6478. const h1x = h1( fuv.x );
  6479. const h0y = h0( fuv.y );
  6480. const h1y = h1( fuv.y );
  6481. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  6482. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  6483. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  6484. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  6485. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.uv( p0 ).level( lod ) ), g1x.mul( textureNode.uv( p1 ).level( lod ) ) ) );
  6486. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.uv( p2 ).level( lod ) ), g1x.mul( textureNode.uv( p3 ).level( lod ) ) ) );
  6487. return a.add( b );
  6488. };
  6489. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  6490. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  6491. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  6492. const fLodSizeInv = div( 1.0, fLodSize );
  6493. const cLodSizeInv = div( 1.0, cLodSize );
  6494. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  6495. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  6496. return fract( lodNode ).mix( fSample, cSample );
  6497. } );
  6498. //
  6499. // Transmission
  6500. //
  6501. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  6502. // Direction of refracted light.
  6503. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  6504. // Compute rotation-independant scaling of the model matrix.
  6505. const modelScale = vec3(
  6506. length( modelMatrix[ 0 ].xyz ),
  6507. length( modelMatrix[ 1 ].xyz ),
  6508. length( modelMatrix[ 2 ].xyz )
  6509. );
  6510. // The thickness is specified in local space.
  6511. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  6512. } ).setLayout( {
  6513. name: 'getVolumeTransmissionRay',
  6514. type: 'vec3',
  6515. inputs: [
  6516. { name: 'n', type: 'vec3' },
  6517. { name: 'v', type: 'vec3' },
  6518. { name: 'thickness', type: 'float' },
  6519. { name: 'ior', type: 'float' },
  6520. { name: 'modelMatrix', type: 'mat4' }
  6521. ]
  6522. } );
  6523. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  6524. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  6525. // an IOR of 1.5 results in the default amount of microfacet refraction.
  6526. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  6527. } ).setLayout( {
  6528. name: 'applyIorToRoughness',
  6529. type: 'float',
  6530. inputs: [
  6531. { name: 'roughness', type: 'float' },
  6532. { name: 'ior', type: 'float' }
  6533. ]
  6534. } );
  6535. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  6536. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  6537. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  6538. const vTexture = material.side == BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  6539. const transmissionSample = vTexture.uv( fragCoord );
  6540. //const transmissionSample = viewportMipTexture( fragCoord );
  6541. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  6542. return textureBicubic( transmissionSample, lod );
  6543. } );
  6544. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  6545. If( attenuationDistance.notEqual( 0 ), () => {
  6546. // Compute light attenuation using Beer's law.
  6547. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  6548. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  6549. return transmittance;
  6550. } );
  6551. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  6552. return vec3( 1.0 );
  6553. } ).setLayout( {
  6554. name: 'volumeAttenuation',
  6555. type: 'vec3',
  6556. inputs: [
  6557. { name: 'transmissionDistance', type: 'float' },
  6558. { name: 'attenuationColor', type: 'vec3' },
  6559. { name: 'attenuationDistance', type: 'float' }
  6560. ]
  6561. } );
  6562. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  6563. let transmittedLight, transmittance;
  6564. if ( dispersion ) {
  6565. transmittedLight = vec4().toVar();
  6566. transmittance = vec3().toVar();
  6567. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  6568. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  6569. Loop( { start: 0, end: 3 }, ( { i } ) => {
  6570. const ior = iors.element( i );
  6571. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  6572. const refractedRayExit = position.add( transmissionRay );
  6573. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  6574. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  6575. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  6576. refractionCoords.addAssign( 1.0 );
  6577. refractionCoords.divAssign( 2.0 );
  6578. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  6579. // Sample framebuffer to get pixel the refracted ray hits.
  6580. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  6581. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  6582. transmittedLight.a.addAssign( transmissionSample.a );
  6583. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  6584. } );
  6585. transmittedLight.a.divAssign( 3.0 );
  6586. } else {
  6587. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  6588. const refractedRayExit = position.add( transmissionRay );
  6589. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  6590. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  6591. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  6592. refractionCoords.addAssign( 1.0 );
  6593. refractionCoords.divAssign( 2.0 );
  6594. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  6595. // Sample framebuffer to get pixel the refracted ray hits.
  6596. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  6597. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  6598. }
  6599. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  6600. const dotNV = n.dot( v ).clamp();
  6601. // Get the specular component.
  6602. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  6603. dotNV,
  6604. specularColor,
  6605. specularF90,
  6606. roughness
  6607. } ) );
  6608. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  6609. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  6610. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  6611. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  6612. } );
  6613. //
  6614. // Iridescence
  6615. //
  6616. // XYZ to linear-sRGB color space
  6617. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  6618. 3.2404542, - 0.9692660, 0.0556434,
  6619. - 1.5371385, 1.8760108, - 0.2040259,
  6620. - 0.4985314, 0.0415560, 1.0572252
  6621. );
  6622. // Assume air interface for top
  6623. // Note: We don't handle the case fresnel0 == 1
  6624. const Fresnel0ToIor = ( fresnel0 ) => {
  6625. const sqrtF0 = fresnel0.sqrt();
  6626. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  6627. };
  6628. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  6629. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  6630. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  6631. };
  6632. // Fresnel equations for dielectric/dielectric interfaces.
  6633. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  6634. // Evaluation XYZ sensitivity curves in Fourier space
  6635. const evalSensitivity = ( OPD, shift ) => {
  6636. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  6637. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  6638. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  6639. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  6640. 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() );
  6641. 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() );
  6642. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  6643. const rgb = XYZ_TO_REC709.mul( xyz );
  6644. return rgb;
  6645. };
  6646. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  6647. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  6648. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  6649. // Evaluate the cosTheta on the base layer (Snell law)
  6650. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  6651. // Handle TIR:
  6652. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  6653. If( cosTheta2Sq.lessThan( 0 ), () => {
  6654. return vec3( 1.0 );
  6655. } );
  6656. const cosTheta2 = cosTheta2Sq.sqrt();
  6657. // First interface
  6658. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  6659. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  6660. //const R21 = R12;
  6661. const T121 = R12.oneMinus();
  6662. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  6663. const phi21 = float( Math.PI ).sub( phi12 );
  6664. // Second interface
  6665. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  6666. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  6667. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  6668. const phi23 = vec3(
  6669. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  6670. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  6671. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  6672. );
  6673. // Phase shift
  6674. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  6675. const phi = vec3( phi21 ).add( phi23 );
  6676. // Compound terms
  6677. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  6678. const r123 = R123.sqrt();
  6679. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  6680. // Reflectance term for m = 0 (DC term amplitude)
  6681. const C0 = R12.add( Rs );
  6682. const I = C0.toVar();
  6683. // Reflectance term for m > 0 (pairs of diracs)
  6684. const Cm = Rs.sub( T121 ).toVar();
  6685. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  6686. Cm.mulAssign( r123 );
  6687. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  6688. I.addAssign( Cm.mul( Sm ) );
  6689. } );
  6690. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  6691. return I.max( vec3( 0.0 ) );
  6692. } ).setLayout( {
  6693. name: 'evalIridescence',
  6694. type: 'vec3',
  6695. inputs: [
  6696. { name: 'outsideIOR', type: 'float' },
  6697. { name: 'eta2', type: 'float' },
  6698. { name: 'cosTheta1', type: 'float' },
  6699. { name: 'thinFilmThickness', type: 'float' },
  6700. { name: 'baseF0', type: 'vec3' }
  6701. ]
  6702. } );
  6703. //
  6704. // Sheen
  6705. //
  6706. // This is a curve-fit approxmation to the "Charlie sheen" BRDF integrated over the hemisphere from
  6707. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  6708. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  6709. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  6710. const dotNV = normal.dot( viewDir ).saturate();
  6711. const r2 = roughness.pow2();
  6712. const a = select(
  6713. roughness.lessThan( 0.25 ),
  6714. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  6715. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  6716. );
  6717. const b = select(
  6718. roughness.lessThan( 0.25 ),
  6719. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  6720. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  6721. );
  6722. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  6723. return DG.mul( 1.0 / Math.PI ).saturate();
  6724. } );
  6725. const clearcoatF0 = vec3( 0.04 );
  6726. const clearcoatF90 = float( 1 );
  6727. //
  6728. class PhysicalLightingModel extends LightingModel {
  6729. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  6730. super();
  6731. this.clearcoat = clearcoat;
  6732. this.sheen = sheen;
  6733. this.iridescence = iridescence;
  6734. this.anisotropy = anisotropy;
  6735. this.transmission = transmission;
  6736. this.dispersion = dispersion;
  6737. this.clearcoatRadiance = null;
  6738. this.clearcoatSpecularDirect = null;
  6739. this.clearcoatSpecularIndirect = null;
  6740. this.sheenSpecularDirect = null;
  6741. this.sheenSpecularIndirect = null;
  6742. this.iridescenceFresnel = null;
  6743. this.iridescenceF0 = null;
  6744. }
  6745. start( context ) {
  6746. if ( this.clearcoat === true ) {
  6747. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  6748. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  6749. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  6750. }
  6751. if ( this.sheen === true ) {
  6752. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  6753. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  6754. }
  6755. if ( this.iridescence === true ) {
  6756. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  6757. this.iridescenceFresnel = evalIridescence( {
  6758. outsideIOR: float( 1.0 ),
  6759. eta2: iridescenceIOR,
  6760. cosTheta1: dotNVi,
  6761. thinFilmThickness: iridescenceThickness,
  6762. baseF0: specularColor
  6763. } );
  6764. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  6765. }
  6766. if ( this.transmission === true ) {
  6767. const position = positionWorld;
  6768. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  6769. const n = transformedNormalWorld;
  6770. context.backdrop = getIBLVolumeRefraction(
  6771. n,
  6772. v,
  6773. roughness,
  6774. diffuseColor,
  6775. specularColor,
  6776. specularF90, // specularF90
  6777. position, // positionWorld
  6778. modelWorldMatrix, // modelMatrix
  6779. cameraViewMatrix, // viewMatrix
  6780. cameraProjectionMatrix, // projMatrix
  6781. ior,
  6782. thickness,
  6783. attenuationColor,
  6784. attenuationDistance,
  6785. this.dispersion ? dispersion : null
  6786. );
  6787. context.backdropAlpha = transmission;
  6788. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  6789. }
  6790. }
  6791. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  6792. // Approximates multiscattering in order to preserve energy.
  6793. // http://www.jcgt.org/published/0008/01/03/
  6794. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  6795. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  6796. const fab = DFGApprox( { roughness, dotNV } );
  6797. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  6798. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  6799. const Ess = fab.x.add( fab.y );
  6800. const Ems = Ess.oneMinus();
  6801. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  6802. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  6803. singleScatter.addAssign( FssEss );
  6804. multiScatter.addAssign( Fms.mul( Ems ) );
  6805. }
  6806. direct( { lightDirection, lightColor, reflectedLight } ) {
  6807. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  6808. const irradiance = dotNL.mul( lightColor );
  6809. if ( this.sheen === true ) {
  6810. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  6811. }
  6812. if ( this.clearcoat === true ) {
  6813. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  6814. const ccIrradiance = dotNLcc.mul( lightColor );
  6815. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  6816. }
  6817. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  6818. 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 } ) ) );
  6819. }
  6820. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  6821. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  6822. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  6823. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  6824. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  6825. const N = transformedNormalView;
  6826. const V = positionViewDirection;
  6827. const P = positionView.toVar();
  6828. const uv = LTC_Uv( { N, V, roughness } );
  6829. const t1 = ltc_1.uv( uv ).toVar();
  6830. const t2 = ltc_2.uv( uv ).toVar();
  6831. const mInv = mat3(
  6832. vec3( t1.x, 0, t1.y ),
  6833. vec3( 0, 1, 0 ),
  6834. vec3( t1.z, 0, t1.w )
  6835. ).toVar();
  6836. // LTC Fresnel Approximation by Stephen Hill
  6837. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  6838. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  6839. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  6840. 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 } ) ) );
  6841. }
  6842. indirect( context, stack, builder ) {
  6843. this.indirectDiffuse( context, stack, builder );
  6844. this.indirectSpecular( context, stack, builder );
  6845. this.ambientOcclusion( context, stack, builder );
  6846. }
  6847. indirectDiffuse( { irradiance, reflectedLight } ) {
  6848. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  6849. }
  6850. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  6851. if ( this.sheen === true ) {
  6852. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  6853. sheen,
  6854. IBLSheenBRDF( {
  6855. normal: transformedNormalView,
  6856. viewDir: positionViewDirection,
  6857. roughness: sheenRoughness
  6858. } )
  6859. ) );
  6860. }
  6861. if ( this.clearcoat === true ) {
  6862. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  6863. const clearcoatEnv = EnvironmentBRDF( {
  6864. dotNV: dotNVcc,
  6865. specularColor: clearcoatF0,
  6866. specularF90: clearcoatF90,
  6867. roughness: clearcoatRoughness
  6868. } );
  6869. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  6870. }
  6871. // Both indirect specular and indirect diffuse light accumulate here
  6872. const singleScattering = vec3().toVar( 'singleScattering' );
  6873. const multiScattering = vec3().toVar( 'multiScattering' );
  6874. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  6875. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  6876. const totalScattering = singleScattering.add( multiScattering );
  6877. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  6878. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  6879. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  6880. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  6881. }
  6882. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  6883. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  6884. const aoNV = dotNV.add( ambientOcclusion );
  6885. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  6886. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  6887. if ( this.clearcoat === true ) {
  6888. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  6889. }
  6890. if ( this.sheen === true ) {
  6891. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  6892. }
  6893. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  6894. reflectedLight.indirectSpecular.mulAssign( aoNode );
  6895. }
  6896. finish( context ) {
  6897. const { outgoingLight } = context;
  6898. if ( this.clearcoat === true ) {
  6899. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  6900. const Fcc = F_Schlick( {
  6901. dotVH: dotNVcc,
  6902. f0: clearcoatF0,
  6903. f90: clearcoatF90
  6904. } );
  6905. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  6906. outgoingLight.assign( clearcoatLight );
  6907. }
  6908. if ( this.sheen === true ) {
  6909. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  6910. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  6911. outgoingLight.assign( sheenLight );
  6912. }
  6913. }
  6914. }
  6915. // These defines must match with PMREMGenerator
  6916. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  6917. const cubeUV_m0 = /*@__PURE__*/ float( - 2.0 );
  6918. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  6919. const cubeUV_m1 = /*@__PURE__*/ float( - 1.0 );
  6920. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  6921. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  6922. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  6923. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  6924. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  6925. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  6926. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  6927. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  6928. // These shader functions convert between the UV coordinates of a single face of
  6929. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  6930. // sampling a textureCube (not generally normalized ).
  6931. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  6932. const absDirection = vec3( abs( direction ) ).toVar();
  6933. const face = float( - 1.0 ).toVar();
  6934. If( absDirection.x.greaterThan( absDirection.z ), () => {
  6935. If( absDirection.x.greaterThan( absDirection.y ), () => {
  6936. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  6937. } ).Else( () => {
  6938. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  6939. } );
  6940. } ).Else( () => {
  6941. If( absDirection.z.greaterThan( absDirection.y ), () => {
  6942. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  6943. } ).Else( () => {
  6944. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  6945. } );
  6946. } );
  6947. return face;
  6948. } ).setLayout( {
  6949. name: 'getFace',
  6950. type: 'float',
  6951. inputs: [
  6952. { name: 'direction', type: 'vec3' }
  6953. ]
  6954. } );
  6955. // RH coordinate system; PMREM face-indexing convention
  6956. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  6957. const uv = vec2().toVar();
  6958. If( face.equal( 0.0 ), () => {
  6959. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  6960. } ).ElseIf( face.equal( 1.0 ), () => {
  6961. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  6962. } ).ElseIf( face.equal( 2.0 ), () => {
  6963. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  6964. } ).ElseIf( face.equal( 3.0 ), () => {
  6965. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  6966. } ).ElseIf( face.equal( 4.0 ), () => {
  6967. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  6968. } ).Else( () => {
  6969. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  6970. } );
  6971. return mul( 0.5, uv.add( 1.0 ) );
  6972. } ).setLayout( {
  6973. name: 'getUV',
  6974. type: 'vec2',
  6975. inputs: [
  6976. { name: 'direction', type: 'vec3' },
  6977. { name: 'face', type: 'float' }
  6978. ]
  6979. } );
  6980. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  6981. const mip = float( 0.0 ).toVar();
  6982. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  6983. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  6984. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  6985. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  6986. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  6987. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  6988. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  6989. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  6990. } ).Else( () => {
  6991. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  6992. } );
  6993. return mip;
  6994. } ).setLayout( {
  6995. name: 'roughnessToMip',
  6996. type: 'float',
  6997. inputs: [
  6998. { name: 'roughness', type: 'float' }
  6999. ]
  7000. } );
  7001. // RH coordinate system; PMREM face-indexing convention
  7002. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  7003. const uv = uv_immutable.toVar();
  7004. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  7005. const direction = vec3( uv, 1.0 ).toVar();
  7006. If( face.equal( 0.0 ), () => {
  7007. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  7008. } ).ElseIf( face.equal( 1.0 ), () => {
  7009. direction.assign( direction.xzy );
  7010. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  7011. } ).ElseIf( face.equal( 2.0 ), () => {
  7012. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  7013. } ).ElseIf( face.equal( 3.0 ), () => {
  7014. direction.assign( direction.zyx );
  7015. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  7016. } ).ElseIf( face.equal( 4.0 ), () => {
  7017. direction.assign( direction.xzy );
  7018. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  7019. } ).ElseIf( face.equal( 5.0 ), () => {
  7020. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  7021. } );
  7022. return direction;
  7023. } ).setLayout( {
  7024. name: 'getDirection',
  7025. type: 'vec3',
  7026. inputs: [
  7027. { name: 'uv', type: 'vec2' },
  7028. { name: 'face', type: 'float' }
  7029. ]
  7030. } );
  7031. //
  7032. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  7033. const roughness = float( roughness_immutable );
  7034. const sampleDir = vec3( sampleDir_immutable );
  7035. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  7036. const mipF = fract( mip );
  7037. const mipInt = floor( mip );
  7038. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  7039. If( mipF.notEqual( 0.0 ), () => {
  7040. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  7041. color0.assign( mix( color0, color1, mipF ) );
  7042. } );
  7043. return color0;
  7044. } );
  7045. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  7046. const mipInt = float( mipInt_immutable ).toVar();
  7047. const direction = vec3( direction_immutable );
  7048. const face = float( getFace( direction ) ).toVar();
  7049. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  7050. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  7051. const faceSize = float( exp2( mipInt ) ).toVar();
  7052. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  7053. If( face.greaterThan( 2.0 ), () => {
  7054. uv.y.addAssign( faceSize );
  7055. face.subAssign( 3.0 );
  7056. } );
  7057. uv.x.addAssign( face.mul( faceSize ) );
  7058. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  7059. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  7060. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  7061. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  7062. return envMap.uv( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  7063. } );
  7064. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  7065. const cosTheta = cos( theta );
  7066. // Rodrigues' axis-angle rotation
  7067. const sampleDirection = outputDirection.mul( cosTheta )
  7068. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  7069. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  7070. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  7071. } );
  7072. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  7073. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  7074. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  7075. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  7076. } );
  7077. axis.assign( normalize( axis ) );
  7078. const gl_FragColor = vec3().toVar();
  7079. 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 } ) ) );
  7080. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  7081. If( i.greaterThanEqual( samples ), () => {
  7082. Break();
  7083. } );
  7084. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  7085. 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 } ) ) );
  7086. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  7087. } );
  7088. return vec4( gl_FragColor, 1 );
  7089. } );
  7090. let _generator = null;
  7091. const _cache = new WeakMap();
  7092. function _generateCubeUVSize( imageHeight ) {
  7093. const maxMip = Math.log2( imageHeight ) - 2;
  7094. const texelHeight = 1.0 / imageHeight;
  7095. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  7096. return { texelWidth, texelHeight, maxMip };
  7097. }
  7098. function _getPMREMFromTexture( texture ) {
  7099. let cacheTexture = _cache.get( texture );
  7100. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  7101. if ( pmremVersion !== texture.pmremVersion ) {
  7102. const image = texture.image;
  7103. if ( texture.isCubeTexture ) {
  7104. if ( isCubeMapReady( image ) ) {
  7105. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  7106. } else {
  7107. return null;
  7108. }
  7109. } else {
  7110. if ( isEquirectangularMapReady( image ) ) {
  7111. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  7112. } else {
  7113. return null;
  7114. }
  7115. }
  7116. cacheTexture.pmremVersion = texture.pmremVersion;
  7117. _cache.set( texture, cacheTexture );
  7118. }
  7119. return cacheTexture.texture;
  7120. }
  7121. class PMREMNode extends TempNode {
  7122. static get type() {
  7123. return 'PMREMNode';
  7124. }
  7125. constructor( value, uvNode = null, levelNode = null ) {
  7126. super( 'vec3' );
  7127. this._value = value;
  7128. this._pmrem = null;
  7129. this.uvNode = uvNode;
  7130. this.levelNode = levelNode;
  7131. this._generator = null;
  7132. const defaultTexture = new Texture();
  7133. defaultTexture.isRenderTargetTexture = true;
  7134. this._texture = texture( defaultTexture );
  7135. this._width = uniform( 0 );
  7136. this._height = uniform( 0 );
  7137. this._maxMip = uniform( 0 );
  7138. this.updateBeforeType = NodeUpdateType.RENDER;
  7139. }
  7140. set value( value ) {
  7141. this._value = value;
  7142. this._pmrem = null;
  7143. }
  7144. get value() {
  7145. return this._value;
  7146. }
  7147. updateFromTexture( texture ) {
  7148. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  7149. this._texture.value = texture;
  7150. this._width.value = cubeUVSize.texelWidth;
  7151. this._height.value = cubeUVSize.texelHeight;
  7152. this._maxMip.value = cubeUVSize.maxMip;
  7153. }
  7154. updateBefore() {
  7155. let pmrem = this._pmrem;
  7156. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  7157. const texture = this._value;
  7158. if ( pmremVersion !== texture.pmremVersion ) {
  7159. if ( texture.isPMREMTexture === true ) {
  7160. pmrem = texture;
  7161. } else {
  7162. pmrem = _getPMREMFromTexture( texture );
  7163. }
  7164. if ( pmrem !== null ) {
  7165. this._pmrem = pmrem;
  7166. this.updateFromTexture( pmrem );
  7167. }
  7168. }
  7169. }
  7170. setup( builder ) {
  7171. if ( _generator === null ) {
  7172. _generator = builder.createPMREMGenerator();
  7173. }
  7174. //
  7175. this.updateBefore( builder );
  7176. //
  7177. let uvNode = this.uvNode;
  7178. if ( uvNode === null && builder.context.getUV ) {
  7179. uvNode = builder.context.getUV( this );
  7180. }
  7181. //
  7182. const texture = this.value;
  7183. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  7184. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  7185. }
  7186. //
  7187. let levelNode = this.levelNode;
  7188. if ( levelNode === null && builder.context.getTextureLevel ) {
  7189. levelNode = builder.context.getTextureLevel( this );
  7190. }
  7191. //
  7192. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  7193. }
  7194. }
  7195. function isCubeMapReady( image ) {
  7196. if ( image === null || image === undefined ) return false;
  7197. let count = 0;
  7198. const length = 6;
  7199. for ( let i = 0; i < length; i ++ ) {
  7200. if ( image[ i ] !== undefined ) count ++;
  7201. }
  7202. return count === length;
  7203. }
  7204. function isEquirectangularMapReady( image ) {
  7205. if ( image === null || image === undefined ) return false;
  7206. return image.height > 0;
  7207. }
  7208. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  7209. const _envNodeCache = new WeakMap();
  7210. class EnvironmentNode extends LightingNode {
  7211. static get type() {
  7212. return 'EnvironmentNode';
  7213. }
  7214. constructor( envNode = null ) {
  7215. super();
  7216. this.envNode = envNode;
  7217. }
  7218. setup( builder ) {
  7219. const { material } = builder;
  7220. let envNode = this.envNode;
  7221. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  7222. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  7223. let cacheEnvNode = _envNodeCache.get( value );
  7224. if ( cacheEnvNode === undefined ) {
  7225. cacheEnvNode = pmremTexture( value );
  7226. _envNodeCache.set( value, cacheEnvNode );
  7227. }
  7228. envNode = cacheEnvNode;
  7229. }
  7230. //
  7231. const envMap = material.envMap;
  7232. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  7233. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  7234. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  7235. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  7236. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  7237. const isolateRadiance = cache( radiance );
  7238. const isolateIrradiance = cache( irradiance );
  7239. //
  7240. builder.context.radiance.addAssign( isolateRadiance );
  7241. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  7242. //
  7243. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  7244. if ( clearcoatRadiance ) {
  7245. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  7246. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  7247. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  7248. }
  7249. }
  7250. }
  7251. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  7252. let reflectVec = null;
  7253. return {
  7254. getUV: () => {
  7255. if ( reflectVec === null ) {
  7256. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  7257. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  7258. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  7259. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  7260. }
  7261. return reflectVec;
  7262. },
  7263. getTextureLevel: () => {
  7264. return roughnessNode;
  7265. }
  7266. };
  7267. };
  7268. const createIrradianceContext = ( normalWorldNode ) => {
  7269. return {
  7270. getUV: () => {
  7271. return normalWorldNode;
  7272. },
  7273. getTextureLevel: () => {
  7274. return float( 1.0 );
  7275. }
  7276. };
  7277. };
  7278. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  7279. class MeshStandardNodeMaterial extends NodeMaterial {
  7280. static get type() {
  7281. return 'MeshStandardNodeMaterial';
  7282. }
  7283. constructor( parameters ) {
  7284. super();
  7285. this.isMeshStandardNodeMaterial = true;
  7286. this.lights = true;
  7287. this.emissiveNode = null;
  7288. this.metalnessNode = null;
  7289. this.roughnessNode = null;
  7290. this.setDefaultValues( _defaultValues$6 );
  7291. this.setValues( parameters );
  7292. }
  7293. setupEnvironment( builder ) {
  7294. let envNode = super.setupEnvironment( builder );
  7295. if ( envNode === null && builder.environmentNode ) {
  7296. envNode = builder.environmentNode;
  7297. }
  7298. return envNode ? new EnvironmentNode( envNode ) : null;
  7299. }
  7300. setupLightingModel( /*builder*/ ) {
  7301. return new PhysicalLightingModel();
  7302. }
  7303. setupSpecular() {
  7304. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  7305. specularColor.assign( specularColorNode );
  7306. specularF90.assign( 1.0 );
  7307. }
  7308. setupVariants() {
  7309. // METALNESS
  7310. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  7311. metalness.assign( metalnessNode );
  7312. // ROUGHNESS
  7313. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  7314. roughnessNode = getRoughness( { roughness: roughnessNode } );
  7315. roughness.assign( roughnessNode );
  7316. // SPECULAR COLOR
  7317. this.setupSpecular();
  7318. // DIFFUSE COLOR
  7319. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  7320. }
  7321. copy( source ) {
  7322. this.emissiveNode = source.emissiveNode;
  7323. this.metalnessNode = source.metalnessNode;
  7324. this.roughnessNode = source.roughnessNode;
  7325. return super.copy( source );
  7326. }
  7327. }
  7328. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  7329. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  7330. static get type() {
  7331. return 'MeshPhysicalNodeMaterial';
  7332. }
  7333. constructor( parameters ) {
  7334. super();
  7335. this.isMeshPhysicalNodeMaterial = true;
  7336. this.clearcoatNode = null;
  7337. this.clearcoatRoughnessNode = null;
  7338. this.clearcoatNormalNode = null;
  7339. this.sheenNode = null;
  7340. this.sheenRoughnessNode = null;
  7341. this.iridescenceNode = null;
  7342. this.iridescenceIORNode = null;
  7343. this.iridescenceThicknessNode = null;
  7344. this.specularIntensityNode = null;
  7345. this.specularColorNode = null;
  7346. this.iorNode = null;
  7347. this.transmissionNode = null;
  7348. this.thicknessNode = null;
  7349. this.attenuationDistanceNode = null;
  7350. this.attenuationColorNode = null;
  7351. this.dispersionNode = null;
  7352. this.anisotropyNode = null;
  7353. this.setDefaultValues( _defaultValues$5 );
  7354. this.setValues( parameters );
  7355. }
  7356. get useClearcoat() {
  7357. return this.clearcoat > 0 || this.clearcoatNode !== null;
  7358. }
  7359. get useIridescence() {
  7360. return this.iridescence > 0 || this.iridescenceNode !== null;
  7361. }
  7362. get useSheen() {
  7363. return this.sheen > 0 || this.sheenNode !== null;
  7364. }
  7365. get useAnisotropy() {
  7366. return this.anisotropy > 0 || this.anisotropyNode !== null;
  7367. }
  7368. get useTransmission() {
  7369. return this.transmission > 0 || this.transmissionNode !== null;
  7370. }
  7371. get useDispersion() {
  7372. return this.dispersion > 0 || this.dispersionNode !== null;
  7373. }
  7374. setupSpecular() {
  7375. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  7376. ior.assign( iorNode );
  7377. 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 ) );
  7378. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  7379. }
  7380. setupLightingModel( /*builder*/ ) {
  7381. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  7382. }
  7383. setupVariants( builder ) {
  7384. super.setupVariants( builder );
  7385. // CLEARCOAT
  7386. if ( this.useClearcoat ) {
  7387. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  7388. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  7389. clearcoat.assign( clearcoatNode );
  7390. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  7391. }
  7392. // SHEEN
  7393. if ( this.useSheen ) {
  7394. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  7395. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  7396. sheen.assign( sheenNode );
  7397. sheenRoughness.assign( sheenRoughnessNode );
  7398. }
  7399. // IRIDESCENCE
  7400. if ( this.useIridescence ) {
  7401. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  7402. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  7403. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  7404. iridescence.assign( iridescenceNode );
  7405. iridescenceIOR.assign( iridescenceIORNode );
  7406. iridescenceThickness.assign( iridescenceThicknessNode );
  7407. }
  7408. // ANISOTROPY
  7409. if ( this.useAnisotropy ) {
  7410. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  7411. anisotropy.assign( anisotropyV.length() );
  7412. If( anisotropy.equal( 0.0 ), () => {
  7413. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  7414. } ).Else( () => {
  7415. anisotropyV.divAssign( vec2( anisotropy ) );
  7416. anisotropy.assign( anisotropy.saturate() );
  7417. } );
  7418. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  7419. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  7420. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  7421. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  7422. }
  7423. // TRANSMISSION
  7424. if ( this.useTransmission ) {
  7425. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  7426. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  7427. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  7428. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  7429. transmission.assign( transmissionNode );
  7430. thickness.assign( thicknessNode );
  7431. attenuationDistance.assign( attenuationDistanceNode );
  7432. attenuationColor.assign( attenuationColorNode );
  7433. if ( this.useDispersion ) {
  7434. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  7435. dispersion.assign( dispersionNode );
  7436. }
  7437. }
  7438. }
  7439. setupClearcoatNormal() {
  7440. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  7441. }
  7442. setup( builder ) {
  7443. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  7444. super.setup( builder );
  7445. }
  7446. copy( source ) {
  7447. this.clearcoatNode = source.clearcoatNode;
  7448. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  7449. this.clearcoatNormalNode = source.clearcoatNormalNode;
  7450. this.sheenNode = source.sheenNode;
  7451. this.sheenRoughnessNode = source.sheenRoughnessNode;
  7452. this.iridescenceNode = source.iridescenceNode;
  7453. this.iridescenceIORNode = source.iridescenceIORNode;
  7454. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  7455. this.specularIntensityNode = source.specularIntensityNode;
  7456. this.specularColorNode = source.specularColorNode;
  7457. this.transmissionNode = source.transmissionNode;
  7458. this.thicknessNode = source.thicknessNode;
  7459. this.attenuationDistanceNode = source.attenuationDistanceNode;
  7460. this.attenuationColorNode = source.attenuationColorNode;
  7461. this.dispersionNode = source.dispersionNode;
  7462. this.anisotropyNode = source.anisotropyNode;
  7463. return super.copy( source );
  7464. }
  7465. }
  7466. class SSSLightingModel extends PhysicalLightingModel {
  7467. constructor( useClearcoat, useSheen, useIridescence, useSSS ) {
  7468. super( useClearcoat, useSheen, useIridescence );
  7469. this.useSSS = useSSS;
  7470. }
  7471. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  7472. if ( this.useSSS === true ) {
  7473. const material = builder.material;
  7474. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  7475. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  7476. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  7477. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  7478. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  7479. }
  7480. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  7481. }
  7482. }
  7483. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  7484. static get type() {
  7485. return 'MeshSSSNodeMaterial';
  7486. }
  7487. constructor( parameters ) {
  7488. super( parameters );
  7489. this.thicknessColorNode = null;
  7490. this.thicknessDistortionNode = float( 0.1 );
  7491. this.thicknessAmbientNode = float( 0.0 );
  7492. this.thicknessAttenuationNode = float( .1 );
  7493. this.thicknessPowerNode = float( 2.0 );
  7494. this.thicknessScaleNode = float( 10.0 );
  7495. }
  7496. get useSSS() {
  7497. return this.thicknessColorNode !== null;
  7498. }
  7499. setupLightingModel( /*builder*/ ) {
  7500. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useSSS );
  7501. }
  7502. copy( source ) {
  7503. this.thicknessColorNode = source.thicknessColorNode;
  7504. this.thicknessDistortionNode = source.thicknessDistortionNode;
  7505. this.thicknessAmbientNode = source.thicknessAmbientNode;
  7506. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  7507. this.thicknessPowerNode = source.thicknessPowerNode;
  7508. this.thicknessScaleNode = source.thicknessScaleNode;
  7509. return super.copy( source );
  7510. }
  7511. }
  7512. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  7513. // dotNL will be from -1.0 to 1.0
  7514. const dotNL = normal.dot( lightDirection );
  7515. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  7516. if ( builder.material.gradientMap ) {
  7517. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  7518. return vec3( gradientMap.r );
  7519. } else {
  7520. const fw = coord.fwidth().mul( 0.5 );
  7521. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  7522. }
  7523. } );
  7524. class ToonLightingModel extends LightingModel {
  7525. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  7526. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  7527. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  7528. }
  7529. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  7530. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  7531. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  7532. }
  7533. }
  7534. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  7535. class MeshToonNodeMaterial extends NodeMaterial {
  7536. static get type() {
  7537. return 'MeshToonNodeMaterial';
  7538. }
  7539. constructor( parameters ) {
  7540. super();
  7541. this.isMeshToonNodeMaterial = true;
  7542. this.lights = true;
  7543. this.setDefaultValues( _defaultValues$4 );
  7544. this.setValues( parameters );
  7545. }
  7546. setupLightingModel( /*builder*/ ) {
  7547. return new ToonLightingModel();
  7548. }
  7549. }
  7550. class MatcapUVNode extends TempNode {
  7551. static get type() {
  7552. return 'MatcapUVNode';
  7553. }
  7554. constructor() {
  7555. super( 'vec2' );
  7556. }
  7557. setup() {
  7558. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  7559. const y = positionViewDirection.cross( x );
  7560. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  7561. }
  7562. }
  7563. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  7564. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  7565. class MeshMatcapNodeMaterial extends NodeMaterial {
  7566. static get type() {
  7567. return 'MeshMatcapNodeMaterial';
  7568. }
  7569. constructor( parameters ) {
  7570. super();
  7571. this.lights = false;
  7572. this.isMeshMatcapNodeMaterial = true;
  7573. this.setDefaultValues( _defaultValues$3 );
  7574. this.setValues( parameters );
  7575. }
  7576. setupVariants( builder ) {
  7577. const uv = matcapUV;
  7578. let matcapColor;
  7579. if ( builder.material.matcap ) {
  7580. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  7581. } else {
  7582. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  7583. }
  7584. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  7585. }
  7586. }
  7587. const _defaultValues$2 = /*@__PURE__*/ new PointsMaterial();
  7588. class PointsNodeMaterial extends NodeMaterial {
  7589. static get type() {
  7590. return 'PointsNodeMaterial';
  7591. }
  7592. constructor( parameters ) {
  7593. super();
  7594. this.isPointsNodeMaterial = true;
  7595. this.lights = false;
  7596. this.transparent = true;
  7597. this.sizeNode = null;
  7598. this.setDefaultValues( _defaultValues$2 );
  7599. this.setValues( parameters );
  7600. }
  7601. copy( source ) {
  7602. this.sizeNode = source.sizeNode;
  7603. return super.copy( source );
  7604. }
  7605. }
  7606. class RotateNode extends TempNode {
  7607. static get type() {
  7608. return 'RotateNode';
  7609. }
  7610. constructor( positionNode, rotationNode ) {
  7611. super();
  7612. this.positionNode = positionNode;
  7613. this.rotationNode = rotationNode;
  7614. }
  7615. getNodeType( builder ) {
  7616. return this.positionNode.getNodeType( builder );
  7617. }
  7618. setup( builder ) {
  7619. const { rotationNode, positionNode } = this;
  7620. const nodeType = this.getNodeType( builder );
  7621. if ( nodeType === 'vec2' ) {
  7622. const cosAngle = rotationNode.cos();
  7623. const sinAngle = rotationNode.sin();
  7624. const rotationMatrix = mat2(
  7625. cosAngle, sinAngle,
  7626. sinAngle.negate(), cosAngle
  7627. );
  7628. return rotationMatrix.mul( positionNode );
  7629. } else {
  7630. const rotation = rotationNode;
  7631. 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 ) );
  7632. 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 ) );
  7633. 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 ) );
  7634. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  7635. }
  7636. }
  7637. }
  7638. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  7639. const _defaultValues$1 = /*@__PURE__*/ new SpriteMaterial();
  7640. class SpriteNodeMaterial extends NodeMaterial {
  7641. static get type() {
  7642. return 'SpriteNodeMaterial';
  7643. }
  7644. constructor( parameters ) {
  7645. super();
  7646. this.isSpriteNodeMaterial = true;
  7647. this.lights = false;
  7648. this._useSizeAttenuation = true;
  7649. this.positionNode = null;
  7650. this.rotationNode = null;
  7651. this.scaleNode = null;
  7652. this.setDefaultValues( _defaultValues$1 );
  7653. this.setValues( parameters );
  7654. }
  7655. setupPosition( { object, camera, context } ) {
  7656. const sizeAttenuation = this.sizeAttenuation;
  7657. // < VERTEX STAGE >
  7658. const { positionNode, rotationNode, scaleNode } = this;
  7659. const vertex = positionLocal;
  7660. let mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  7661. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  7662. if ( scaleNode !== null ) {
  7663. scale = scale.mul( scaleNode );
  7664. }
  7665. if ( ! sizeAttenuation ) {
  7666. if ( camera.isPerspectiveCamera ) {
  7667. scale = scale.mul( mvPosition.z.negate() );
  7668. } else {
  7669. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  7670. scale = scale.mul( orthoScale.mul( 2 ) );
  7671. }
  7672. }
  7673. let alignedPosition = vertex.xy;
  7674. if ( object.center && object.center.isVector2 === true ) {
  7675. const center = reference$1( 'center', 'vec2' );
  7676. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  7677. }
  7678. alignedPosition = alignedPosition.mul( scale );
  7679. const rotation = float( rotationNode || materialRotation );
  7680. const rotatedPosition = rotate( alignedPosition, rotation );
  7681. mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  7682. const modelViewProjection = cameraProjectionMatrix.mul( mvPosition );
  7683. context.vertex = vertex;
  7684. return modelViewProjection;
  7685. }
  7686. copy( source ) {
  7687. this.positionNode = source.positionNode;
  7688. this.rotationNode = source.rotationNode;
  7689. this.scaleNode = source.scaleNode;
  7690. return super.copy( source );
  7691. }
  7692. get sizeAttenuation() {
  7693. return this._useSizeAttenuation;
  7694. }
  7695. set sizeAttenuation( value ) {
  7696. if ( this._useSizeAttenuation !== value ) {
  7697. this._useSizeAttenuation = value;
  7698. this.needsUpdate = true;
  7699. }
  7700. }
  7701. }
  7702. class ShadowMaskModel extends LightingModel {
  7703. constructor() {
  7704. super();
  7705. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  7706. }
  7707. direct( { shadowMask } ) {
  7708. this.shadowNode.mulAssign( shadowMask );
  7709. }
  7710. finish( context ) {
  7711. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  7712. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  7713. }
  7714. }
  7715. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  7716. class ShadowNodeMaterial extends NodeMaterial {
  7717. static get type() {
  7718. return 'ShadowNodeMaterial';
  7719. }
  7720. constructor( parameters ) {
  7721. super();
  7722. this.isShadowNodeMaterial = true;
  7723. this.lights = true;
  7724. this.setDefaultValues( _defaultValues );
  7725. this.setValues( parameters );
  7726. }
  7727. setupLightingModel( /*builder*/ ) {
  7728. return new ShadowMaskModel();
  7729. }
  7730. }
  7731. const normal = Fn( ( { texture, uv } ) => {
  7732. const epsilon = 0.0001;
  7733. const ret = vec3().toVar();
  7734. If( uv.x.lessThan( epsilon ), () => {
  7735. ret.assign( vec3( 1, 0, 0 ) );
  7736. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  7737. ret.assign( vec3( 0, 1, 0 ) );
  7738. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  7739. ret.assign( vec3( 0, 0, 1 ) );
  7740. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  7741. ret.assign( vec3( - 1, 0, 0 ) );
  7742. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  7743. ret.assign( vec3( 0, - 1, 0 ) );
  7744. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  7745. ret.assign( vec3( 0, 0, - 1 ) );
  7746. } ).Else( () => {
  7747. const step = 0.01;
  7748. 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 );
  7749. 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 );
  7750. 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 );
  7751. ret.assign( vec3( x, y, z ) );
  7752. } );
  7753. return ret.normalize();
  7754. } );
  7755. class Texture3DNode extends TextureNode {
  7756. static get type() {
  7757. return 'Texture3DNode';
  7758. }
  7759. constructor( value, uvNode = null, levelNode = null ) {
  7760. super( value, uvNode, levelNode );
  7761. this.isTexture3DNode = true;
  7762. }
  7763. getInputType( /*builder*/ ) {
  7764. return 'texture3D';
  7765. }
  7766. getDefaultUV() {
  7767. return vec3( 0.5, 0.5, 0.5 );
  7768. }
  7769. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  7770. setupUV( builder, uvNode ) {
  7771. return uvNode;
  7772. }
  7773. generateUV( builder, uvNode ) {
  7774. return uvNode.build( builder, 'vec3' );
  7775. }
  7776. normal( uvNode ) {
  7777. return normal( { texture: this, uv: uvNode } );
  7778. }
  7779. }
  7780. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  7781. class VolumeNodeMaterial extends NodeMaterial {
  7782. static get type() {
  7783. return 'VolumeNodeMaterial';
  7784. }
  7785. constructor( params = {} ) {
  7786. super();
  7787. this.lights = false;
  7788. this.isVolumeNodeMaterial = true;
  7789. this.testNode = null;
  7790. this.setValues( params );
  7791. }
  7792. setup( builder ) {
  7793. const map = texture3D( this.map, null, 0 );
  7794. const hitBox = Fn( ( { orig, dir } ) => {
  7795. const box_min = vec3( - 0.5 );
  7796. const box_max = vec3( 0.5 );
  7797. const inv_dir = dir.reciprocal();
  7798. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  7799. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  7800. const tmin = min$1( tmin_tmp, tmax_tmp );
  7801. const tmax = max$1( tmin_tmp, tmax_tmp );
  7802. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  7803. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  7804. return vec2( t0, t1 );
  7805. } );
  7806. this.fragmentNode = Fn( () => {
  7807. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  7808. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  7809. const rayDir = vDirection.normalize();
  7810. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  7811. bounds.x.greaterThan( bounds.y ).discard();
  7812. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  7813. const p = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  7814. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  7815. const delta = float( min$1( inc.x, min$1( inc.y, inc.z ) ) ).toVar( 'delta' ); // used 'delta' name in loop
  7816. delta.divAssign( materialReference( 'steps', 'float' ) );
  7817. const ac = vec4( materialReference( 'base', 'color' ), 0.0 ).toVar();
  7818. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  7819. const d = property( 'float', 'd' ).assign( map.uv( p.add( 0.5 ) ).r );
  7820. if ( this.testNode !== null ) {
  7821. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  7822. } else {
  7823. // default to show surface of mesh
  7824. ac.a.assign( 1 );
  7825. Break();
  7826. }
  7827. p.addAssign( rayDir.mul( delta ) );
  7828. } );
  7829. ac.a.equal( 0 ).discard();
  7830. return vec4( ac );
  7831. } )();
  7832. super.setup( builder );
  7833. }
  7834. }
  7835. class Animation {
  7836. constructor( nodes, info ) {
  7837. this.nodes = nodes;
  7838. this.info = info;
  7839. this._context = self;
  7840. this._animationLoop = null;
  7841. this._requestId = null;
  7842. }
  7843. start() {
  7844. const update = ( time, frame ) => {
  7845. this._requestId = this._context.requestAnimationFrame( update );
  7846. if ( this.info.autoReset === true ) this.info.reset();
  7847. this.nodes.nodeFrame.update();
  7848. this.info.frame = this.nodes.nodeFrame.frameId;
  7849. if ( this._animationLoop !== null ) this._animationLoop( time, frame );
  7850. };
  7851. update();
  7852. }
  7853. stop() {
  7854. this._context.cancelAnimationFrame( this._requestId );
  7855. this._requestId = null;
  7856. }
  7857. setAnimationLoop( callback ) {
  7858. this._animationLoop = callback;
  7859. }
  7860. setContext( context ) {
  7861. this._context = context;
  7862. }
  7863. dispose() {
  7864. this.stop();
  7865. }
  7866. }
  7867. class ChainMap {
  7868. constructor() {
  7869. this.weakMap = new WeakMap();
  7870. }
  7871. get( keys ) {
  7872. let map = this.weakMap;
  7873. for ( let i = 0; i < keys.length; i ++ ) {
  7874. map = map.get( keys[ i ] );
  7875. if ( map === undefined ) return undefined;
  7876. }
  7877. return map.get( keys[ keys.length - 1 ] );
  7878. }
  7879. set( keys, value ) {
  7880. let map = this.weakMap;
  7881. for ( let i = 0; i < keys.length; i ++ ) {
  7882. const key = keys[ i ];
  7883. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  7884. map = map.get( key );
  7885. }
  7886. return map.set( keys[ keys.length - 1 ], value );
  7887. }
  7888. delete( keys ) {
  7889. let map = this.weakMap;
  7890. for ( let i = 0; i < keys.length; i ++ ) {
  7891. map = map.get( keys[ i ] );
  7892. if ( map === undefined ) return false;
  7893. }
  7894. return map.delete( keys[ keys.length - 1 ] );
  7895. }
  7896. }
  7897. let _id$7 = 0;
  7898. function getKeys( obj ) {
  7899. const keys = Object.keys( obj );
  7900. let proto = Object.getPrototypeOf( obj );
  7901. while ( proto ) {
  7902. const descriptors = Object.getOwnPropertyDescriptors( proto );
  7903. for ( const key in descriptors ) {
  7904. if ( descriptors[ key ] !== undefined ) {
  7905. const descriptor = descriptors[ key ];
  7906. if ( descriptor && typeof descriptor.get === 'function' ) {
  7907. keys.push( key );
  7908. }
  7909. }
  7910. }
  7911. proto = Object.getPrototypeOf( proto );
  7912. }
  7913. return keys;
  7914. }
  7915. class RenderObject {
  7916. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  7917. this._nodes = nodes;
  7918. this._geometries = geometries;
  7919. this.id = _id$7 ++;
  7920. this.renderer = renderer;
  7921. this.object = object;
  7922. this.material = material;
  7923. this.scene = scene;
  7924. this.camera = camera;
  7925. this.lightsNode = lightsNode;
  7926. this.context = renderContext;
  7927. this.geometry = object.geometry;
  7928. this.version = material.version;
  7929. this.drawRange = null;
  7930. this.attributes = null;
  7931. this.pipeline = null;
  7932. this.vertexBuffers = null;
  7933. this.drawParams = null;
  7934. this.bundle = null;
  7935. this.clippingContext = clippingContext;
  7936. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  7937. this.initialNodesCacheKey = this.getDynamicCacheKey();
  7938. this.initialCacheKey = this.getCacheKey();
  7939. this._nodeBuilderState = null;
  7940. this._bindings = null;
  7941. this._monitor = null;
  7942. this.onDispose = null;
  7943. this.isRenderObject = true;
  7944. this.onMaterialDispose = () => {
  7945. this.dispose();
  7946. };
  7947. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  7948. }
  7949. updateClipping( parent ) {
  7950. this.clippingContext = parent;
  7951. }
  7952. get clippingNeedsUpdate() {
  7953. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  7954. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  7955. return true;
  7956. }
  7957. get hardwareClippingPlanes() {
  7958. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  7959. }
  7960. getNodeBuilderState() {
  7961. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  7962. }
  7963. getMonitor() {
  7964. return this._monitor || ( this._monitor = this.getNodeBuilderState().monitor );
  7965. }
  7966. getBindings() {
  7967. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  7968. }
  7969. getIndex() {
  7970. return this._geometries.getIndex( this );
  7971. }
  7972. getIndirect() {
  7973. return this._geometries.getIndirect( this );
  7974. }
  7975. getChainArray() {
  7976. return [ this.object, this.material, this.context, this.lightsNode ];
  7977. }
  7978. setGeometry( geometry ) {
  7979. this.geometry = geometry;
  7980. this.attributes = null;
  7981. }
  7982. getAttributes() {
  7983. if ( this.attributes !== null ) return this.attributes;
  7984. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  7985. const geometry = this.geometry;
  7986. const attributes = [];
  7987. const vertexBuffers = new Set();
  7988. for ( const nodeAttribute of nodeAttributes ) {
  7989. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  7990. if ( attribute === undefined ) continue;
  7991. attributes.push( attribute );
  7992. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  7993. vertexBuffers.add( bufferAttribute );
  7994. }
  7995. this.attributes = attributes;
  7996. this.vertexBuffers = Array.from( vertexBuffers.values() );
  7997. return attributes;
  7998. }
  7999. getVertexBuffers() {
  8000. if ( this.vertexBuffers === null ) this.getAttributes();
  8001. return this.vertexBuffers;
  8002. }
  8003. getDrawParameters() {
  8004. const { object, material, geometry, group, drawRange } = this;
  8005. const drawParams = this.drawParams || ( this.drawParams = {
  8006. vertexCount: 0,
  8007. firstVertex: 0,
  8008. instanceCount: 0,
  8009. firstInstance: 0
  8010. } );
  8011. const index = this.getIndex();
  8012. const hasIndex = ( index !== null );
  8013. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  8014. if ( instanceCount === 0 ) return null;
  8015. drawParams.instanceCount = instanceCount;
  8016. if ( object.isBatchedMesh === true ) return drawParams;
  8017. let rangeFactor = 1;
  8018. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  8019. rangeFactor = 2;
  8020. }
  8021. let firstVertex = drawRange.start * rangeFactor;
  8022. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  8023. if ( group !== null ) {
  8024. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  8025. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  8026. }
  8027. const position = geometry.attributes.position;
  8028. let itemCount = Infinity;
  8029. if ( hasIndex ) {
  8030. itemCount = index.count;
  8031. } else if ( position !== undefined && position !== null ) {
  8032. itemCount = position.count;
  8033. }
  8034. firstVertex = Math.max( firstVertex, 0 );
  8035. lastVertex = Math.min( lastVertex, itemCount );
  8036. const count = lastVertex - firstVertex;
  8037. if ( count < 0 || count === Infinity ) return null;
  8038. drawParams.vertexCount = count;
  8039. drawParams.firstVertex = firstVertex;
  8040. return drawParams;
  8041. }
  8042. getGeometryCacheKey() {
  8043. const { geometry } = this;
  8044. let cacheKey = '';
  8045. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  8046. const attribute = geometry.attributes[ name ];
  8047. cacheKey += name + ',';
  8048. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  8049. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  8050. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  8051. if ( attribute.normalized ) cacheKey += 'n,';
  8052. }
  8053. if ( geometry.index ) {
  8054. cacheKey += 'index,';
  8055. }
  8056. return cacheKey;
  8057. }
  8058. getMaterialCacheKey() {
  8059. const { object, material } = this;
  8060. let cacheKey = material.customProgramCacheKey();
  8061. for ( const property of getKeys( material ) ) {
  8062. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  8063. const value = material[ property ];
  8064. let valueKey;
  8065. if ( value !== null ) {
  8066. // some material values require a formatting
  8067. const type = typeof value;
  8068. if ( type === 'number' ) {
  8069. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  8070. } else if ( type === 'object' ) {
  8071. valueKey = '{';
  8072. if ( value.isTexture ) {
  8073. valueKey += value.mapping;
  8074. }
  8075. valueKey += '}';
  8076. } else {
  8077. valueKey = String( value );
  8078. }
  8079. } else {
  8080. valueKey = String( value );
  8081. }
  8082. cacheKey += /*property + ':' +*/ valueKey + ',';
  8083. }
  8084. cacheKey += this.clippingContextCacheKey + ',';
  8085. if ( object.geometry ) {
  8086. cacheKey += this.getGeometryCacheKey();
  8087. }
  8088. if ( object.skeleton ) {
  8089. cacheKey += object.skeleton.bones.length + ',';
  8090. }
  8091. if ( object.morphTargetInfluences ) {
  8092. cacheKey += object.morphTargetInfluences.length + ',';
  8093. }
  8094. if ( object.isBatchedMesh ) {
  8095. cacheKey += object._matricesTexture.uuid + ',';
  8096. if ( object._colorsTexture !== null ) {
  8097. cacheKey += object._colorsTexture.uuid + ',';
  8098. }
  8099. }
  8100. if ( object.count > 1 ) {
  8101. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  8102. cacheKey += object.uuid + ',';
  8103. }
  8104. cacheKey += object.receiveShadow + ',';
  8105. return hashString( cacheKey );
  8106. }
  8107. get needsGeometryUpdate() {
  8108. return this.geometry.id !== this.object.geometry.id;
  8109. }
  8110. get needsUpdate() {
  8111. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  8112. }
  8113. getDynamicCacheKey() {
  8114. // Environment Nodes Cache Key
  8115. let cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  8116. if ( this.object.receiveShadow ) {
  8117. cacheKey += 1;
  8118. }
  8119. return cacheKey;
  8120. }
  8121. getCacheKey() {
  8122. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  8123. }
  8124. dispose() {
  8125. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  8126. this.onDispose();
  8127. }
  8128. }
  8129. const chainArray = [];
  8130. class RenderObjects {
  8131. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  8132. this.renderer = renderer;
  8133. this.nodes = nodes;
  8134. this.geometries = geometries;
  8135. this.pipelines = pipelines;
  8136. this.bindings = bindings;
  8137. this.info = info;
  8138. this.chainMaps = {};
  8139. }
  8140. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  8141. const chainMap = this.getChainMap( passId );
  8142. // reuse chainArray
  8143. chainArray[ 0 ] = object;
  8144. chainArray[ 1 ] = material;
  8145. chainArray[ 2 ] = renderContext;
  8146. chainArray[ 3 ] = lightsNode;
  8147. let renderObject = chainMap.get( chainArray );
  8148. if ( renderObject === undefined ) {
  8149. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  8150. chainMap.set( chainArray, renderObject );
  8151. } else {
  8152. renderObject.updateClipping( clippingContext );
  8153. if ( renderObject.needsGeometryUpdate ) {
  8154. renderObject.setGeometry( object.geometry );
  8155. }
  8156. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  8157. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  8158. renderObject.dispose();
  8159. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  8160. } else {
  8161. renderObject.version = material.version;
  8162. }
  8163. }
  8164. }
  8165. return renderObject;
  8166. }
  8167. getChainMap( passId = 'default' ) {
  8168. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  8169. }
  8170. dispose() {
  8171. this.chainMaps = {};
  8172. }
  8173. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  8174. const chainMap = this.getChainMap( passId );
  8175. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  8176. renderObject.onDispose = () => {
  8177. this.pipelines.delete( renderObject );
  8178. this.bindings.delete( renderObject );
  8179. this.nodes.delete( renderObject );
  8180. chainMap.delete( renderObject.getChainArray() );
  8181. };
  8182. return renderObject;
  8183. }
  8184. }
  8185. class DataMap {
  8186. constructor() {
  8187. this.data = new WeakMap();
  8188. }
  8189. get( object ) {
  8190. let map = this.data.get( object );
  8191. if ( map === undefined ) {
  8192. map = {};
  8193. this.data.set( object, map );
  8194. }
  8195. return map;
  8196. }
  8197. delete( object ) {
  8198. let map;
  8199. if ( this.data.has( object ) ) {
  8200. map = this.data.get( object );
  8201. this.data.delete( object );
  8202. }
  8203. return map;
  8204. }
  8205. has( object ) {
  8206. return this.data.has( object );
  8207. }
  8208. dispose() {
  8209. this.data = new WeakMap();
  8210. }
  8211. }
  8212. const AttributeType = {
  8213. VERTEX: 1,
  8214. INDEX: 2,
  8215. STORAGE: 3,
  8216. INDIRECT: 4
  8217. };
  8218. // size of a chunk in bytes (STD140 layout)
  8219. const GPU_CHUNK_BYTES = 16;
  8220. // @TODO: Move to src/constants.js
  8221. const BlendColorFactor = 211;
  8222. const OneMinusBlendColorFactor = 212;
  8223. class Attributes extends DataMap {
  8224. constructor( backend ) {
  8225. super();
  8226. this.backend = backend;
  8227. }
  8228. delete( attribute ) {
  8229. const attributeData = super.delete( attribute );
  8230. if ( attributeData !== undefined ) {
  8231. this.backend.destroyAttribute( attribute );
  8232. }
  8233. return attributeData;
  8234. }
  8235. update( attribute, type ) {
  8236. const data = this.get( attribute );
  8237. if ( data.version === undefined ) {
  8238. if ( type === AttributeType.VERTEX ) {
  8239. this.backend.createAttribute( attribute );
  8240. } else if ( type === AttributeType.INDEX ) {
  8241. this.backend.createIndexAttribute( attribute );
  8242. } else if ( type === AttributeType.STORAGE ) {
  8243. this.backend.createStorageAttribute( attribute );
  8244. } else if ( type === AttributeType.INDIRECT ) {
  8245. this.backend.createIndirectStorageAttribute( attribute );
  8246. }
  8247. data.version = this._getBufferAttribute( attribute ).version;
  8248. } else {
  8249. const bufferAttribute = this._getBufferAttribute( attribute );
  8250. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  8251. this.backend.updateAttribute( attribute );
  8252. data.version = bufferAttribute.version;
  8253. }
  8254. }
  8255. }
  8256. _getBufferAttribute( attribute ) {
  8257. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8258. return attribute;
  8259. }
  8260. }
  8261. function arrayNeedsUint32( array ) {
  8262. // assumes larger values usually on last
  8263. for ( let i = array.length - 1; i >= 0; -- i ) {
  8264. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  8265. }
  8266. return false;
  8267. }
  8268. function getWireframeVersion( geometry ) {
  8269. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  8270. }
  8271. function getWireframeIndex( geometry ) {
  8272. const indices = [];
  8273. const geometryIndex = geometry.index;
  8274. const geometryPosition = geometry.attributes.position;
  8275. if ( geometryIndex !== null ) {
  8276. const array = geometryIndex.array;
  8277. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  8278. const a = array[ i + 0 ];
  8279. const b = array[ i + 1 ];
  8280. const c = array[ i + 2 ];
  8281. indices.push( a, b, b, c, c, a );
  8282. }
  8283. } else {
  8284. const array = geometryPosition.array;
  8285. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  8286. const a = i + 0;
  8287. const b = i + 1;
  8288. const c = i + 2;
  8289. indices.push( a, b, b, c, c, a );
  8290. }
  8291. }
  8292. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  8293. attribute.version = getWireframeVersion( geometry );
  8294. return attribute;
  8295. }
  8296. class Geometries extends DataMap {
  8297. constructor( attributes, info ) {
  8298. super();
  8299. this.attributes = attributes;
  8300. this.info = info;
  8301. this.wireframes = new WeakMap();
  8302. this.attributeCall = new WeakMap();
  8303. }
  8304. has( renderObject ) {
  8305. const geometry = renderObject.geometry;
  8306. return super.has( geometry ) && this.get( geometry ).initialized === true;
  8307. }
  8308. updateForRender( renderObject ) {
  8309. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  8310. this.updateAttributes( renderObject );
  8311. }
  8312. initGeometry( renderObject ) {
  8313. const geometry = renderObject.geometry;
  8314. const geometryData = this.get( geometry );
  8315. geometryData.initialized = true;
  8316. this.info.memory.geometries ++;
  8317. const onDispose = () => {
  8318. this.info.memory.geometries --;
  8319. const index = geometry.index;
  8320. const geometryAttributes = renderObject.getAttributes();
  8321. if ( index !== null ) {
  8322. this.attributes.delete( index );
  8323. }
  8324. for ( const geometryAttribute of geometryAttributes ) {
  8325. this.attributes.delete( geometryAttribute );
  8326. }
  8327. const wireframeAttribute = this.wireframes.get( geometry );
  8328. if ( wireframeAttribute !== undefined ) {
  8329. this.attributes.delete( wireframeAttribute );
  8330. }
  8331. geometry.removeEventListener( 'dispose', onDispose );
  8332. };
  8333. geometry.addEventListener( 'dispose', onDispose );
  8334. }
  8335. updateAttributes( renderObject ) {
  8336. // attributes
  8337. const attributes = renderObject.getAttributes();
  8338. for ( const attribute of attributes ) {
  8339. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  8340. this.updateAttribute( attribute, AttributeType.STORAGE );
  8341. } else {
  8342. this.updateAttribute( attribute, AttributeType.VERTEX );
  8343. }
  8344. }
  8345. // indexes
  8346. const index = this.getIndex( renderObject );
  8347. if ( index !== null ) {
  8348. this.updateAttribute( index, AttributeType.INDEX );
  8349. }
  8350. // indirect
  8351. const indirect = renderObject.geometry.indirect;
  8352. if ( indirect !== null ) {
  8353. this.updateAttribute( indirect, AttributeType.INDIRECT );
  8354. }
  8355. }
  8356. updateAttribute( attribute, type ) {
  8357. const callId = this.info.render.calls;
  8358. if ( ! attribute.isInterleavedBufferAttribute ) {
  8359. if ( this.attributeCall.get( attribute ) !== callId ) {
  8360. this.attributes.update( attribute, type );
  8361. this.attributeCall.set( attribute, callId );
  8362. }
  8363. } else {
  8364. if ( this.attributeCall.get( attribute ) === undefined ) {
  8365. this.attributes.update( attribute, type );
  8366. this.attributeCall.set( attribute, callId );
  8367. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  8368. this.attributes.update( attribute, type );
  8369. this.attributeCall.set( attribute.data, callId );
  8370. this.attributeCall.set( attribute, callId );
  8371. }
  8372. }
  8373. }
  8374. getIndirect( renderObject ) {
  8375. return renderObject.geometry.indirect;
  8376. }
  8377. getIndex( renderObject ) {
  8378. const { geometry, material } = renderObject;
  8379. let index = geometry.index;
  8380. if ( material.wireframe === true ) {
  8381. const wireframes = this.wireframes;
  8382. let wireframeAttribute = wireframes.get( geometry );
  8383. if ( wireframeAttribute === undefined ) {
  8384. wireframeAttribute = getWireframeIndex( geometry );
  8385. wireframes.set( geometry, wireframeAttribute );
  8386. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  8387. this.attributes.delete( wireframeAttribute );
  8388. wireframeAttribute = getWireframeIndex( geometry );
  8389. wireframes.set( geometry, wireframeAttribute );
  8390. }
  8391. index = wireframeAttribute;
  8392. }
  8393. return index;
  8394. }
  8395. }
  8396. class Info {
  8397. constructor() {
  8398. this.autoReset = true;
  8399. this.frame = 0;
  8400. this.calls = 0;
  8401. this.render = {
  8402. calls: 0,
  8403. frameCalls: 0,
  8404. drawCalls: 0,
  8405. triangles: 0,
  8406. points: 0,
  8407. lines: 0,
  8408. timestamp: 0,
  8409. previousFrameCalls: 0,
  8410. timestampCalls: 0
  8411. };
  8412. this.compute = {
  8413. calls: 0,
  8414. frameCalls: 0,
  8415. timestamp: 0,
  8416. previousFrameCalls: 0,
  8417. timestampCalls: 0
  8418. };
  8419. this.memory = {
  8420. geometries: 0,
  8421. textures: 0
  8422. };
  8423. }
  8424. update( object, count, instanceCount ) {
  8425. this.render.drawCalls ++;
  8426. if ( object.isMesh || object.isSprite ) {
  8427. this.render.triangles += instanceCount * ( count / 3 );
  8428. } else if ( object.isPoints ) {
  8429. this.render.points += instanceCount * count;
  8430. } else if ( object.isLineSegments ) {
  8431. this.render.lines += instanceCount * ( count / 2 );
  8432. } else if ( object.isLine ) {
  8433. this.render.lines += instanceCount * ( count - 1 );
  8434. } else {
  8435. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  8436. }
  8437. }
  8438. updateTimestamp( type, time ) {
  8439. if ( this[ type ].timestampCalls === 0 ) {
  8440. this[ type ].timestamp = 0;
  8441. }
  8442. this[ type ].timestamp += time;
  8443. this[ type ].timestampCalls ++;
  8444. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  8445. this[ type ].timestampCalls = 0;
  8446. }
  8447. }
  8448. reset() {
  8449. const previousRenderFrameCalls = this.render.frameCalls;
  8450. this.render.previousFrameCalls = previousRenderFrameCalls;
  8451. const previousComputeFrameCalls = this.compute.frameCalls;
  8452. this.compute.previousFrameCalls = previousComputeFrameCalls;
  8453. this.render.drawCalls = 0;
  8454. this.render.frameCalls = 0;
  8455. this.compute.frameCalls = 0;
  8456. this.render.triangles = 0;
  8457. this.render.points = 0;
  8458. this.render.lines = 0;
  8459. }
  8460. dispose() {
  8461. this.reset();
  8462. this.calls = 0;
  8463. this.render.calls = 0;
  8464. this.compute.calls = 0;
  8465. this.render.timestamp = 0;
  8466. this.compute.timestamp = 0;
  8467. this.memory.geometries = 0;
  8468. this.memory.textures = 0;
  8469. }
  8470. }
  8471. class Pipeline {
  8472. constructor( cacheKey ) {
  8473. this.cacheKey = cacheKey;
  8474. this.usedTimes = 0;
  8475. }
  8476. }
  8477. class RenderPipeline extends Pipeline {
  8478. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  8479. super( cacheKey );
  8480. this.vertexProgram = vertexProgram;
  8481. this.fragmentProgram = fragmentProgram;
  8482. }
  8483. }
  8484. class ComputePipeline extends Pipeline {
  8485. constructor( cacheKey, computeProgram ) {
  8486. super( cacheKey );
  8487. this.computeProgram = computeProgram;
  8488. this.isComputePipeline = true;
  8489. }
  8490. }
  8491. let _id$6 = 0;
  8492. class ProgrammableStage {
  8493. constructor( code, type, transforms = null, attributes = null ) {
  8494. this.id = _id$6 ++;
  8495. this.code = code;
  8496. this.stage = type;
  8497. this.transforms = transforms;
  8498. this.attributes = attributes;
  8499. this.usedTimes = 0;
  8500. }
  8501. }
  8502. class Pipelines extends DataMap {
  8503. constructor( backend, nodes ) {
  8504. super();
  8505. this.backend = backend;
  8506. this.nodes = nodes;
  8507. this.bindings = null; // set by the bindings
  8508. this.caches = new Map();
  8509. this.programs = {
  8510. vertex: new Map(),
  8511. fragment: new Map(),
  8512. compute: new Map()
  8513. };
  8514. }
  8515. getForCompute( computeNode, bindings ) {
  8516. const { backend } = this;
  8517. const data = this.get( computeNode );
  8518. if ( this._needsComputeUpdate( computeNode ) ) {
  8519. const previousPipeline = data.pipeline;
  8520. if ( previousPipeline ) {
  8521. previousPipeline.usedTimes --;
  8522. previousPipeline.computeProgram.usedTimes --;
  8523. }
  8524. // get shader
  8525. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  8526. // programmable stage
  8527. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  8528. if ( stageCompute === undefined ) {
  8529. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  8530. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  8531. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  8532. backend.createProgram( stageCompute );
  8533. }
  8534. // determine compute pipeline
  8535. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  8536. let pipeline = this.caches.get( cacheKey );
  8537. if ( pipeline === undefined ) {
  8538. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  8539. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  8540. }
  8541. // keep track of all used times
  8542. pipeline.usedTimes ++;
  8543. stageCompute.usedTimes ++;
  8544. //
  8545. data.version = computeNode.version;
  8546. data.pipeline = pipeline;
  8547. }
  8548. return data.pipeline;
  8549. }
  8550. getForRender( renderObject, promises = null ) {
  8551. const { backend } = this;
  8552. const data = this.get( renderObject );
  8553. if ( this._needsRenderUpdate( renderObject ) ) {
  8554. const previousPipeline = data.pipeline;
  8555. if ( previousPipeline ) {
  8556. previousPipeline.usedTimes --;
  8557. previousPipeline.vertexProgram.usedTimes --;
  8558. previousPipeline.fragmentProgram.usedTimes --;
  8559. }
  8560. // get shader
  8561. const nodeBuilderState = renderObject.getNodeBuilderState();
  8562. // programmable stages
  8563. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  8564. if ( stageVertex === undefined ) {
  8565. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  8566. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex' );
  8567. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  8568. backend.createProgram( stageVertex );
  8569. }
  8570. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  8571. if ( stageFragment === undefined ) {
  8572. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  8573. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment' );
  8574. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  8575. backend.createProgram( stageFragment );
  8576. }
  8577. // determine render pipeline
  8578. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  8579. let pipeline = this.caches.get( cacheKey );
  8580. if ( pipeline === undefined ) {
  8581. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  8582. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  8583. } else {
  8584. renderObject.pipeline = pipeline;
  8585. }
  8586. // keep track of all used times
  8587. pipeline.usedTimes ++;
  8588. stageVertex.usedTimes ++;
  8589. stageFragment.usedTimes ++;
  8590. //
  8591. data.pipeline = pipeline;
  8592. }
  8593. return data.pipeline;
  8594. }
  8595. delete( object ) {
  8596. const pipeline = this.get( object ).pipeline;
  8597. if ( pipeline ) {
  8598. // pipeline
  8599. pipeline.usedTimes --;
  8600. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  8601. // programs
  8602. if ( pipeline.isComputePipeline ) {
  8603. pipeline.computeProgram.usedTimes --;
  8604. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  8605. } else {
  8606. pipeline.fragmentProgram.usedTimes --;
  8607. pipeline.vertexProgram.usedTimes --;
  8608. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  8609. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  8610. }
  8611. }
  8612. return super.delete( object );
  8613. }
  8614. dispose() {
  8615. super.dispose();
  8616. this.caches = new Map();
  8617. this.programs = {
  8618. vertex: new Map(),
  8619. fragment: new Map(),
  8620. compute: new Map()
  8621. };
  8622. }
  8623. updateForRender( renderObject ) {
  8624. this.getForRender( renderObject );
  8625. }
  8626. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  8627. // check for existing pipeline
  8628. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  8629. let pipeline = this.caches.get( cacheKey );
  8630. if ( pipeline === undefined ) {
  8631. pipeline = new ComputePipeline( cacheKey, stageCompute );
  8632. this.caches.set( cacheKey, pipeline );
  8633. this.backend.createComputePipeline( pipeline, bindings );
  8634. }
  8635. return pipeline;
  8636. }
  8637. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  8638. // check for existing pipeline
  8639. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  8640. let pipeline = this.caches.get( cacheKey );
  8641. if ( pipeline === undefined ) {
  8642. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  8643. this.caches.set( cacheKey, pipeline );
  8644. renderObject.pipeline = pipeline;
  8645. this.backend.createRenderPipeline( renderObject, promises );
  8646. }
  8647. return pipeline;
  8648. }
  8649. _getComputeCacheKey( computeNode, stageCompute ) {
  8650. return computeNode.id + ',' + stageCompute.id;
  8651. }
  8652. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  8653. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  8654. }
  8655. _releasePipeline( pipeline ) {
  8656. this.caches.delete( pipeline.cacheKey );
  8657. }
  8658. _releaseProgram( program ) {
  8659. const code = program.code;
  8660. const stage = program.stage;
  8661. this.programs[ stage ].delete( code );
  8662. }
  8663. _needsComputeUpdate( computeNode ) {
  8664. const data = this.get( computeNode );
  8665. return data.pipeline === undefined || data.version !== computeNode.version;
  8666. }
  8667. _needsRenderUpdate( renderObject ) {
  8668. const data = this.get( renderObject );
  8669. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  8670. }
  8671. }
  8672. class Bindings extends DataMap {
  8673. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  8674. super();
  8675. this.backend = backend;
  8676. this.textures = textures;
  8677. this.pipelines = pipelines;
  8678. this.attributes = attributes;
  8679. this.nodes = nodes;
  8680. this.info = info;
  8681. this.pipelines.bindings = this; // assign bindings to pipelines
  8682. }
  8683. getForRender( renderObject ) {
  8684. const bindings = renderObject.getBindings();
  8685. for ( const bindGroup of bindings ) {
  8686. const groupData = this.get( bindGroup );
  8687. if ( groupData.bindGroup === undefined ) {
  8688. // each object defines an array of bindings (ubos, textures, samplers etc.)
  8689. this._init( bindGroup );
  8690. this.backend.createBindings( bindGroup, bindings, 0 );
  8691. groupData.bindGroup = bindGroup;
  8692. }
  8693. }
  8694. return bindings;
  8695. }
  8696. getForCompute( computeNode ) {
  8697. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  8698. for ( const bindGroup of bindings ) {
  8699. const groupData = this.get( bindGroup );
  8700. if ( groupData.bindGroup === undefined ) {
  8701. this._init( bindGroup );
  8702. this.backend.createBindings( bindGroup, bindings, 0 );
  8703. groupData.bindGroup = bindGroup;
  8704. }
  8705. }
  8706. return bindings;
  8707. }
  8708. updateForCompute( computeNode ) {
  8709. this._updateBindings( this.getForCompute( computeNode ) );
  8710. }
  8711. updateForRender( renderObject ) {
  8712. this._updateBindings( this.getForRender( renderObject ) );
  8713. }
  8714. _updateBindings( bindings ) {
  8715. for ( const bindGroup of bindings ) {
  8716. this._update( bindGroup, bindings );
  8717. }
  8718. }
  8719. _init( bindGroup ) {
  8720. for ( const binding of bindGroup.bindings ) {
  8721. if ( binding.isSampledTexture ) {
  8722. this.textures.updateTexture( binding.texture );
  8723. } else if ( binding.isStorageBuffer ) {
  8724. const attribute = binding.attribute;
  8725. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  8726. this.attributes.update( attribute, attributeType );
  8727. }
  8728. }
  8729. }
  8730. _update( bindGroup, bindings ) {
  8731. const { backend } = this;
  8732. let needsBindingsUpdate = false;
  8733. let cacheBindings = true;
  8734. let cacheIndex = 0;
  8735. let version = 0;
  8736. // iterate over all bindings and check if buffer updates or a new binding group is required
  8737. for ( const binding of bindGroup.bindings ) {
  8738. if ( binding.isNodeUniformsGroup ) {
  8739. const updated = this.nodes.updateGroup( binding );
  8740. if ( ! updated ) continue;
  8741. }
  8742. if ( binding.isUniformBuffer ) {
  8743. const updated = binding.update();
  8744. if ( updated ) {
  8745. backend.updateBinding( binding );
  8746. }
  8747. } else if ( binding.isSampler ) {
  8748. binding.update();
  8749. } else if ( binding.isSampledTexture ) {
  8750. const texturesTextureData = this.textures.get( binding.texture );
  8751. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  8752. const updated = binding.update();
  8753. const texture = binding.texture;
  8754. if ( updated ) {
  8755. this.textures.updateTexture( texture );
  8756. }
  8757. const textureData = backend.get( texture );
  8758. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  8759. cacheBindings = false;
  8760. } else {
  8761. cacheIndex = cacheIndex * 10 + texture.id;
  8762. version += texture.version;
  8763. }
  8764. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  8765. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  8766. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  8767. this.textures.updateTexture( texture );
  8768. needsBindingsUpdate = true;
  8769. }
  8770. if ( texture.isStorageTexture === true ) {
  8771. const textureData = this.get( texture );
  8772. if ( binding.store === true ) {
  8773. textureData.needsMipmap = true;
  8774. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  8775. this.backend.generateMipmaps( texture );
  8776. textureData.needsMipmap = false;
  8777. }
  8778. }
  8779. }
  8780. }
  8781. if ( needsBindingsUpdate === true ) {
  8782. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  8783. }
  8784. }
  8785. }
  8786. function painterSortStable( a, b ) {
  8787. if ( a.groupOrder !== b.groupOrder ) {
  8788. return a.groupOrder - b.groupOrder;
  8789. } else if ( a.renderOrder !== b.renderOrder ) {
  8790. return a.renderOrder - b.renderOrder;
  8791. } else if ( a.material.id !== b.material.id ) {
  8792. return a.material.id - b.material.id;
  8793. } else if ( a.z !== b.z ) {
  8794. return a.z - b.z;
  8795. } else {
  8796. return a.id - b.id;
  8797. }
  8798. }
  8799. function reversePainterSortStable( a, b ) {
  8800. if ( a.groupOrder !== b.groupOrder ) {
  8801. return a.groupOrder - b.groupOrder;
  8802. } else if ( a.renderOrder !== b.renderOrder ) {
  8803. return a.renderOrder - b.renderOrder;
  8804. } else if ( a.z !== b.z ) {
  8805. return b.z - a.z;
  8806. } else {
  8807. return a.id - b.id;
  8808. }
  8809. }
  8810. function needsDoublePass( material ) {
  8811. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  8812. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  8813. }
  8814. class RenderList {
  8815. constructor( lighting, scene, camera ) {
  8816. this.renderItems = [];
  8817. this.renderItemsIndex = 0;
  8818. this.opaque = [];
  8819. this.transparentDoublePass = [];
  8820. this.transparent = [];
  8821. this.bundles = [];
  8822. this.lightsNode = lighting.getNode( scene, camera );
  8823. this.lightsArray = [];
  8824. this.scene = scene;
  8825. this.camera = camera;
  8826. this.occlusionQueryCount = 0;
  8827. }
  8828. begin() {
  8829. this.renderItemsIndex = 0;
  8830. this.opaque.length = 0;
  8831. this.transparentDoublePass.length = 0;
  8832. this.transparent.length = 0;
  8833. this.bundles.length = 0;
  8834. this.lightsArray.length = 0;
  8835. this.occlusionQueryCount = 0;
  8836. return this;
  8837. }
  8838. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  8839. let renderItem = this.renderItems[ this.renderItemsIndex ];
  8840. if ( renderItem === undefined ) {
  8841. renderItem = {
  8842. id: object.id,
  8843. object: object,
  8844. geometry: geometry,
  8845. material: material,
  8846. groupOrder: groupOrder,
  8847. renderOrder: object.renderOrder,
  8848. z: z,
  8849. group: group,
  8850. clippingContext: clippingContext
  8851. };
  8852. this.renderItems[ this.renderItemsIndex ] = renderItem;
  8853. } else {
  8854. renderItem.id = object.id;
  8855. renderItem.object = object;
  8856. renderItem.geometry = geometry;
  8857. renderItem.material = material;
  8858. renderItem.groupOrder = groupOrder;
  8859. renderItem.renderOrder = object.renderOrder;
  8860. renderItem.z = z;
  8861. renderItem.group = group;
  8862. renderItem.clippingContext = clippingContext;
  8863. }
  8864. this.renderItemsIndex ++;
  8865. return renderItem;
  8866. }
  8867. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  8868. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  8869. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  8870. if ( material.transparent === true || material.transmission > 0 ) {
  8871. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  8872. this.transparent.push( renderItem );
  8873. } else {
  8874. this.opaque.push( renderItem );
  8875. }
  8876. }
  8877. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  8878. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  8879. if ( material.transparent === true || material.transmission > 0 ) {
  8880. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  8881. this.transparent.unshift( renderItem );
  8882. } else {
  8883. this.opaque.unshift( renderItem );
  8884. }
  8885. }
  8886. pushBundle( group ) {
  8887. this.bundles.push( group );
  8888. }
  8889. pushLight( light ) {
  8890. this.lightsArray.push( light );
  8891. }
  8892. sort( customOpaqueSort, customTransparentSort ) {
  8893. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  8894. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  8895. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  8896. }
  8897. finish() {
  8898. // update lights
  8899. this.lightsNode.setLights( this.lightsArray );
  8900. // Clear references from inactive renderItems in the list
  8901. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  8902. const renderItem = this.renderItems[ i ];
  8903. if ( renderItem.id === null ) break;
  8904. renderItem.id = null;
  8905. renderItem.object = null;
  8906. renderItem.geometry = null;
  8907. renderItem.material = null;
  8908. renderItem.groupOrder = null;
  8909. renderItem.renderOrder = null;
  8910. renderItem.z = null;
  8911. renderItem.group = null;
  8912. renderItem.clippingContext = null;
  8913. }
  8914. }
  8915. }
  8916. class RenderLists {
  8917. constructor( lighting ) {
  8918. this.lighting = lighting;
  8919. this.lists = new ChainMap();
  8920. }
  8921. get( scene, camera ) {
  8922. const lists = this.lists;
  8923. const keys = [ scene, camera ];
  8924. let list = lists.get( keys );
  8925. if ( list === undefined ) {
  8926. list = new RenderList( this.lighting, scene, camera );
  8927. lists.set( keys, list );
  8928. }
  8929. return list;
  8930. }
  8931. dispose() {
  8932. this.lists = new ChainMap();
  8933. }
  8934. }
  8935. let id$1 = 0;
  8936. class RenderContext {
  8937. constructor() {
  8938. this.id = id$1 ++;
  8939. this.color = true;
  8940. this.clearColor = true;
  8941. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  8942. this.depth = true;
  8943. this.clearDepth = true;
  8944. this.clearDepthValue = 1;
  8945. this.stencil = false;
  8946. this.clearStencil = true;
  8947. this.clearStencilValue = 1;
  8948. this.viewport = false;
  8949. this.viewportValue = new Vector4();
  8950. this.scissor = false;
  8951. this.scissorValue = new Vector4();
  8952. this.textures = null;
  8953. this.depthTexture = null;
  8954. this.activeCubeFace = 0;
  8955. this.sampleCount = 1;
  8956. this.width = 0;
  8957. this.height = 0;
  8958. this.isRenderContext = true;
  8959. }
  8960. getCacheKey() {
  8961. return getCacheKey( this );
  8962. }
  8963. }
  8964. function getCacheKey( renderContext ) {
  8965. const { textures, activeCubeFace } = renderContext;
  8966. const values = [ activeCubeFace ];
  8967. for ( const texture of textures ) {
  8968. values.push( texture.id );
  8969. }
  8970. return hashArray( values );
  8971. }
  8972. class RenderContexts {
  8973. constructor() {
  8974. this.chainMaps = {};
  8975. }
  8976. get( scene, camera, renderTarget = null ) {
  8977. const chainKey = [ scene, camera ];
  8978. let attachmentState;
  8979. if ( renderTarget === null ) {
  8980. attachmentState = 'default';
  8981. } else {
  8982. const format = renderTarget.texture.format;
  8983. const count = renderTarget.textures.length;
  8984. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  8985. }
  8986. const chainMap = this.getChainMap( attachmentState );
  8987. let renderState = chainMap.get( chainKey );
  8988. if ( renderState === undefined ) {
  8989. renderState = new RenderContext();
  8990. chainMap.set( chainKey, renderState );
  8991. }
  8992. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  8993. return renderState;
  8994. }
  8995. getChainMap( attachmentState ) {
  8996. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  8997. }
  8998. dispose() {
  8999. this.chainMaps = {};
  9000. }
  9001. }
  9002. const _size$3 = /*@__PURE__*/ new Vector3();
  9003. class Textures extends DataMap {
  9004. constructor( renderer, backend, info ) {
  9005. super();
  9006. this.renderer = renderer;
  9007. this.backend = backend;
  9008. this.info = info;
  9009. }
  9010. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  9011. const renderTargetData = this.get( renderTarget );
  9012. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  9013. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  9014. const textures = renderTarget.textures;
  9015. const size = this.getSize( textures[ 0 ] );
  9016. const mipWidth = size.width >> activeMipmapLevel;
  9017. const mipHeight = size.height >> activeMipmapLevel;
  9018. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  9019. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  9020. let textureNeedsUpdate = false;
  9021. if ( depthTexture === undefined && useDepthTexture ) {
  9022. depthTexture = new DepthTexture();
  9023. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  9024. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  9025. depthTexture.image.width = mipWidth;
  9026. depthTexture.image.height = mipHeight;
  9027. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  9028. }
  9029. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  9030. textureNeedsUpdate = true;
  9031. if ( depthTexture ) {
  9032. depthTexture.needsUpdate = true;
  9033. depthTexture.image.width = mipWidth;
  9034. depthTexture.image.height = mipHeight;
  9035. }
  9036. }
  9037. renderTargetData.width = size.width;
  9038. renderTargetData.height = size.height;
  9039. renderTargetData.textures = textures;
  9040. renderTargetData.depthTexture = depthTexture || null;
  9041. renderTargetData.depth = renderTarget.depthBuffer;
  9042. renderTargetData.stencil = renderTarget.stencilBuffer;
  9043. renderTargetData.renderTarget = renderTarget;
  9044. if ( renderTargetData.sampleCount !== sampleCount ) {
  9045. textureNeedsUpdate = true;
  9046. if ( depthTexture ) {
  9047. depthTexture.needsUpdate = true;
  9048. }
  9049. renderTargetData.sampleCount = sampleCount;
  9050. }
  9051. //
  9052. const options = { sampleCount };
  9053. for ( let i = 0; i < textures.length; i ++ ) {
  9054. const texture = textures[ i ];
  9055. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  9056. this.updateTexture( texture, options );
  9057. }
  9058. if ( depthTexture ) {
  9059. this.updateTexture( depthTexture, options );
  9060. }
  9061. // dispose handler
  9062. if ( renderTargetData.initialized !== true ) {
  9063. renderTargetData.initialized = true;
  9064. // dispose
  9065. const onDispose = () => {
  9066. renderTarget.removeEventListener( 'dispose', onDispose );
  9067. for ( let i = 0; i < textures.length; i ++ ) {
  9068. this._destroyTexture( textures[ i ] );
  9069. }
  9070. if ( depthTexture ) {
  9071. this._destroyTexture( depthTexture );
  9072. }
  9073. this.delete( renderTarget );
  9074. };
  9075. renderTarget.addEventListener( 'dispose', onDispose );
  9076. }
  9077. }
  9078. updateTexture( texture, options = {} ) {
  9079. const textureData = this.get( texture );
  9080. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  9081. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  9082. const backend = this.backend;
  9083. if ( isRenderTarget && textureData.initialized === true ) {
  9084. // it's an update
  9085. backend.destroySampler( texture );
  9086. backend.destroyTexture( texture );
  9087. }
  9088. //
  9089. if ( texture.isFramebufferTexture ) {
  9090. const renderTarget = this.renderer.getRenderTarget();
  9091. if ( renderTarget ) {
  9092. texture.type = renderTarget.texture.type;
  9093. } else {
  9094. texture.type = UnsignedByteType;
  9095. }
  9096. }
  9097. //
  9098. const { width, height, depth } = this.getSize( texture );
  9099. options.width = width;
  9100. options.height = height;
  9101. options.depth = depth;
  9102. options.needsMipmaps = this.needsMipmaps( texture );
  9103. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  9104. //
  9105. if ( isRenderTarget || texture.isStorageTexture === true ) {
  9106. backend.createSampler( texture );
  9107. backend.createTexture( texture, options );
  9108. textureData.generation = texture.version;
  9109. } else {
  9110. const needsCreate = textureData.initialized !== true;
  9111. if ( needsCreate ) backend.createSampler( texture );
  9112. if ( texture.version > 0 ) {
  9113. const image = texture.image;
  9114. if ( image === undefined ) {
  9115. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  9116. } else if ( image.complete === false ) {
  9117. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  9118. } else {
  9119. if ( texture.images ) {
  9120. const images = [];
  9121. for ( const image of texture.images ) {
  9122. images.push( image );
  9123. }
  9124. options.images = images;
  9125. } else {
  9126. options.image = image;
  9127. }
  9128. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  9129. backend.createTexture( texture, options );
  9130. textureData.isDefaultTexture = false;
  9131. textureData.generation = texture.version;
  9132. }
  9133. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  9134. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  9135. }
  9136. } else {
  9137. // async update
  9138. backend.createDefaultTexture( texture );
  9139. textureData.isDefaultTexture = true;
  9140. textureData.generation = texture.version;
  9141. }
  9142. }
  9143. // dispose handler
  9144. if ( textureData.initialized !== true ) {
  9145. textureData.initialized = true;
  9146. textureData.generation = texture.version;
  9147. //
  9148. this.info.memory.textures ++;
  9149. // dispose
  9150. const onDispose = () => {
  9151. texture.removeEventListener( 'dispose', onDispose );
  9152. this._destroyTexture( texture );
  9153. this.info.memory.textures --;
  9154. };
  9155. texture.addEventListener( 'dispose', onDispose );
  9156. }
  9157. //
  9158. textureData.version = texture.version;
  9159. }
  9160. getSize( texture, target = _size$3 ) {
  9161. let image = texture.images ? texture.images[ 0 ] : texture.image;
  9162. if ( image ) {
  9163. if ( image.image !== undefined ) image = image.image;
  9164. target.width = image.width || 1;
  9165. target.height = image.height || 1;
  9166. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  9167. } else {
  9168. target.width = target.height = target.depth = 1;
  9169. }
  9170. return target;
  9171. }
  9172. getMipLevels( texture, width, height ) {
  9173. let mipLevelCount;
  9174. if ( texture.isCompressedTexture ) {
  9175. if ( texture.mipmaps ) {
  9176. mipLevelCount = texture.mipmaps.length;
  9177. } else {
  9178. mipLevelCount = 1;
  9179. }
  9180. } else {
  9181. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  9182. }
  9183. return mipLevelCount;
  9184. }
  9185. needsMipmaps( texture ) {
  9186. return this.isEnvironmentTexture( texture ) || texture.isCompressedTexture === true || texture.generateMipmaps;
  9187. }
  9188. isEnvironmentTexture( texture ) {
  9189. const mapping = texture.mapping;
  9190. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  9191. }
  9192. _destroyTexture( texture ) {
  9193. this.backend.destroySampler( texture );
  9194. this.backend.destroyTexture( texture );
  9195. this.delete( texture );
  9196. }
  9197. }
  9198. class Color4 extends Color {
  9199. constructor( r, g, b, a = 1 ) {
  9200. super( r, g, b );
  9201. this.a = a;
  9202. }
  9203. set( r, g, b, a = 1 ) {
  9204. this.a = a;
  9205. return super.set( r, g, b );
  9206. }
  9207. copy( color ) {
  9208. if ( color.a !== undefined ) this.a = color.a;
  9209. return super.copy( color );
  9210. }
  9211. clone() {
  9212. return new this.constructor( this.r, this.g, this.b, this.a );
  9213. }
  9214. }
  9215. class ParameterNode extends PropertyNode {
  9216. static get type() {
  9217. return 'ParameterNode';
  9218. }
  9219. constructor( nodeType, name = null ) {
  9220. super( nodeType, name );
  9221. this.isParameterNode = true;
  9222. }
  9223. getHash() {
  9224. return this.uuid;
  9225. }
  9226. generate() {
  9227. return this.name;
  9228. }
  9229. }
  9230. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  9231. class StackNode extends Node {
  9232. static get type() {
  9233. return 'StackNode';
  9234. }
  9235. constructor( parent = null ) {
  9236. super();
  9237. this.nodes = [];
  9238. this.outputNode = null;
  9239. this.parent = parent;
  9240. this._currentCond = null;
  9241. this.isStackNode = true;
  9242. }
  9243. getNodeType( builder ) {
  9244. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  9245. }
  9246. add( node ) {
  9247. this.nodes.push( node );
  9248. return this;
  9249. }
  9250. If( boolNode, method ) {
  9251. const methodNode = new ShaderNode( method );
  9252. this._currentCond = select( boolNode, methodNode );
  9253. return this.add( this._currentCond );
  9254. }
  9255. ElseIf( boolNode, method ) {
  9256. const methodNode = new ShaderNode( method );
  9257. const ifNode = select( boolNode, methodNode );
  9258. this._currentCond.elseNode = ifNode;
  9259. this._currentCond = ifNode;
  9260. return this;
  9261. }
  9262. Else( method ) {
  9263. this._currentCond.elseNode = new ShaderNode( method );
  9264. return this;
  9265. }
  9266. build( builder, ...params ) {
  9267. const previousStack = getCurrentStack();
  9268. setCurrentStack( this );
  9269. for ( const node of this.nodes ) {
  9270. node.build( builder, 'void' );
  9271. }
  9272. setCurrentStack( previousStack );
  9273. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  9274. }
  9275. //
  9276. else( ...params ) { // @deprecated, r168
  9277. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  9278. return this.Else( ...params );
  9279. }
  9280. elseif( ...params ) { // @deprecated, r168
  9281. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  9282. return this.ElseIf( ...params );
  9283. }
  9284. }
  9285. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  9286. class StructTypeNode extends Node {
  9287. static get type() {
  9288. return 'StructTypeNode';
  9289. }
  9290. constructor( types ) {
  9291. super();
  9292. this.types = types;
  9293. this.isStructTypeNode = true;
  9294. }
  9295. getMemberTypes() {
  9296. return this.types;
  9297. }
  9298. }
  9299. class OutputStructNode extends Node {
  9300. static get type() {
  9301. return 'OutputStructNode';
  9302. }
  9303. constructor( ...members ) {
  9304. super();
  9305. this.members = members;
  9306. this.isOutputStructNode = true;
  9307. }
  9308. setup( builder ) {
  9309. super.setup( builder );
  9310. const members = this.members;
  9311. const types = [];
  9312. for ( let i = 0; i < members.length; i ++ ) {
  9313. types.push( members[ i ].getNodeType( builder ) );
  9314. }
  9315. this.nodeType = builder.getStructTypeFromNode( new StructTypeNode( types ) ).name;
  9316. }
  9317. generate( builder, output ) {
  9318. const propertyName = builder.getOutputStructName();
  9319. const members = this.members;
  9320. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  9321. for ( let i = 0; i < members.length; i ++ ) {
  9322. const snippet = members[ i ].build( builder, output );
  9323. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  9324. }
  9325. return propertyName;
  9326. }
  9327. }
  9328. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  9329. function getTextureIndex( textures, name ) {
  9330. for ( let i = 0; i < textures.length; i ++ ) {
  9331. if ( textures[ i ].name === name ) {
  9332. return i;
  9333. }
  9334. }
  9335. return - 1;
  9336. }
  9337. class MRTNode extends OutputStructNode {
  9338. static get type() {
  9339. return 'MRTNode';
  9340. }
  9341. constructor( outputNodes ) {
  9342. super();
  9343. this.outputNodes = outputNodes;
  9344. this.isMRTNode = true;
  9345. }
  9346. has( name ) {
  9347. return this.outputNodes[ name ] !== undefined;
  9348. }
  9349. get( name ) {
  9350. return this.outputNodes[ name ];
  9351. }
  9352. merge( mrtNode ) {
  9353. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  9354. return mrt( outputs );
  9355. }
  9356. setup( builder ) {
  9357. const outputNodes = this.outputNodes;
  9358. const mrt = builder.renderer.getRenderTarget();
  9359. const members = [];
  9360. const textures = mrt.textures;
  9361. for ( const name in outputNodes ) {
  9362. const index = getTextureIndex( textures, name );
  9363. members[ index ] = vec4( outputNodes[ name ] );
  9364. }
  9365. this.members = members;
  9366. return super.setup( builder );
  9367. }
  9368. }
  9369. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  9370. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  9371. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  9372. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  9373. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  9374. const result = word.shiftRight( 22 ).bitXor( word );
  9375. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  9376. } );
  9377. // remapping functions https://iquilezles.org/articles/functions/
  9378. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  9379. 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 ) );
  9380. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  9381. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  9382. // https://github.com/cabbibo/glsl-tri-noise-3d
  9383. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  9384. return x.fract().sub( .5 ).abs();
  9385. } ).setLayout( {
  9386. name: 'tri',
  9387. type: 'float',
  9388. inputs: [
  9389. { name: 'x', type: 'float' }
  9390. ]
  9391. } );
  9392. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  9393. 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. ) ) ) ) );
  9394. } ).setLayout( {
  9395. name: 'tri3',
  9396. type: 'vec3',
  9397. inputs: [
  9398. { name: 'p', type: 'vec3' }
  9399. ]
  9400. } );
  9401. const triNoise3D = /*@__PURE__*/ Fn( ( [ p_immutable, spd, time ] ) => {
  9402. const p = vec3( p_immutable ).toVar();
  9403. const z = float( 1.4 ).toVar();
  9404. const rz = float( 0.0 ).toVar();
  9405. const bp = vec3( p ).toVar();
  9406. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  9407. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  9408. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) );
  9409. bp.mulAssign( 1.8 );
  9410. z.mulAssign( 1.5 );
  9411. p.mulAssign( 1.2 );
  9412. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  9413. rz.addAssign( t.div( z ) );
  9414. bp.addAssign( 0.14 );
  9415. } );
  9416. return rz;
  9417. } ).setLayout( {
  9418. name: 'triNoise3D',
  9419. type: 'float',
  9420. inputs: [
  9421. { name: 'p', type: 'vec3' },
  9422. { name: 'spd', type: 'float' },
  9423. { name: 'time', type: 'float' }
  9424. ]
  9425. } );
  9426. class FunctionOverloadingNode extends Node {
  9427. static get type() {
  9428. return 'FunctionOverloadingNode';
  9429. }
  9430. constructor( functionNodes = [], ...parametersNodes ) {
  9431. super();
  9432. this.functionNodes = functionNodes;
  9433. this.parametersNodes = parametersNodes;
  9434. this._candidateFnCall = null;
  9435. this.global = true;
  9436. }
  9437. getNodeType() {
  9438. return this.functionNodes[ 0 ].shaderNode.layout.type;
  9439. }
  9440. setup( builder ) {
  9441. const params = this.parametersNodes;
  9442. let candidateFnCall = this._candidateFnCall;
  9443. if ( candidateFnCall === null ) {
  9444. let candidateFn = null;
  9445. let candidateScore = - 1;
  9446. for ( const functionNode of this.functionNodes ) {
  9447. const shaderNode = functionNode.shaderNode;
  9448. const layout = shaderNode.layout;
  9449. if ( layout === null ) {
  9450. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  9451. }
  9452. const inputs = layout.inputs;
  9453. if ( params.length === inputs.length ) {
  9454. let score = 0;
  9455. for ( let i = 0; i < params.length; i ++ ) {
  9456. const param = params[ i ];
  9457. const input = inputs[ i ];
  9458. if ( param.getNodeType( builder ) === input.type ) {
  9459. score ++;
  9460. } else {
  9461. score = 0;
  9462. }
  9463. }
  9464. if ( score > candidateScore ) {
  9465. candidateFn = functionNode;
  9466. candidateScore = score;
  9467. }
  9468. }
  9469. }
  9470. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  9471. }
  9472. return candidateFnCall;
  9473. }
  9474. }
  9475. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  9476. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  9477. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  9478. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  9479. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  9480. // Deprecated
  9481. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  9482. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  9483. return time.mul( timeScale );
  9484. };
  9485. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  9486. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  9487. return time.mul( timeScale );
  9488. };
  9489. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  9490. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  9491. return deltaTime.mul( timeScale );
  9492. };
  9493. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  9494. const oscSquare = ( t = time ) => t.fract().round();
  9495. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  9496. const oscSawtooth = ( t = time ) => t.fract();
  9497. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  9498. return rotate( uv.sub( center ), rotation ).add( center );
  9499. } );
  9500. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  9501. const delta = uv.sub( center );
  9502. const delta2 = delta.dot( delta );
  9503. const delta4 = delta2.mul( delta2 );
  9504. const deltaOffset = delta4.mul( strength );
  9505. return uv.add( delta.mul( deltaOffset ) );
  9506. } );
  9507. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  9508. let worldMatrix;
  9509. if ( position !== null ) {
  9510. worldMatrix = modelWorldMatrix.toVar();
  9511. worldMatrix[ 3 ][ 0 ] = position.x;
  9512. worldMatrix[ 3 ][ 1 ] = position.y;
  9513. worldMatrix[ 3 ][ 2 ] = position.z;
  9514. } else {
  9515. worldMatrix = modelWorldMatrix;
  9516. }
  9517. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  9518. if ( defined( horizontal ) ) {
  9519. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  9520. modelViewMatrix[ 0 ][ 1 ] = 0;
  9521. modelViewMatrix[ 0 ][ 2 ] = 0;
  9522. }
  9523. if ( defined( vertical ) ) {
  9524. modelViewMatrix[ 1 ][ 0 ] = 0;
  9525. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  9526. modelViewMatrix[ 1 ][ 2 ] = 0;
  9527. }
  9528. modelViewMatrix[ 2 ][ 0 ] = 0;
  9529. modelViewMatrix[ 2 ][ 1 ] = 0;
  9530. modelViewMatrix[ 2 ][ 2 ] = 1;
  9531. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  9532. } );
  9533. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  9534. const depth = linearDepth();
  9535. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  9536. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  9537. return finalUV;
  9538. } );
  9539. class SpriteSheetUVNode extends Node {
  9540. static get type() {
  9541. return 'SpriteSheetUVNode';
  9542. }
  9543. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  9544. super( 'vec2' );
  9545. this.countNode = countNode;
  9546. this.uvNode = uvNode;
  9547. this.frameNode = frameNode;
  9548. }
  9549. setup() {
  9550. const { frameNode, uvNode, countNode } = this;
  9551. const { width, height } = countNode;
  9552. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  9553. const column = frameNum.mod( width );
  9554. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  9555. const scale = countNode.reciprocal();
  9556. const uvFrameOffset = vec2( column, row );
  9557. return uvNode.add( uvFrameOffset ).mul( scale );
  9558. }
  9559. }
  9560. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  9561. class TriplanarTexturesNode extends Node {
  9562. static get type() {
  9563. return 'TriplanarTexturesNode';
  9564. }
  9565. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  9566. super( 'vec4' );
  9567. this.textureXNode = textureXNode;
  9568. this.textureYNode = textureYNode;
  9569. this.textureZNode = textureZNode;
  9570. this.scaleNode = scaleNode;
  9571. this.positionNode = positionNode;
  9572. this.normalNode = normalNode;
  9573. }
  9574. setup() {
  9575. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  9576. // Ref: https://github.com/keijiro/StandardTriplanar
  9577. // Blending factor of triplanar mapping
  9578. let bf = normalNode.abs().normalize();
  9579. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  9580. // Triplanar mapping
  9581. const tx = positionNode.yz.mul( scaleNode );
  9582. const ty = positionNode.zx.mul( scaleNode );
  9583. const tz = positionNode.xy.mul( scaleNode );
  9584. // Base color
  9585. const textureX = textureXNode.value;
  9586. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  9587. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  9588. const cx = texture( textureX, tx ).mul( bf.x );
  9589. const cy = texture( textureY, ty ).mul( bf.y );
  9590. const cz = texture( textureZ, tz ).mul( bf.z );
  9591. return add( cx, cy, cz );
  9592. }
  9593. }
  9594. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  9595. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  9596. const _reflectorPlane = new Plane();
  9597. const _normal = new Vector3();
  9598. const _reflectorWorldPosition = new Vector3();
  9599. const _cameraWorldPosition = new Vector3();
  9600. const _rotationMatrix = new Matrix4();
  9601. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  9602. const clipPlane = new Vector4();
  9603. const _view = new Vector3();
  9604. const _target = new Vector3();
  9605. const _q = new Vector4();
  9606. const _size$2 = new Vector2();
  9607. const _defaultRT = new RenderTarget();
  9608. const _defaultUV = screenUV.flipX();
  9609. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  9610. let _inReflector = false;
  9611. class ReflectorNode extends TextureNode {
  9612. static get type() {
  9613. return 'ReflectorNode';
  9614. }
  9615. constructor( parameters = {} ) {
  9616. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  9617. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  9618. this._depthNode = null;
  9619. this.setUpdateMatrix( false );
  9620. }
  9621. get reflector() {
  9622. return this._reflectorBaseNode;
  9623. }
  9624. get target() {
  9625. return this._reflectorBaseNode.target;
  9626. }
  9627. getDepthNode() {
  9628. if ( this._depthNode === null ) {
  9629. if ( this._reflectorBaseNode.depth !== true ) {
  9630. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  9631. }
  9632. this._depthNode = nodeObject( new ReflectorNode( {
  9633. defaultTexture: _defaultRT.depthTexture,
  9634. reflector: this._reflectorBaseNode
  9635. } ) );
  9636. }
  9637. return this._depthNode;
  9638. }
  9639. setup( builder ) {
  9640. // ignore if used in post-processing
  9641. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  9642. return super.setup( builder );
  9643. }
  9644. clone() {
  9645. const texture = new this.constructor( this.reflectorNode );
  9646. texture._reflectorBaseNode = this._reflectorBaseNode;
  9647. return texture;
  9648. }
  9649. }
  9650. class ReflectorBaseNode extends Node {
  9651. static get type() {
  9652. return 'ReflectorBaseNode';
  9653. }
  9654. constructor( textureNode, parameters = {} ) {
  9655. super();
  9656. const {
  9657. target = new Object3D(),
  9658. resolution = 1,
  9659. generateMipmaps = false,
  9660. bounces = true,
  9661. depth = false
  9662. } = parameters;
  9663. //
  9664. this.textureNode = textureNode;
  9665. this.target = target;
  9666. this.resolution = resolution;
  9667. this.generateMipmaps = generateMipmaps;
  9668. this.bounces = bounces;
  9669. this.depth = depth;
  9670. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  9671. this.virtualCameras = new WeakMap();
  9672. this.renderTargets = new WeakMap();
  9673. }
  9674. _updateResolution( renderTarget, renderer ) {
  9675. const resolution = this.resolution;
  9676. renderer.getDrawingBufferSize( _size$2 );
  9677. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  9678. }
  9679. setup( builder ) {
  9680. this._updateResolution( _defaultRT, builder.renderer );
  9681. return super.setup( builder );
  9682. }
  9683. getVirtualCamera( camera ) {
  9684. let virtualCamera = this.virtualCameras.get( camera );
  9685. if ( virtualCamera === undefined ) {
  9686. virtualCamera = camera.clone();
  9687. this.virtualCameras.set( camera, virtualCamera );
  9688. }
  9689. return virtualCamera;
  9690. }
  9691. getRenderTarget( camera ) {
  9692. let renderTarget = this.renderTargets.get( camera );
  9693. if ( renderTarget === undefined ) {
  9694. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  9695. if ( this.generateMipmaps === true ) {
  9696. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  9697. renderTarget.texture.generateMipmaps = true;
  9698. }
  9699. if ( this.depth === true ) {
  9700. renderTarget.depthTexture = new DepthTexture();
  9701. }
  9702. this.renderTargets.set( camera, renderTarget );
  9703. }
  9704. return renderTarget;
  9705. }
  9706. updateBefore( frame ) {
  9707. if ( this.bounces === false && _inReflector ) return;
  9708. _inReflector = true;
  9709. const { scene, camera, renderer, material } = frame;
  9710. const { target } = this;
  9711. const virtualCamera = this.getVirtualCamera( camera );
  9712. const renderTarget = this.getRenderTarget( virtualCamera );
  9713. renderer.getDrawingBufferSize( _size$2 );
  9714. this._updateResolution( renderTarget, renderer );
  9715. //
  9716. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  9717. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  9718. _rotationMatrix.extractRotation( target.matrixWorld );
  9719. _normal.set( 0, 0, 1 );
  9720. _normal.applyMatrix4( _rotationMatrix );
  9721. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  9722. // Avoid rendering when reflector is facing away
  9723. if ( _view.dot( _normal ) > 0 ) return;
  9724. _view.reflect( _normal ).negate();
  9725. _view.add( _reflectorWorldPosition );
  9726. _rotationMatrix.extractRotation( camera.matrixWorld );
  9727. _lookAtPosition.set( 0, 0, - 1 );
  9728. _lookAtPosition.applyMatrix4( _rotationMatrix );
  9729. _lookAtPosition.add( _cameraWorldPosition );
  9730. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  9731. _target.reflect( _normal ).negate();
  9732. _target.add( _reflectorWorldPosition );
  9733. //
  9734. virtualCamera.coordinateSystem = camera.coordinateSystem;
  9735. virtualCamera.position.copy( _view );
  9736. virtualCamera.up.set( 0, 1, 0 );
  9737. virtualCamera.up.applyMatrix4( _rotationMatrix );
  9738. virtualCamera.up.reflect( _normal );
  9739. virtualCamera.lookAt( _target );
  9740. virtualCamera.near = camera.near;
  9741. virtualCamera.far = camera.far;
  9742. virtualCamera.updateMatrixWorld();
  9743. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  9744. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  9745. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  9746. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  9747. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  9748. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  9749. const projectionMatrix = virtualCamera.projectionMatrix;
  9750. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  9751. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  9752. _q.z = - 1.0;
  9753. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  9754. // Calculate the scaled plane vector
  9755. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  9756. const clipBias = 0;
  9757. // Replacing the third row of the projection matrix
  9758. projectionMatrix.elements[ 2 ] = clipPlane.x;
  9759. projectionMatrix.elements[ 6 ] = clipPlane.y;
  9760. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  9761. projectionMatrix.elements[ 14 ] = clipPlane.w;
  9762. //
  9763. this.textureNode.value = renderTarget.texture;
  9764. if ( this.depth === true ) {
  9765. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  9766. }
  9767. material.visible = false;
  9768. const currentRenderTarget = renderer.getRenderTarget();
  9769. const currentMRT = renderer.getMRT();
  9770. renderer.setMRT( null );
  9771. renderer.setRenderTarget( renderTarget );
  9772. renderer.render( scene, virtualCamera );
  9773. renderer.setMRT( currentMRT );
  9774. renderer.setRenderTarget( currentRenderTarget );
  9775. material.visible = true;
  9776. _inReflector = false;
  9777. }
  9778. }
  9779. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  9780. // Helper for passes that need to fill the viewport with a single quad.
  9781. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  9782. // https://github.com/mrdoob/three.js/pull/21358
  9783. class QuadGeometry extends BufferGeometry {
  9784. constructor( flipY = false ) {
  9785. super();
  9786. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  9787. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  9788. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  9789. }
  9790. }
  9791. const _geometry = /*@__PURE__*/ new QuadGeometry();
  9792. class QuadMesh extends Mesh {
  9793. constructor( material = null ) {
  9794. super( _geometry, material );
  9795. this.camera = _camera;
  9796. this.isQuadMesh = true;
  9797. }
  9798. renderAsync( renderer ) {
  9799. return renderer.renderAsync( this, _camera );
  9800. }
  9801. render( renderer ) {
  9802. renderer.render( this, _camera );
  9803. }
  9804. }
  9805. const _size$1 = /*@__PURE__*/ new Vector2();
  9806. class RTTNode extends TextureNode {
  9807. static get type() {
  9808. return 'RTTNode';
  9809. }
  9810. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  9811. const renderTarget = new RenderTarget( width, height, options );
  9812. super( renderTarget.texture, uv() );
  9813. this.node = node;
  9814. this.width = width;
  9815. this.height = height;
  9816. this.renderTarget = renderTarget;
  9817. this.textureNeedsUpdate = true;
  9818. this.autoUpdate = true;
  9819. this.updateMap = new WeakMap();
  9820. this._rttNode = null;
  9821. this._quadMesh = new QuadMesh( new NodeMaterial() );
  9822. this.updateBeforeType = NodeUpdateType.RENDER;
  9823. }
  9824. get autoSize() {
  9825. return this.width === null;
  9826. }
  9827. setup( builder ) {
  9828. this._rttNode = this.node.context( builder.getSharedContext() );
  9829. this._quadMesh.material.name = 'RTT';
  9830. this._quadMesh.material.needsUpdate = true;
  9831. return super.setup( builder );
  9832. }
  9833. setSize( width, height ) {
  9834. this.width = width;
  9835. this.height = height;
  9836. const effectiveWidth = width * this.pixelRatio;
  9837. const effectiveHeight = height * this.pixelRatio;
  9838. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  9839. this.textureNeedsUpdate = true;
  9840. }
  9841. setPixelRatio( pixelRatio ) {
  9842. this.pixelRatio = pixelRatio;
  9843. this.setSize( this.width, this.height );
  9844. }
  9845. updateBefore( { renderer } ) {
  9846. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  9847. this.textureNeedsUpdate = false;
  9848. //
  9849. if ( this.autoSize === true ) {
  9850. this.pixelRatio = renderer.getPixelRatio();
  9851. const size = renderer.getSize( _size$1 );
  9852. this.setSize( size.width, size.height );
  9853. }
  9854. //
  9855. this._quadMesh.material.fragmentNode = this._rttNode;
  9856. //
  9857. const currentRenderTarget = renderer.getRenderTarget();
  9858. renderer.setRenderTarget( this.renderTarget );
  9859. this._quadMesh.render( renderer );
  9860. renderer.setRenderTarget( currentRenderTarget );
  9861. }
  9862. clone() {
  9863. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  9864. newNode.sampler = this.sampler;
  9865. newNode.referenceNode = this;
  9866. return newNode;
  9867. }
  9868. }
  9869. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  9870. const convertToTexture = ( node, ...params ) => {
  9871. if ( node.isTextureNode ) return node;
  9872. if ( node.isPassNode ) return node.getTextureNode();
  9873. return rtt( node, ...params );
  9874. };
  9875. /**
  9876. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  9877. * depth value and the camera's inverse projection matrix.
  9878. *
  9879. * @param {vec2} screenPosition - The fragment's screen position expressed as uv coordinates.
  9880. * @param {float} depth - The fragment's depth value.
  9881. * @param {mat4} projectionMatrixInverse - The camera's inverse projection matrix.
  9882. * @return {vec3} The fragments position in view space.
  9883. */
  9884. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  9885. let clipSpacePosition;
  9886. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  9887. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  9888. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  9889. } else {
  9890. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  9891. }
  9892. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  9893. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  9894. } );
  9895. /**
  9896. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  9897. * and the camera's projection matrix
  9898. *
  9899. * @param {vec3} viewPosition - The fragments position in view space.
  9900. * @param {mat4} projectionMatrix - The camera's projection matrix.
  9901. * @return {vec2} The fragment's screen position expressed as uv coordinates.
  9902. */
  9903. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  9904. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  9905. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  9906. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  9907. } );
  9908. /**
  9909. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  9910. * target is available or if flat surface normals are required.
  9911. *
  9912. * @param {vec2} uv - The texture coordinate.
  9913. * @param {DepthTexture} depthTexture - The depth texture.
  9914. * @param {mat4} projectionMatrixInverse - The camera's inverse projection matrix.
  9915. * @return {vec3} The computed normal vector.
  9916. */
  9917. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  9918. const size = textureSize( textureLoad( depthTexture ) );
  9919. const p = ivec2( uv.mul( size ) ).toVar();
  9920. const c0 = textureLoad( depthTexture, p ).toVar();
  9921. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  9922. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  9923. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  9924. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  9925. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  9926. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  9927. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  9928. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  9929. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  9930. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  9931. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  9932. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  9933. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  9934. 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 ) ) );
  9935. 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 ) ) );
  9936. return normalize( cross( dpdx, dpdy ) );
  9937. } );
  9938. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  9939. constructor( array, itemSize, typeClass = Float32Array ) {
  9940. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  9941. super( array, itemSize );
  9942. this.isStorageInstancedBufferAttribute = true;
  9943. }
  9944. }
  9945. class StorageBufferAttribute extends BufferAttribute {
  9946. constructor( array, itemSize, typeClass = Float32Array ) {
  9947. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  9948. super( array, itemSize );
  9949. this.isStorageBufferAttribute = true;
  9950. }
  9951. }
  9952. class StorageArrayElementNode extends ArrayElementNode {
  9953. static get type() {
  9954. return 'StorageArrayElementNode';
  9955. }
  9956. constructor( storageBufferNode, indexNode ) {
  9957. super( storageBufferNode, indexNode );
  9958. this.isStorageArrayElementNode = true;
  9959. }
  9960. set storageBufferNode( value ) {
  9961. this.node = value;
  9962. }
  9963. get storageBufferNode() {
  9964. return this.node;
  9965. }
  9966. setup( builder ) {
  9967. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  9968. if ( this.node.isPBO === true ) {
  9969. builder.setupPBO( this.node );
  9970. }
  9971. }
  9972. return super.setup( builder );
  9973. }
  9974. generate( builder, output ) {
  9975. let snippet;
  9976. const isAssignContext = builder.context.assign;
  9977. //
  9978. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  9979. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  9980. snippet = builder.generatePBO( this );
  9981. } else {
  9982. snippet = this.node.build( builder );
  9983. }
  9984. } else {
  9985. snippet = super.generate( builder );
  9986. }
  9987. if ( isAssignContext !== true ) {
  9988. const type = this.getNodeType( builder );
  9989. snippet = builder.format( snippet, type, output );
  9990. }
  9991. return snippet;
  9992. }
  9993. }
  9994. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  9995. class StorageBufferNode extends BufferNode {
  9996. static get type() {
  9997. return 'StorageBufferNode';
  9998. }
  9999. constructor( value, bufferType = null, bufferCount = 0 ) {
  10000. if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  10001. bufferType = getTypeFromLength( value.itemSize );
  10002. bufferCount = value.count;
  10003. }
  10004. super( value, bufferType, bufferCount );
  10005. this.isStorageBufferNode = true;
  10006. this.access = NodeAccess.READ_WRITE;
  10007. this.isAtomic = false;
  10008. this.isPBO = false;
  10009. this.bufferCount = bufferCount;
  10010. this._attribute = null;
  10011. this._varying = null;
  10012. this.global = true;
  10013. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  10014. // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  10015. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  10016. else value.isStorageBufferAttribute = true;
  10017. }
  10018. }
  10019. getHash( builder ) {
  10020. if ( this.bufferCount === 0 ) {
  10021. let bufferData = builder.globalCache.getData( this.value );
  10022. if ( bufferData === undefined ) {
  10023. bufferData = {
  10024. node: this
  10025. };
  10026. builder.globalCache.setData( this.value, bufferData );
  10027. }
  10028. return bufferData.node.uuid;
  10029. }
  10030. return this.uuid;
  10031. }
  10032. getInputType( /*builder*/ ) {
  10033. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  10034. }
  10035. element( indexNode ) {
  10036. return storageElement( this, indexNode );
  10037. }
  10038. setPBO( value ) {
  10039. this.isPBO = value;
  10040. return this;
  10041. }
  10042. getPBO() {
  10043. return this.isPBO;
  10044. }
  10045. setAccess( value ) {
  10046. this.access = value;
  10047. return this;
  10048. }
  10049. toReadOnly() {
  10050. return this.setAccess( NodeAccess.READ_ONLY );
  10051. }
  10052. setAtomic( value ) {
  10053. this.isAtomic = value;
  10054. return this;
  10055. }
  10056. toAtomic() {
  10057. return this.setAtomic( true );
  10058. }
  10059. getAttributeData() {
  10060. if ( this._attribute === null ) {
  10061. this._attribute = bufferAttribute( this.value );
  10062. this._varying = varying( this._attribute );
  10063. }
  10064. return {
  10065. attribute: this._attribute,
  10066. varying: this._varying
  10067. };
  10068. }
  10069. getNodeType( builder ) {
  10070. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  10071. return super.getNodeType( builder );
  10072. }
  10073. const { attribute } = this.getAttributeData();
  10074. return attribute.getNodeType( builder );
  10075. }
  10076. generate( builder ) {
  10077. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  10078. return super.generate( builder );
  10079. }
  10080. const { attribute, varying } = this.getAttributeData();
  10081. const output = varying.build( builder );
  10082. builder.registerTransform( output, attribute );
  10083. return output;
  10084. }
  10085. }
  10086. const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) );
  10087. const storageObject = ( value, type, count ) => { // @deprecated, r171
  10088. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  10089. return storage( value, type, count ).setPBO( true );
  10090. };
  10091. const attributeArray = ( count, type = 'float' ) => {
  10092. const itemSize = getLengthFromType( type );
  10093. const buffer = new StorageBufferAttribute( count, itemSize );
  10094. const node = storage( buffer, type, count );
  10095. return node;
  10096. };
  10097. const instancedArray = ( count, type = 'float' ) => {
  10098. const itemSize = getLengthFromType( type );
  10099. const buffer = new StorageInstancedBufferAttribute( count, itemSize );
  10100. const node = storage( buffer, type, count );
  10101. return node;
  10102. };
  10103. class VertexColorNode extends AttributeNode {
  10104. static get type() {
  10105. return 'VertexColorNode';
  10106. }
  10107. constructor( index = 0 ) {
  10108. super( null, 'vec4' );
  10109. this.isVertexColorNode = true;
  10110. this.index = index;
  10111. }
  10112. getAttributeName( /*builder*/ ) {
  10113. const index = this.index;
  10114. return 'color' + ( index > 0 ? index : '' );
  10115. }
  10116. generate( builder ) {
  10117. const attributeName = this.getAttributeName( builder );
  10118. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  10119. let result;
  10120. if ( geometryAttribute === true ) {
  10121. result = super.generate( builder );
  10122. } else {
  10123. // Vertex color fallback should be white
  10124. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  10125. }
  10126. return result;
  10127. }
  10128. serialize( data ) {
  10129. super.serialize( data );
  10130. data.index = this.index;
  10131. }
  10132. deserialize( data ) {
  10133. super.deserialize( data );
  10134. this.index = data.index;
  10135. }
  10136. }
  10137. const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) );
  10138. class PointUVNode extends Node {
  10139. static get type() {
  10140. return 'PointUVNode';
  10141. }
  10142. constructor() {
  10143. super( 'vec2' );
  10144. this.isPointUVNode = true;
  10145. }
  10146. generate( /*builder*/ ) {
  10147. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  10148. }
  10149. }
  10150. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  10151. const _e1 = /*@__PURE__*/ new Euler();
  10152. const _m1 = /*@__PURE__*/ new Matrix4();
  10153. class SceneNode extends Node {
  10154. static get type() {
  10155. return 'SceneNode';
  10156. }
  10157. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  10158. super();
  10159. this.scope = scope;
  10160. this.scene = scene;
  10161. }
  10162. setup( builder ) {
  10163. const scope = this.scope;
  10164. const scene = this.scene !== null ? this.scene : builder.scene;
  10165. let output;
  10166. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  10167. output = reference( 'backgroundBlurriness', 'float', scene );
  10168. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  10169. output = reference( 'backgroundIntensity', 'float', scene );
  10170. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  10171. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  10172. const background = scene.background;
  10173. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  10174. _e1.copy( scene.backgroundRotation );
  10175. // accommodate left-handed frame
  10176. _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1;
  10177. _m1.makeRotationFromEuler( _e1 );
  10178. } else {
  10179. _m1.identity();
  10180. }
  10181. return _m1;
  10182. } );
  10183. } else {
  10184. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  10185. }
  10186. return output;
  10187. }
  10188. }
  10189. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  10190. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  10191. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  10192. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  10193. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  10194. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  10195. class StorageTextureNode extends TextureNode {
  10196. static get type() {
  10197. return 'StorageTextureNode';
  10198. }
  10199. constructor( value, uvNode, storeNode = null ) {
  10200. super( value, uvNode );
  10201. this.storeNode = storeNode;
  10202. this.isStorageTextureNode = true;
  10203. this.access = NodeAccess.WRITE_ONLY;
  10204. }
  10205. getInputType( /*builder*/ ) {
  10206. return 'storageTexture';
  10207. }
  10208. setup( builder ) {
  10209. super.setup( builder );
  10210. const properties = builder.getNodeProperties( this );
  10211. properties.storeNode = this.storeNode;
  10212. }
  10213. setAccess( value ) {
  10214. this.access = value;
  10215. return this;
  10216. }
  10217. generate( builder, output ) {
  10218. let snippet;
  10219. if ( this.storeNode !== null ) {
  10220. snippet = this.generateStore( builder );
  10221. } else {
  10222. snippet = super.generate( builder, output );
  10223. }
  10224. return snippet;
  10225. }
  10226. toReadWrite() {
  10227. return this.setAccess( NodeAccess.READ_WRITE );
  10228. }
  10229. toReadOnly() {
  10230. return this.setAccess( NodeAccess.READ_ONLY );
  10231. }
  10232. toWriteOnly() {
  10233. return this.setAccess( NodeAccess.WRITE_ONLY );
  10234. }
  10235. generateStore( builder ) {
  10236. const properties = builder.getNodeProperties( this );
  10237. const { uvNode, storeNode } = properties;
  10238. const textureProperty = super.generate( builder, 'property' );
  10239. const uvSnippet = uvNode.build( builder, 'uvec2' );
  10240. const storeSnippet = storeNode.build( builder, 'vec4' );
  10241. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  10242. builder.addLineFlowCode( snippet, this );
  10243. }
  10244. }
  10245. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  10246. const textureStore = ( value, uvNode, storeNode ) => {
  10247. const node = storageTexture( value, uvNode, storeNode );
  10248. if ( storeNode !== null ) node.append();
  10249. return node;
  10250. };
  10251. class UserDataNode extends ReferenceNode {
  10252. static get type() {
  10253. return 'UserDataNode';
  10254. }
  10255. constructor( property, inputType, userData = null ) {
  10256. super( property, inputType, userData );
  10257. this.userData = userData;
  10258. }
  10259. updateReference( state ) {
  10260. this.reference = this.userData !== null ? this.userData : state.object.userData;
  10261. return this.reference;
  10262. }
  10263. }
  10264. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  10265. const _objectData = new WeakMap();
  10266. class VelocityNode extends TempNode {
  10267. static get type() {
  10268. return 'VelocityNode';
  10269. }
  10270. constructor() {
  10271. super( 'vec2' );
  10272. this.projectionMatrix = null;
  10273. this.updateType = NodeUpdateType.OBJECT;
  10274. this.updateAfterType = NodeUpdateType.OBJECT;
  10275. this.previousModelWorldMatrix = uniform( new Matrix4() );
  10276. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  10277. this.previousCameraViewMatrix = uniform( new Matrix4() );
  10278. }
  10279. setProjectionMatrix( projectionMatrix ) {
  10280. this.projectionMatrix = projectionMatrix;
  10281. }
  10282. update( { frameId, camera, object } ) {
  10283. const previousModelMatrix = getPreviousMatrix( object );
  10284. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  10285. //
  10286. const cameraData = getData( camera );
  10287. if ( cameraData.frameId !== frameId ) {
  10288. cameraData.frameId = frameId;
  10289. if ( cameraData.previousProjectionMatrix === undefined ) {
  10290. cameraData.previousProjectionMatrix = new Matrix4();
  10291. cameraData.previousCameraViewMatrix = new Matrix4();
  10292. cameraData.currentProjectionMatrix = new Matrix4();
  10293. cameraData.currentCameraViewMatrix = new Matrix4();
  10294. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  10295. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  10296. } else {
  10297. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  10298. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  10299. }
  10300. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  10301. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  10302. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  10303. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  10304. }
  10305. }
  10306. updateAfter( { object } ) {
  10307. getPreviousMatrix( object ).copy( object.matrixWorld );
  10308. }
  10309. setup( /*builder*/ ) {
  10310. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  10311. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  10312. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  10313. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  10314. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  10315. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  10316. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  10317. return velocity;
  10318. }
  10319. }
  10320. function getData( object ) {
  10321. let objectData = _objectData.get( object );
  10322. if ( objectData === undefined ) {
  10323. objectData = {};
  10324. _objectData.set( object, objectData );
  10325. }
  10326. return objectData;
  10327. }
  10328. function getPreviousMatrix( object, index = 0 ) {
  10329. const objectData = getData( object );
  10330. let matrix = objectData[ index ];
  10331. if ( matrix === undefined ) {
  10332. objectData[ index ] = matrix = new Matrix4();
  10333. }
  10334. return matrix;
  10335. }
  10336. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  10337. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  10338. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  10339. } ).setLayout( {
  10340. name: 'blendBurn',
  10341. type: 'vec3',
  10342. inputs: [
  10343. { name: 'base', type: 'vec3' },
  10344. { name: 'blend', type: 'vec3' }
  10345. ]
  10346. } );
  10347. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  10348. return min$1( base.div( blend.oneMinus() ), 1.0 );
  10349. } ).setLayout( {
  10350. name: 'blendDodge',
  10351. type: 'vec3',
  10352. inputs: [
  10353. { name: 'base', type: 'vec3' },
  10354. { name: 'blend', type: 'vec3' }
  10355. ]
  10356. } );
  10357. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  10358. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  10359. } ).setLayout( {
  10360. name: 'blendScreen',
  10361. type: 'vec3',
  10362. inputs: [
  10363. { name: 'base', type: 'vec3' },
  10364. { name: 'blend', type: 'vec3' }
  10365. ]
  10366. } );
  10367. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  10368. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  10369. } ).setLayout( {
  10370. name: 'blendOverlay',
  10371. type: 'vec3',
  10372. inputs: [
  10373. { name: 'base', type: 'vec3' },
  10374. { name: 'blend', type: 'vec3' }
  10375. ]
  10376. } );
  10377. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  10378. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  10379. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  10380. } ).setLayout( {
  10381. name: 'blendColor',
  10382. type: 'vec4',
  10383. inputs: [
  10384. { name: 'base', type: 'vec4' },
  10385. { name: 'blend', type: 'vec4' }
  10386. ]
  10387. } );
  10388. // deprecated
  10389. const burn = ( ...params ) => { // @deprecated, r171
  10390. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  10391. return blendBurn( params );
  10392. };
  10393. const dodge = ( ...params ) => { // @deprecated, r171
  10394. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  10395. return blendDodge( params );
  10396. };
  10397. const screen = ( ...params ) => { // @deprecated, r171
  10398. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  10399. return blendScreen( params );
  10400. };
  10401. const overlay = ( ...params ) => { // @deprecated, r171
  10402. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  10403. return blendOverlay( params );
  10404. };
  10405. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  10406. return luminance( color.rgb );
  10407. } );
  10408. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  10409. return adjustment.mix( luminance( color.rgb ), color.rgb );
  10410. } );
  10411. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  10412. const average = add( color.r, color.g, color.b ).div( 3.0 );
  10413. const mx = color.r.max( color.g.max( color.b ) );
  10414. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  10415. return mix( color.rgb, mx, amt );
  10416. } );
  10417. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  10418. const k = vec3( 0.57735, 0.57735, 0.57735 );
  10419. const cosAngle = adjustment.cos();
  10420. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  10421. } );
  10422. const luminance = (
  10423. color,
  10424. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  10425. ) => dot( color, luminanceCoefficients );
  10426. const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) );
  10427. /**
  10428. * Color Decision List (CDL) v1.2
  10429. *
  10430. * Compact representation of color grading information, defined by slope, offset, power, and
  10431. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  10432. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  10433. *
  10434. * @param {vec4} color Input (-Infinity < input < +Infinity)
  10435. * @param {number | vec3} slope Slope (0 ≤ slope < +Infinity)
  10436. * @param {number | vec3} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  10437. * @param {number | vec3} power Power (0 < power < +Infinity)
  10438. * @param {number} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  10439. * @param {vec3} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  10440. * @return Output, -Infinity < output < +Infinity
  10441. *
  10442. * References:
  10443. * - ASC CDL v1.2
  10444. * - https://blender.stackexchange.com/a/55239/43930
  10445. * - https://docs.acescentral.com/specifications/acescc/
  10446. */
  10447. const cdl = /*@__PURE__*/ Fn( ( [
  10448. color,
  10449. slope = vec3( 1 ),
  10450. offset = vec3( 0 ),
  10451. power = vec3( 1 ),
  10452. saturation = float( 1 ),
  10453. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  10454. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  10455. ] ) => {
  10456. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  10457. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  10458. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  10459. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  10460. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  10461. const pv = v.pow( power ).toVar();
  10462. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  10463. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  10464. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  10465. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  10466. return vec4( v.rgb, color.a );
  10467. } );
  10468. class PosterizeNode extends TempNode {
  10469. static get type() {
  10470. return 'PosterizeNode';
  10471. }
  10472. constructor( sourceNode, stepsNode ) {
  10473. super();
  10474. this.sourceNode = sourceNode;
  10475. this.stepsNode = stepsNode;
  10476. }
  10477. setup() {
  10478. const { sourceNode, stepsNode } = this;
  10479. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  10480. }
  10481. }
  10482. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  10483. const _size = /*@__PURE__*/ new Vector2();
  10484. class PassTextureNode extends TextureNode {
  10485. static get type() {
  10486. return 'PassTextureNode';
  10487. }
  10488. constructor( passNode, texture ) {
  10489. super( texture );
  10490. this.passNode = passNode;
  10491. this.setUpdateMatrix( false );
  10492. }
  10493. setup( builder ) {
  10494. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  10495. return super.setup( builder );
  10496. }
  10497. clone() {
  10498. return new this.constructor( this.passNode, this.value );
  10499. }
  10500. }
  10501. class PassMultipleTextureNode extends PassTextureNode {
  10502. static get type() {
  10503. return 'PassMultipleTextureNode';
  10504. }
  10505. constructor( passNode, textureName, previousTexture = false ) {
  10506. super( passNode, null );
  10507. this.textureName = textureName;
  10508. this.previousTexture = previousTexture;
  10509. }
  10510. updateTexture() {
  10511. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  10512. }
  10513. setup( builder ) {
  10514. this.updateTexture();
  10515. return super.setup( builder );
  10516. }
  10517. clone() {
  10518. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  10519. }
  10520. }
  10521. class PassNode extends TempNode {
  10522. static get type() {
  10523. return 'PassNode';
  10524. }
  10525. constructor( scope, scene, camera, options = {} ) {
  10526. super( 'vec4' );
  10527. this.scope = scope;
  10528. this.scene = scene;
  10529. this.camera = camera;
  10530. this.options = options;
  10531. this._pixelRatio = 1;
  10532. this._width = 1;
  10533. this._height = 1;
  10534. const depthTexture = new DepthTexture();
  10535. depthTexture.isRenderTargetTexture = true;
  10536. //depthTexture.type = FloatType;
  10537. depthTexture.name = 'depth';
  10538. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  10539. renderTarget.texture.name = 'output';
  10540. renderTarget.depthTexture = depthTexture;
  10541. this.renderTarget = renderTarget;
  10542. this.updateBeforeType = NodeUpdateType.FRAME;
  10543. this._textures = {
  10544. output: renderTarget.texture,
  10545. depth: depthTexture
  10546. };
  10547. this._textureNodes = {};
  10548. this._linearDepthNodes = {};
  10549. this._viewZNodes = {};
  10550. this._previousTextures = {};
  10551. this._previousTextureNodes = {};
  10552. this._cameraNear = uniform( 0 );
  10553. this._cameraFar = uniform( 0 );
  10554. this._mrt = null;
  10555. this.isPassNode = true;
  10556. }
  10557. setMRT( mrt ) {
  10558. this._mrt = mrt;
  10559. return this;
  10560. }
  10561. getMRT() {
  10562. return this._mrt;
  10563. }
  10564. isGlobal() {
  10565. return true;
  10566. }
  10567. getTexture( name ) {
  10568. let texture = this._textures[ name ];
  10569. if ( texture === undefined ) {
  10570. const refTexture = this.renderTarget.texture;
  10571. texture = refTexture.clone();
  10572. texture.isRenderTargetTexture = true;
  10573. texture.name = name;
  10574. this._textures[ name ] = texture;
  10575. this.renderTarget.textures.push( texture );
  10576. }
  10577. return texture;
  10578. }
  10579. getPreviousTexture( name ) {
  10580. let texture = this._previousTextures[ name ];
  10581. if ( texture === undefined ) {
  10582. texture = this.getTexture( name ).clone();
  10583. texture.isRenderTargetTexture = true;
  10584. this._previousTextures[ name ] = texture;
  10585. }
  10586. return texture;
  10587. }
  10588. toggleTexture( name ) {
  10589. const prevTexture = this._previousTextures[ name ];
  10590. if ( prevTexture !== undefined ) {
  10591. const texture = this._textures[ name ];
  10592. const index = this.renderTarget.textures.indexOf( texture );
  10593. this.renderTarget.textures[ index ] = prevTexture;
  10594. this._textures[ name ] = prevTexture;
  10595. this._previousTextures[ name ] = texture;
  10596. this._textureNodes[ name ].updateTexture();
  10597. this._previousTextureNodes[ name ].updateTexture();
  10598. }
  10599. }
  10600. getTextureNode( name = 'output' ) {
  10601. let textureNode = this._textureNodes[ name ];
  10602. if ( textureNode === undefined ) {
  10603. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  10604. textureNode.updateTexture();
  10605. this._textureNodes[ name ] = textureNode;
  10606. }
  10607. return textureNode;
  10608. }
  10609. getPreviousTextureNode( name = 'output' ) {
  10610. let textureNode = this._previousTextureNodes[ name ];
  10611. if ( textureNode === undefined ) {
  10612. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  10613. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  10614. textureNode.updateTexture();
  10615. this._previousTextureNodes[ name ] = textureNode;
  10616. }
  10617. return textureNode;
  10618. }
  10619. getViewZNode( name = 'depth' ) {
  10620. let viewZNode = this._viewZNodes[ name ];
  10621. if ( viewZNode === undefined ) {
  10622. const cameraNear = this._cameraNear;
  10623. const cameraFar = this._cameraFar;
  10624. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  10625. }
  10626. return viewZNode;
  10627. }
  10628. getLinearDepthNode( name = 'depth' ) {
  10629. let linearDepthNode = this._linearDepthNodes[ name ];
  10630. if ( linearDepthNode === undefined ) {
  10631. const cameraNear = this._cameraNear;
  10632. const cameraFar = this._cameraFar;
  10633. const viewZNode = this.getViewZNode( name );
  10634. // TODO: just if ( builder.camera.isPerspectiveCamera )
  10635. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  10636. }
  10637. return linearDepthNode;
  10638. }
  10639. setup( { renderer } ) {
  10640. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  10641. // Disable MSAA for WebGL backend for now
  10642. if ( renderer.backend.isWebGLBackend === true ) {
  10643. this.renderTarget.samples = 0;
  10644. }
  10645. this.renderTarget.depthTexture.isMultisampleRenderTargetTexture = this.renderTarget.samples > 1;
  10646. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  10647. }
  10648. updateBefore( frame ) {
  10649. const { renderer } = frame;
  10650. const { scene, camera } = this;
  10651. this._pixelRatio = renderer.getPixelRatio();
  10652. const size = renderer.getSize( _size );
  10653. this.setSize( size.width, size.height );
  10654. const currentRenderTarget = renderer.getRenderTarget();
  10655. const currentMRT = renderer.getMRT();
  10656. this._cameraNear.value = camera.near;
  10657. this._cameraFar.value = camera.far;
  10658. for ( const name in this._previousTextures ) {
  10659. this.toggleTexture( name );
  10660. }
  10661. renderer.setRenderTarget( this.renderTarget );
  10662. renderer.setMRT( this._mrt );
  10663. renderer.render( scene, camera );
  10664. renderer.setRenderTarget( currentRenderTarget );
  10665. renderer.setMRT( currentMRT );
  10666. }
  10667. setSize( width, height ) {
  10668. this._width = width;
  10669. this._height = height;
  10670. const effectiveWidth = this._width * this._pixelRatio;
  10671. const effectiveHeight = this._height * this._pixelRatio;
  10672. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  10673. }
  10674. setPixelRatio( pixelRatio ) {
  10675. this._pixelRatio = pixelRatio;
  10676. this.setSize( this._width, this._height );
  10677. }
  10678. dispose() {
  10679. this.renderTarget.dispose();
  10680. }
  10681. }
  10682. PassNode.COLOR = 'color';
  10683. PassNode.DEPTH = 'depth';
  10684. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  10685. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  10686. const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) );
  10687. class ToonOutlinePassNode extends PassNode {
  10688. static get type() {
  10689. return 'ToonOutlinePassNode';
  10690. }
  10691. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  10692. super( PassNode.COLOR, scene, camera );
  10693. this.colorNode = colorNode;
  10694. this.thicknessNode = thicknessNode;
  10695. this.alphaNode = alphaNode;
  10696. this._materialCache = new WeakMap();
  10697. }
  10698. updateBefore( frame ) {
  10699. const { renderer } = frame;
  10700. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  10701. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  10702. // only render outline for supported materials
  10703. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  10704. if ( material.wireframe === false ) {
  10705. const outlineMaterial = this._getOutlineMaterial( material );
  10706. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  10707. }
  10708. }
  10709. // default
  10710. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  10711. } );
  10712. super.updateBefore( frame );
  10713. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  10714. }
  10715. _createMaterial() {
  10716. const material = new NodeMaterial();
  10717. material.isMeshToonOutlineMaterial = true;
  10718. material.name = 'Toon_Outline';
  10719. material.side = BackSide;
  10720. // vertex node
  10721. const outlineNormal = normalLocal.negate();
  10722. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  10723. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  10724. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  10725. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  10726. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  10727. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  10728. // color node
  10729. material.colorNode = vec4( this.colorNode, this.alphaNode );
  10730. return material;
  10731. }
  10732. _getOutlineMaterial( originalMaterial ) {
  10733. let outlineMaterial = this._materialCache.get( originalMaterial );
  10734. if ( outlineMaterial === undefined ) {
  10735. outlineMaterial = this._createMaterial();
  10736. this._materialCache.set( originalMaterial, outlineMaterial );
  10737. }
  10738. return outlineMaterial;
  10739. }
  10740. }
  10741. 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 ) ) );
  10742. // exposure only
  10743. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  10744. return color.mul( exposure ).clamp();
  10745. } ).setLayout( {
  10746. name: 'linearToneMapping',
  10747. type: 'vec3',
  10748. inputs: [
  10749. { name: 'color', type: 'vec3' },
  10750. { name: 'exposure', type: 'float' }
  10751. ]
  10752. } );
  10753. // source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf
  10754. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  10755. color = color.mul( exposure );
  10756. return color.div( color.add( 1.0 ) ).clamp();
  10757. } ).setLayout( {
  10758. name: 'reinhardToneMapping',
  10759. type: 'vec3',
  10760. inputs: [
  10761. { name: 'color', type: 'vec3' },
  10762. { name: 'exposure', type: 'float' }
  10763. ]
  10764. } );
  10765. // source: http://filmicworlds.com/blog/filmic-tonemapping-operators/
  10766. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  10767. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  10768. color = color.mul( exposure );
  10769. color = color.sub( 0.004 ).max( 0.0 );
  10770. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  10771. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  10772. return a.div( b ).pow( 2.2 );
  10773. } ).setLayout( {
  10774. name: 'cineonToneMapping',
  10775. type: 'vec3',
  10776. inputs: [
  10777. { name: 'color', type: 'vec3' },
  10778. { name: 'exposure', type: 'float' }
  10779. ]
  10780. } );
  10781. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  10782. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  10783. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  10784. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  10785. return a.div( b );
  10786. } );
  10787. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  10788. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  10789. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  10790. const ACESInputMat = mat3(
  10791. 0.59719, 0.35458, 0.04823,
  10792. 0.07600, 0.90834, 0.01566,
  10793. 0.02840, 0.13383, 0.83777
  10794. );
  10795. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  10796. const ACESOutputMat = mat3(
  10797. 1.60475, - 0.53108, - 0.07367,
  10798. - 0.10208, 1.10813, - 0.00605,
  10799. - 0.00327, - 0.07276, 1.07602
  10800. );
  10801. color = color.mul( exposure ).div( 0.6 );
  10802. color = ACESInputMat.mul( color );
  10803. // Apply RRT and ODT
  10804. color = RRTAndODTFit( color );
  10805. color = ACESOutputMat.mul( color );
  10806. // Clamp to [0, 1]
  10807. return color.clamp();
  10808. } ).setLayout( {
  10809. name: 'acesFilmicToneMapping',
  10810. type: 'vec3',
  10811. inputs: [
  10812. { name: 'color', type: 'vec3' },
  10813. { name: 'exposure', type: 'float' }
  10814. ]
  10815. } );
  10816. 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 ) );
  10817. 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 ) );
  10818. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  10819. const x = vec3( x_immutable ).toVar();
  10820. const x2 = vec3( x.mul( x ) ).toVar();
  10821. const x4 = vec3( x2.mul( x2 ) ).toVar();
  10822. 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 ) ) ) );
  10823. } );
  10824. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  10825. const colortone = vec3( color ).toVar();
  10826. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  10827. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  10828. const AgxMinEv = float( - 12.47393 );
  10829. const AgxMaxEv = float( 4.026069 );
  10830. colortone.mulAssign( exposure );
  10831. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  10832. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  10833. colortone.assign( max$1( colortone, 1e-10 ) );
  10834. colortone.assign( log2( colortone ) );
  10835. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  10836. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  10837. colortone.assign( agxDefaultContrastApprox( colortone ) );
  10838. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  10839. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  10840. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  10841. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  10842. return colortone;
  10843. } ).setLayout( {
  10844. name: 'agxToneMapping',
  10845. type: 'vec3',
  10846. inputs: [
  10847. { name: 'color', type: 'vec3' },
  10848. { name: 'exposure', type: 'float' }
  10849. ]
  10850. } );
  10851. // https://modelviewer.dev/examples/tone-mapping
  10852. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  10853. const StartCompression = float( 0.8 - 0.04 );
  10854. const Desaturation = float( 0.15 );
  10855. color = color.mul( exposure );
  10856. const x = min$1( color.r, min$1( color.g, color.b ) );
  10857. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  10858. color.subAssign( offset );
  10859. const peak = max$1( color.r, max$1( color.g, color.b ) );
  10860. If( peak.lessThan( StartCompression ), () => {
  10861. return color;
  10862. } );
  10863. const d = sub( 1, StartCompression );
  10864. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  10865. color.mulAssign( newPeak.div( peak ) );
  10866. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  10867. return mix( color, vec3( newPeak ), g );
  10868. } ).setLayout( {
  10869. name: 'neutralToneMapping',
  10870. type: 'vec3',
  10871. inputs: [
  10872. { name: 'color', type: 'vec3' },
  10873. { name: 'exposure', type: 'float' }
  10874. ]
  10875. } );
  10876. class CodeNode extends Node {
  10877. static get type() {
  10878. return 'CodeNode';
  10879. }
  10880. constructor( code = '', includes = [], language = '' ) {
  10881. super( 'code' );
  10882. this.isCodeNode = true;
  10883. this.code = code;
  10884. this.language = language;
  10885. this.includes = includes;
  10886. }
  10887. isGlobal() {
  10888. return true;
  10889. }
  10890. setIncludes( includes ) {
  10891. this.includes = includes;
  10892. return this;
  10893. }
  10894. getIncludes( /*builder*/ ) {
  10895. return this.includes;
  10896. }
  10897. generate( builder ) {
  10898. const includes = this.getIncludes( builder );
  10899. for ( const include of includes ) {
  10900. include.build( builder );
  10901. }
  10902. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  10903. nodeCode.code = this.code;
  10904. return nodeCode.code;
  10905. }
  10906. serialize( data ) {
  10907. super.serialize( data );
  10908. data.code = this.code;
  10909. data.language = this.language;
  10910. }
  10911. deserialize( data ) {
  10912. super.deserialize( data );
  10913. this.code = data.code;
  10914. this.language = data.language;
  10915. }
  10916. }
  10917. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  10918. const js = ( src, includes ) => code( src, includes, 'js' );
  10919. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  10920. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  10921. class FunctionNode extends CodeNode {
  10922. static get type() {
  10923. return 'FunctionNode';
  10924. }
  10925. constructor( code = '', includes = [], language = '' ) {
  10926. super( code, includes, language );
  10927. }
  10928. getNodeType( builder ) {
  10929. return this.getNodeFunction( builder ).type;
  10930. }
  10931. getInputs( builder ) {
  10932. return this.getNodeFunction( builder ).inputs;
  10933. }
  10934. getNodeFunction( builder ) {
  10935. const nodeData = builder.getDataFromNode( this );
  10936. let nodeFunction = nodeData.nodeFunction;
  10937. if ( nodeFunction === undefined ) {
  10938. nodeFunction = builder.parser.parseFunction( this.code );
  10939. nodeData.nodeFunction = nodeFunction;
  10940. }
  10941. return nodeFunction;
  10942. }
  10943. generate( builder, output ) {
  10944. super.generate( builder );
  10945. const nodeFunction = this.getNodeFunction( builder );
  10946. const name = nodeFunction.name;
  10947. const type = nodeFunction.type;
  10948. const nodeCode = builder.getCodeFromNode( this, type );
  10949. if ( name !== '' ) {
  10950. // use a custom property name
  10951. nodeCode.name = name;
  10952. }
  10953. const propertyName = builder.getPropertyName( nodeCode );
  10954. const code = this.getNodeFunction( builder ).getCode( propertyName );
  10955. nodeCode.code = code + '\n';
  10956. if ( output === 'property' ) {
  10957. return propertyName;
  10958. } else {
  10959. return builder.format( `${ propertyName }()`, type, output );
  10960. }
  10961. }
  10962. }
  10963. const nativeFn = ( code, includes = [], language = '' ) => {
  10964. for ( let i = 0; i < includes.length; i ++ ) {
  10965. const include = includes[ i ];
  10966. // TSL Function: glslFn, wgslFn
  10967. if ( typeof include === 'function' ) {
  10968. includes[ i ] = include.functionNode;
  10969. }
  10970. }
  10971. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  10972. const fn = ( ...params ) => functionNode.call( ...params );
  10973. fn.functionNode = functionNode;
  10974. return fn;
  10975. };
  10976. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  10977. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  10978. class ScriptableValueNode extends Node {
  10979. static get type() {
  10980. return 'ScriptableValueNode';
  10981. }
  10982. constructor( value = null ) {
  10983. super();
  10984. this._value = value;
  10985. this._cache = null;
  10986. this.inputType = null;
  10987. this.outpuType = null;
  10988. this.events = new EventDispatcher();
  10989. this.isScriptableValueNode = true;
  10990. }
  10991. get isScriptableOutputNode() {
  10992. return this.outputType !== null;
  10993. }
  10994. set value( val ) {
  10995. if ( this._value === val ) return;
  10996. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  10997. URL.revokeObjectURL( this._cache );
  10998. this._cache = null;
  10999. }
  11000. this._value = val;
  11001. this.events.dispatchEvent( { type: 'change' } );
  11002. this.refresh();
  11003. }
  11004. get value() {
  11005. return this._value;
  11006. }
  11007. refresh() {
  11008. this.events.dispatchEvent( { type: 'refresh' } );
  11009. }
  11010. getValue() {
  11011. const value = this.value;
  11012. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  11013. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  11014. } else if ( value && value.value !== null && value.value !== undefined && (
  11015. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  11016. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  11017. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  11018. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  11019. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  11020. ( this.inputType === 'Color' && value.value.isColor ) ||
  11021. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  11022. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  11023. ) ) {
  11024. return value.value;
  11025. }
  11026. return this._cache || value;
  11027. }
  11028. getNodeType( builder ) {
  11029. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  11030. }
  11031. setup() {
  11032. return this.value && this.value.isNode ? this.value : float();
  11033. }
  11034. serialize( data ) {
  11035. super.serialize( data );
  11036. if ( this.value !== null ) {
  11037. if ( this.inputType === 'ArrayBuffer' ) {
  11038. data.value = arrayBufferToBase64( this.value );
  11039. } else {
  11040. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  11041. }
  11042. } else {
  11043. data.value = null;
  11044. }
  11045. data.inputType = this.inputType;
  11046. data.outputType = this.outputType;
  11047. }
  11048. deserialize( data ) {
  11049. super.deserialize( data );
  11050. let value = null;
  11051. if ( data.value !== null ) {
  11052. if ( data.inputType === 'ArrayBuffer' ) {
  11053. value = base64ToArrayBuffer( data.value );
  11054. } else if ( data.inputType === 'Texture' ) {
  11055. value = data.meta.textures[ data.value ];
  11056. } else {
  11057. value = data.meta.nodes[ data.value ] || null;
  11058. }
  11059. }
  11060. this.value = value;
  11061. this.inputType = data.inputType;
  11062. this.outputType = data.outputType;
  11063. }
  11064. }
  11065. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  11066. class Resources extends Map {
  11067. get( key, callback = null, ...params ) {
  11068. if ( this.has( key ) ) return super.get( key );
  11069. if ( callback !== null ) {
  11070. const value = callback( ...params );
  11071. this.set( key, value );
  11072. return value;
  11073. }
  11074. }
  11075. }
  11076. class Parameters {
  11077. constructor( scriptableNode ) {
  11078. this.scriptableNode = scriptableNode;
  11079. }
  11080. get parameters() {
  11081. return this.scriptableNode.parameters;
  11082. }
  11083. get layout() {
  11084. return this.scriptableNode.getLayout();
  11085. }
  11086. getInputLayout( id ) {
  11087. return this.scriptableNode.getInputLayout( id );
  11088. }
  11089. get( name ) {
  11090. const param = this.parameters[ name ];
  11091. const value = param ? param.getValue() : null;
  11092. return value;
  11093. }
  11094. }
  11095. const ScriptableNodeResources = new Resources();
  11096. class ScriptableNode extends Node {
  11097. static get type() {
  11098. return 'ScriptableNode';
  11099. }
  11100. constructor( codeNode = null, parameters = {} ) {
  11101. super();
  11102. this.codeNode = codeNode;
  11103. this.parameters = parameters;
  11104. this._local = new Resources();
  11105. this._output = scriptableValue();
  11106. this._outputs = {};
  11107. this._source = this.source;
  11108. this._method = null;
  11109. this._object = null;
  11110. this._value = null;
  11111. this._needsOutputUpdate = true;
  11112. this.onRefresh = this.onRefresh.bind( this );
  11113. this.isScriptableNode = true;
  11114. }
  11115. get source() {
  11116. return this.codeNode ? this.codeNode.code : '';
  11117. }
  11118. setLocal( name, value ) {
  11119. return this._local.set( name, value );
  11120. }
  11121. getLocal( name ) {
  11122. return this._local.get( name );
  11123. }
  11124. onRefresh() {
  11125. this._refresh();
  11126. }
  11127. getInputLayout( id ) {
  11128. for ( const element of this.getLayout() ) {
  11129. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  11130. return element;
  11131. }
  11132. }
  11133. }
  11134. getOutputLayout( id ) {
  11135. for ( const element of this.getLayout() ) {
  11136. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  11137. return element;
  11138. }
  11139. }
  11140. }
  11141. setOutput( name, value ) {
  11142. const outputs = this._outputs;
  11143. if ( outputs[ name ] === undefined ) {
  11144. outputs[ name ] = scriptableValue( value );
  11145. } else {
  11146. outputs[ name ].value = value;
  11147. }
  11148. return this;
  11149. }
  11150. getOutput( name ) {
  11151. return this._outputs[ name ];
  11152. }
  11153. getParameter( name ) {
  11154. return this.parameters[ name ];
  11155. }
  11156. setParameter( name, value ) {
  11157. const parameters = this.parameters;
  11158. if ( value && value.isScriptableNode ) {
  11159. this.deleteParameter( name );
  11160. parameters[ name ] = value;
  11161. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  11162. } else if ( value && value.isScriptableValueNode ) {
  11163. this.deleteParameter( name );
  11164. parameters[ name ] = value;
  11165. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  11166. } else if ( parameters[ name ] === undefined ) {
  11167. parameters[ name ] = scriptableValue( value );
  11168. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  11169. } else {
  11170. parameters[ name ].value = value;
  11171. }
  11172. return this;
  11173. }
  11174. getValue() {
  11175. return this.getDefaultOutput().getValue();
  11176. }
  11177. deleteParameter( name ) {
  11178. let valueNode = this.parameters[ name ];
  11179. if ( valueNode ) {
  11180. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  11181. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  11182. }
  11183. return this;
  11184. }
  11185. clearParameters() {
  11186. for ( const name of Object.keys( this.parameters ) ) {
  11187. this.deleteParameter( name );
  11188. }
  11189. this.needsUpdate = true;
  11190. return this;
  11191. }
  11192. call( name, ...params ) {
  11193. const object = this.getObject();
  11194. const method = object[ name ];
  11195. if ( typeof method === 'function' ) {
  11196. return method( ...params );
  11197. }
  11198. }
  11199. async callAsync( name, ...params ) {
  11200. const object = this.getObject();
  11201. const method = object[ name ];
  11202. if ( typeof method === 'function' ) {
  11203. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  11204. }
  11205. }
  11206. getNodeType( builder ) {
  11207. return this.getDefaultOutputNode().getNodeType( builder );
  11208. }
  11209. refresh( output = null ) {
  11210. if ( output !== null ) {
  11211. this.getOutput( output ).refresh();
  11212. } else {
  11213. this._refresh();
  11214. }
  11215. }
  11216. getObject() {
  11217. if ( this.needsUpdate ) this.dispose();
  11218. if ( this._object !== null ) return this._object;
  11219. //
  11220. const refresh = () => this.refresh();
  11221. const setOutput = ( id, value ) => this.setOutput( id, value );
  11222. const parameters = new Parameters( this );
  11223. const THREE = ScriptableNodeResources.get( 'THREE' );
  11224. const TSL = ScriptableNodeResources.get( 'TSL' );
  11225. const method = this.getMethod( this.codeNode );
  11226. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  11227. this._object = method( ...params );
  11228. const layout = this._object.layout;
  11229. if ( layout ) {
  11230. if ( layout.cache === false ) {
  11231. this._local.clear();
  11232. }
  11233. // default output
  11234. this._output.outputType = layout.outputType || null;
  11235. if ( Array.isArray( layout.elements ) ) {
  11236. for ( const element of layout.elements ) {
  11237. const id = element.id || element.name;
  11238. if ( element.inputType ) {
  11239. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  11240. this.getParameter( id ).inputType = element.inputType;
  11241. }
  11242. if ( element.outputType ) {
  11243. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  11244. this.getOutput( id ).outputType = element.outputType;
  11245. }
  11246. }
  11247. }
  11248. }
  11249. return this._object;
  11250. }
  11251. deserialize( data ) {
  11252. super.deserialize( data );
  11253. for ( const name in this.parameters ) {
  11254. let valueNode = this.parameters[ name ];
  11255. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  11256. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  11257. }
  11258. }
  11259. getLayout() {
  11260. return this.getObject().layout;
  11261. }
  11262. getDefaultOutputNode() {
  11263. const output = this.getDefaultOutput().value;
  11264. if ( output && output.isNode ) {
  11265. return output;
  11266. }
  11267. return float();
  11268. }
  11269. getDefaultOutput() {
  11270. return this._exec()._output;
  11271. }
  11272. getMethod() {
  11273. if ( this.needsUpdate ) this.dispose();
  11274. if ( this._method !== null ) return this._method;
  11275. //
  11276. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  11277. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  11278. const properties = interfaceProps.join( ', ' );
  11279. const declarations = 'var ' + properties + '; var output = {};\n';
  11280. const returns = '\nreturn { ...output, ' + properties + ' };';
  11281. const code = declarations + this.codeNode.code + returns;
  11282. //
  11283. this._method = new Function( ...parametersProps, code );
  11284. return this._method;
  11285. }
  11286. dispose() {
  11287. if ( this._method === null ) return;
  11288. if ( this._object && typeof this._object.dispose === 'function' ) {
  11289. this._object.dispose();
  11290. }
  11291. this._method = null;
  11292. this._object = null;
  11293. this._source = null;
  11294. this._value = null;
  11295. this._needsOutputUpdate = true;
  11296. this._output.value = null;
  11297. this._outputs = {};
  11298. }
  11299. setup() {
  11300. return this.getDefaultOutputNode();
  11301. }
  11302. getCacheKey( force ) {
  11303. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  11304. for ( const param in this.parameters ) {
  11305. values.push( this.parameters[ param ].getCacheKey( force ) );
  11306. }
  11307. return hashArray( values );
  11308. }
  11309. set needsUpdate( value ) {
  11310. if ( value === true ) this.dispose();
  11311. }
  11312. get needsUpdate() {
  11313. return this.source !== this._source;
  11314. }
  11315. _exec() {
  11316. if ( this.codeNode === null ) return this;
  11317. if ( this._needsOutputUpdate === true ) {
  11318. this._value = this.call( 'main' );
  11319. this._needsOutputUpdate = false;
  11320. }
  11321. this._output.value = this._value;
  11322. return this;
  11323. }
  11324. _refresh() {
  11325. this.needsUpdate = true;
  11326. this._exec();
  11327. this._output.refresh();
  11328. }
  11329. }
  11330. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  11331. class FogNode extends Node {
  11332. static get type() {
  11333. return 'FogNode';
  11334. }
  11335. constructor( colorNode, factorNode ) {
  11336. super( 'float' );
  11337. this.isFogNode = true;
  11338. this.colorNode = colorNode;
  11339. this.factorNode = factorNode;
  11340. }
  11341. getViewZNode( builder ) {
  11342. let viewZ;
  11343. const getViewZ = builder.context.getViewZ;
  11344. if ( getViewZ !== undefined ) {
  11345. viewZ = getViewZ( this );
  11346. }
  11347. return ( viewZ || positionView.z ).negate();
  11348. }
  11349. setup() {
  11350. return this.factorNode;
  11351. }
  11352. }
  11353. const fog = /*@__PURE__*/ nodeProxy( FogNode );
  11354. class FogRangeNode extends FogNode {
  11355. static get type() {
  11356. return 'FogRangeNode';
  11357. }
  11358. constructor( colorNode, nearNode, farNode ) {
  11359. super( colorNode );
  11360. this.isFogRangeNode = true;
  11361. this.nearNode = nearNode;
  11362. this.farNode = farNode;
  11363. }
  11364. setup( builder ) {
  11365. const viewZ = this.getViewZNode( builder );
  11366. return smoothstep( this.nearNode, this.farNode, viewZ );
  11367. }
  11368. }
  11369. const rangeFog = /*@__PURE__*/ nodeProxy( FogRangeNode );
  11370. class FogExp2Node extends FogNode {
  11371. static get type() {
  11372. return 'FogExp2Node';
  11373. }
  11374. constructor( colorNode, densityNode ) {
  11375. super( colorNode );
  11376. this.isFogExp2Node = true;
  11377. this.densityNode = densityNode;
  11378. }
  11379. setup( builder ) {
  11380. const viewZ = this.getViewZNode( builder );
  11381. const density = this.densityNode;
  11382. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  11383. }
  11384. }
  11385. const densityFog = /*@__PURE__*/ nodeProxy( FogExp2Node );
  11386. let min = null;
  11387. let max = null;
  11388. class RangeNode extends Node {
  11389. static get type() {
  11390. return 'RangeNode';
  11391. }
  11392. constructor( minNode = float(), maxNode = float() ) {
  11393. super();
  11394. this.minNode = minNode;
  11395. this.maxNode = maxNode;
  11396. }
  11397. getVectorLength( builder ) {
  11398. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  11399. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  11400. return minLength > maxLength ? minLength : maxLength;
  11401. }
  11402. getNodeType( builder ) {
  11403. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  11404. }
  11405. setup( builder ) {
  11406. const object = builder.object;
  11407. let output = null;
  11408. if ( object.count > 1 ) {
  11409. const minValue = this.minNode.value;
  11410. const maxValue = this.maxNode.value;
  11411. const minLength = builder.getTypeLength( getValueType( minValue ) );
  11412. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  11413. min = min || new Vector4();
  11414. max = max || new Vector4();
  11415. min.setScalar( 0 );
  11416. max.setScalar( 0 );
  11417. if ( minLength === 1 ) min.setScalar( minValue );
  11418. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b );
  11419. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  11420. if ( maxLength === 1 ) max.setScalar( maxValue );
  11421. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b );
  11422. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  11423. const stride = 4;
  11424. const length = stride * object.count;
  11425. const array = new Float32Array( length );
  11426. for ( let i = 0; i < length; i ++ ) {
  11427. const index = i % stride;
  11428. const minElementValue = min.getComponent( index );
  11429. const maxElementValue = max.getComponent( index );
  11430. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  11431. }
  11432. const nodeType = this.getNodeType( builder );
  11433. if ( object.count <= 4096 ) {
  11434. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  11435. } else {
  11436. // TODO: Improve anonymous buffer attribute creation removing this part
  11437. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  11438. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  11439. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  11440. }
  11441. } else {
  11442. output = float( 0 );
  11443. }
  11444. return output;
  11445. }
  11446. }
  11447. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  11448. class ComputeBuiltinNode extends Node {
  11449. static get type() {
  11450. return 'ComputeBuiltinNode';
  11451. }
  11452. constructor( builtinName, nodeType ) {
  11453. super( nodeType );
  11454. this._builtinName = builtinName;
  11455. }
  11456. getHash( builder ) {
  11457. return this.getBuiltinName( builder );
  11458. }
  11459. getNodeType( /*builder*/ ) {
  11460. return this.nodeType;
  11461. }
  11462. setBuiltinName( builtinName ) {
  11463. this._builtinName = builtinName;
  11464. return this;
  11465. }
  11466. getBuiltinName( /*builder*/ ) {
  11467. return this._builtinName;
  11468. }
  11469. hasBuiltin( builder ) {
  11470. builder.hasBuiltin( this._builtinName );
  11471. }
  11472. generate( builder, output ) {
  11473. const builtinName = this.getBuiltinName( builder );
  11474. const nodeType = this.getNodeType( builder );
  11475. if ( builder.shaderStage === 'compute' ) {
  11476. return builder.format( builtinName, nodeType, output );
  11477. } else {
  11478. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  11479. return builder.generateConst( nodeType );
  11480. }
  11481. }
  11482. serialize( data ) {
  11483. super.serialize( data );
  11484. data.global = this.global;
  11485. data._builtinName = this._builtinName;
  11486. }
  11487. deserialize( data ) {
  11488. super.deserialize( data );
  11489. this.global = data.global;
  11490. this._builtinName = data._builtinName;
  11491. }
  11492. }
  11493. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  11494. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  11495. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  11496. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  11497. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  11498. class BarrierNode extends Node {
  11499. constructor( scope ) {
  11500. super();
  11501. this.scope = scope;
  11502. }
  11503. generate( builder ) {
  11504. const { scope } = this;
  11505. const { renderer } = builder;
  11506. if ( renderer.backend.isWebGLBackend === true ) {
  11507. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  11508. } else {
  11509. builder.addLineFlowCode( `${scope}Barrier()`, this );
  11510. }
  11511. }
  11512. }
  11513. const barrier = nodeProxy( BarrierNode );
  11514. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  11515. const storageBarrier = () => barrier( 'storage' ).append();
  11516. const textureBarrier = () => barrier( 'texture' ).append();
  11517. class WorkgroupInfoElementNode extends ArrayElementNode {
  11518. constructor( workgroupInfoNode, indexNode ) {
  11519. super( workgroupInfoNode, indexNode );
  11520. this.isWorkgroupInfoElementNode = true;
  11521. }
  11522. generate( builder, output ) {
  11523. let snippet;
  11524. const isAssignContext = builder.context.assign;
  11525. snippet = super.generate( builder );
  11526. if ( isAssignContext !== true ) {
  11527. const type = this.getNodeType( builder );
  11528. snippet = builder.format( snippet, type, output );
  11529. }
  11530. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  11531. return snippet;
  11532. }
  11533. }
  11534. class WorkgroupInfoNode extends Node {
  11535. constructor( scope, bufferType, bufferCount = 0 ) {
  11536. super( bufferType );
  11537. this.bufferType = bufferType;
  11538. this.bufferCount = bufferCount;
  11539. this.isWorkgroupInfoNode = true;
  11540. this.scope = scope;
  11541. }
  11542. label( name ) {
  11543. this.name = name;
  11544. return this;
  11545. }
  11546. getHash() {
  11547. return this.uuid;
  11548. }
  11549. setScope( scope ) {
  11550. this.scope = scope;
  11551. return this;
  11552. }
  11553. getInputType( /*builder*/ ) {
  11554. return `${this.scope}Array`;
  11555. }
  11556. element( indexNode ) {
  11557. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  11558. }
  11559. generate( builder ) {
  11560. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  11561. }
  11562. }
  11563. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  11564. class AtomicFunctionNode extends TempNode {
  11565. static get type() {
  11566. return 'AtomicFunctionNode';
  11567. }
  11568. constructor( method, pointerNode, valueNode, storeNode = null ) {
  11569. super( 'uint' );
  11570. this.method = method;
  11571. this.pointerNode = pointerNode;
  11572. this.valueNode = valueNode;
  11573. this.storeNode = storeNode;
  11574. }
  11575. getInputType( builder ) {
  11576. return this.pointerNode.getNodeType( builder );
  11577. }
  11578. getNodeType( builder ) {
  11579. return this.getInputType( builder );
  11580. }
  11581. generate( builder ) {
  11582. const method = this.method;
  11583. const type = this.getNodeType( builder );
  11584. const inputType = this.getInputType( builder );
  11585. const a = this.pointerNode;
  11586. const b = this.valueNode;
  11587. const params = [];
  11588. params.push( `&${ a.build( builder, inputType ) }` );
  11589. params.push( b.build( builder, inputType ) );
  11590. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  11591. if ( this.storeNode !== null ) {
  11592. const varSnippet = this.storeNode.build( builder, inputType );
  11593. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this );
  11594. } else {
  11595. builder.addLineFlowCode( methodSnippet, this );
  11596. }
  11597. }
  11598. }
  11599. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  11600. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  11601. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  11602. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  11603. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  11604. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  11605. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  11606. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  11607. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  11608. const atomicNode = nodeProxy( AtomicFunctionNode );
  11609. const atomicFunc = ( method, pointerNode, valueNode, storeNode ) => {
  11610. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  11611. node.append();
  11612. return node;
  11613. };
  11614. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  11615. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  11616. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  11617. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  11618. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  11619. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  11620. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  11621. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  11622. let uniformsLib;
  11623. function getLightData( light ) {
  11624. uniformsLib = uniformsLib || new WeakMap();
  11625. let uniforms = uniformsLib.get( light );
  11626. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  11627. return uniforms;
  11628. }
  11629. function lightShadowMatrix( light ) {
  11630. const data = getLightData( light );
  11631. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( () => {
  11632. light.shadow.updateMatrices( light );
  11633. return light.shadow.matrix;
  11634. } ) );
  11635. }
  11636. function lightProjectionUV( light ) {
  11637. const data = getLightData( light );
  11638. if ( data.projectionUV === undefined ) {
  11639. const spotLightCoord = lightShadowMatrix( light ).mul( positionWorld );
  11640. data.projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  11641. }
  11642. return data.projectionUV;
  11643. }
  11644. function lightPosition( light ) {
  11645. const data = getLightData( light );
  11646. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  11647. }
  11648. function lightTargetPosition( light ) {
  11649. const data = getLightData( light );
  11650. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  11651. }
  11652. function lightViewPosition( light ) {
  11653. const data = getLightData( light );
  11654. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  11655. self.value = self.value || new Vector3();
  11656. self.value.setFromMatrixPosition( light.matrixWorld );
  11657. self.value.applyMatrix4( camera.matrixWorldInverse );
  11658. } ) );
  11659. }
  11660. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  11661. const sortLights = ( lights ) => {
  11662. return lights.sort( ( a, b ) => a.id - b.id );
  11663. };
  11664. const getLightNodeById = ( id, lightNodes ) => {
  11665. for ( const lightNode of lightNodes ) {
  11666. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  11667. return lightNode;
  11668. }
  11669. }
  11670. return null;
  11671. };
  11672. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  11673. class LightsNode extends Node {
  11674. static get type() {
  11675. return 'LightsNode';
  11676. }
  11677. constructor() {
  11678. super( 'vec3' );
  11679. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  11680. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  11681. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  11682. this._lights = [];
  11683. this._lightNodes = null;
  11684. this._lightNodesHash = null;
  11685. this.global = true;
  11686. }
  11687. getHash( builder ) {
  11688. if ( this._lightNodesHash === null ) {
  11689. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  11690. const hash = [];
  11691. for ( const lightNode of this._lightNodes ) {
  11692. hash.push( lightNode.getSelf().getHash() );
  11693. }
  11694. this._lightNodesHash = 'lights-' + hash.join( ',' );
  11695. }
  11696. return this._lightNodesHash;
  11697. }
  11698. analyze( builder ) {
  11699. const properties = builder.getDataFromNode( this );
  11700. for ( const node of properties.nodes ) {
  11701. node.build( builder );
  11702. }
  11703. }
  11704. setupLightsNode( builder ) {
  11705. const lightNodes = [];
  11706. const previousLightNodes = this._lightNodes;
  11707. const lights = sortLights( this._lights );
  11708. const nodeLibrary = builder.renderer.library;
  11709. for ( const light of lights ) {
  11710. if ( light.isNode ) {
  11711. lightNodes.push( nodeObject( light ) );
  11712. } else {
  11713. let lightNode = null;
  11714. if ( previousLightNodes !== null ) {
  11715. lightNode = getLightNodeById( light.id, previousLightNodes ); // resuse existing light node
  11716. }
  11717. if ( lightNode === null ) {
  11718. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  11719. if ( lightNodeClass === null ) {
  11720. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  11721. continue;
  11722. }
  11723. let lightNode = null;
  11724. if ( ! _lightsNodeRef.has( light ) ) {
  11725. lightNode = nodeObject( new lightNodeClass( light ) );
  11726. _lightsNodeRef.set( light, lightNode );
  11727. } else {
  11728. lightNode = _lightsNodeRef.get( light );
  11729. }
  11730. lightNodes.push( lightNode );
  11731. }
  11732. }
  11733. }
  11734. this._lightNodes = lightNodes;
  11735. }
  11736. setupLights( builder, lightNodes ) {
  11737. for ( const lightNode of lightNodes ) {
  11738. lightNode.build( builder );
  11739. }
  11740. }
  11741. setup( builder ) {
  11742. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  11743. const context = builder.context;
  11744. const lightingModel = context.lightingModel;
  11745. let outgoingLightNode = this.outgoingLightNode;
  11746. if ( lightingModel ) {
  11747. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  11748. context.outgoingLight = outgoingLightNode;
  11749. const stack = builder.addStack();
  11750. //
  11751. const properties = builder.getDataFromNode( this );
  11752. properties.nodes = stack.nodes;
  11753. //
  11754. lightingModel.start( context, stack, builder );
  11755. // lights
  11756. this.setupLights( builder, _lightNodes );
  11757. //
  11758. lightingModel.indirect( context, stack, builder );
  11759. //
  11760. const { backdrop, backdropAlpha } = context;
  11761. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  11762. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  11763. if ( backdrop !== null ) {
  11764. if ( backdropAlpha !== null ) {
  11765. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  11766. } else {
  11767. totalDiffuse = vec3( backdrop );
  11768. }
  11769. context.material.transparent = true;
  11770. }
  11771. totalDiffuseNode.assign( totalDiffuse );
  11772. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  11773. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  11774. //
  11775. lightingModel.finish( context, stack, builder );
  11776. //
  11777. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  11778. }
  11779. return outgoingLightNode;
  11780. }
  11781. setLights( lights ) {
  11782. this._lights = lights;
  11783. this._lightNodes = null;
  11784. this._lightNodesHash = null;
  11785. return this;
  11786. }
  11787. getLights() {
  11788. return this._lights;
  11789. }
  11790. get hasLights() {
  11791. return this._lights.length > 0;
  11792. }
  11793. }
  11794. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  11795. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  11796. const shadowWorldPosition = /*@__PURE__*/ vec3().toVar( 'shadowWorldPosition' );
  11797. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  11798. let dist = positionWorld.sub( position ).length();
  11799. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  11800. dist = dist.saturate(); // clamp to [ 0, 1 ]
  11801. return dist;
  11802. } );
  11803. const linearShadowDistance = ( light ) => {
  11804. const camera = light.shadow.camera;
  11805. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  11806. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  11807. const referencePosition = objectPosition( light );
  11808. return linearDistance( referencePosition, nearDistance, farDistance );
  11809. };
  11810. const getShadowMaterial = ( light ) => {
  11811. let material = shadowMaterialLib.get( light );
  11812. if ( material === undefined ) {
  11813. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  11814. material = new NodeMaterial();
  11815. material.colorNode = vec4( 0, 0, 0, 1 );
  11816. material.depthNode = depthNode;
  11817. material.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  11818. material.blending = NoBlending;
  11819. material.name = 'ShadowMaterial';
  11820. shadowMaterialLib.set( light, material );
  11821. }
  11822. return material;
  11823. };
  11824. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  11825. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  11826. } );
  11827. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  11828. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  11829. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  11830. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  11831. const texelSize = vec2( 1 ).div( mapSize );
  11832. const dx0 = texelSize.x.negate().mul( radius );
  11833. const dy0 = texelSize.y.negate().mul( radius );
  11834. const dx1 = texelSize.x.mul( radius );
  11835. const dy1 = texelSize.y.mul( radius );
  11836. const dx2 = dx0.div( 2 );
  11837. const dy2 = dy0.div( 2 );
  11838. const dx3 = dx1.div( 2 );
  11839. const dy3 = dy1.div( 2 );
  11840. return add(
  11841. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  11842. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  11843. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  11844. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  11845. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  11846. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  11847. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  11848. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  11849. depthCompare( shadowCoord.xy, shadowCoord.z ),
  11850. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  11851. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  11852. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  11853. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  11854. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  11855. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  11856. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  11857. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  11858. ).mul( 1 / 17 );
  11859. } );
  11860. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  11861. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  11862. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  11863. const texelSize = vec2( 1 ).div( mapSize );
  11864. const dx = texelSize.x;
  11865. const dy = texelSize.y;
  11866. const uv = shadowCoord.xy;
  11867. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  11868. uv.subAssign( f.mul( texelSize ) );
  11869. return add(
  11870. depthCompare( uv, shadowCoord.z ),
  11871. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  11872. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  11873. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  11874. mix(
  11875. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  11876. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  11877. f.x
  11878. ),
  11879. mix(
  11880. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  11881. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  11882. f.x
  11883. ),
  11884. mix(
  11885. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  11886. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  11887. f.y
  11888. ),
  11889. mix(
  11890. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  11891. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  11892. f.y
  11893. ),
  11894. mix(
  11895. mix(
  11896. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  11897. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  11898. f.x
  11899. ),
  11900. mix(
  11901. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  11902. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  11903. f.x
  11904. ),
  11905. f.y
  11906. )
  11907. ).mul( 1 / 9 );
  11908. } );
  11909. // VSM
  11910. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  11911. const occlusion = float( 1 ).toVar();
  11912. const distribution = texture( depthTexture ).uv( shadowCoord.xy ).rg;
  11913. const hardShadow = step( shadowCoord.z, distribution.x );
  11914. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  11915. const distance = shadowCoord.z.sub( distribution.x );
  11916. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  11917. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  11918. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  11919. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  11920. } );
  11921. return occlusion;
  11922. } );
  11923. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  11924. const mean = float( 0 ).toVar();
  11925. const squaredMean = float( 0 ).toVar();
  11926. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  11927. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  11928. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  11929. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  11930. const depth = shadowPass.uv( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  11931. mean.addAssign( depth );
  11932. squaredMean.addAssign( depth.mul( depth ) );
  11933. } );
  11934. mean.divAssign( samples );
  11935. squaredMean.divAssign( samples );
  11936. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  11937. return vec2( mean, std_dev );
  11938. } );
  11939. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  11940. const mean = float( 0 ).toVar();
  11941. const squaredMean = float( 0 ).toVar();
  11942. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  11943. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  11944. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  11945. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  11946. const distribution = shadowPass.uv( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  11947. mean.addAssign( distribution.x );
  11948. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  11949. } );
  11950. mean.divAssign( samples );
  11951. squaredMean.divAssign( samples );
  11952. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  11953. return vec2( mean, std_dev );
  11954. } );
  11955. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  11956. //
  11957. const _quadMesh$1 = /*@__PURE__*/ new QuadMesh();
  11958. class ShadowNode extends Node {
  11959. static get type() {
  11960. return 'ShadowNode';
  11961. }
  11962. constructor( light, shadow = null ) {
  11963. super();
  11964. this.light = light;
  11965. this.shadow = shadow || light.shadow;
  11966. this.shadowMap = null;
  11967. this.vsmShadowMapVertical = null;
  11968. this.vsmShadowMapHorizontal = null;
  11969. this.vsmMaterialVertical = null;
  11970. this.vsmMaterialHorizontal = null;
  11971. this.updateBeforeType = NodeUpdateType.RENDER;
  11972. this._node = null;
  11973. this.isShadowNode = true;
  11974. }
  11975. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  11976. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  11977. .and( shadowCoord.x.lessThanEqual( 1 ) )
  11978. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  11979. .and( shadowCoord.y.lessThanEqual( 1 ) )
  11980. .and( shadowCoord.z.lessThanEqual( 1 ) );
  11981. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow } );
  11982. return frustumTest.select( shadowNode, float( 1 ) );
  11983. }
  11984. setupShadowCoord( builder, shadowPosition ) {
  11985. const { shadow } = this;
  11986. const { renderer } = builder;
  11987. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  11988. let shadowCoord = shadowPosition;
  11989. let coordZ;
  11990. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  11991. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  11992. coordZ = shadowCoord.z;
  11993. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  11994. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  11995. }
  11996. } else {
  11997. const w = shadowCoord.w;
  11998. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  11999. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  12000. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  12001. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  12002. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  12003. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  12004. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  12005. }
  12006. shadowCoord = vec3(
  12007. shadowCoord.x,
  12008. shadowCoord.y.oneMinus(), // follow webgpu standards
  12009. coordZ.add( bias )
  12010. );
  12011. return shadowCoord;
  12012. }
  12013. getShadowFilterFn( type ) {
  12014. return _shadowFilterLib[ type ];
  12015. }
  12016. setupShadow( builder ) {
  12017. const { renderer } = builder;
  12018. const { light, shadow } = this;
  12019. const shadowMapType = renderer.shadowMap.type;
  12020. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  12021. depthTexture.compareFunction = LessCompare;
  12022. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  12023. shadowMap.depthTexture = depthTexture;
  12024. shadow.camera.updateProjectionMatrix();
  12025. // VSM
  12026. if ( shadowMapType === VSMShadowMap ) {
  12027. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  12028. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  12029. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  12030. const shadowPassVertical = texture( depthTexture );
  12031. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  12032. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  12033. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  12034. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  12035. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  12036. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  12037. material.name = 'VSMVertical';
  12038. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  12039. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  12040. material.name = 'VSMHorizontal';
  12041. }
  12042. //
  12043. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  12044. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  12045. const shadowPosition = lightShadowMatrix( light ).mul( shadowWorldPosition.add( transformedNormalWorld.mul( normalBias ) ) );
  12046. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  12047. //
  12048. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  12049. if ( filterFn === null ) {
  12050. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  12051. }
  12052. const shadowDepthTexture = ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  12053. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow } );
  12054. const shadowColor = texture( shadowMap.texture, shadowCoord );
  12055. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  12056. this.shadowMap = shadowMap;
  12057. this.shadow.map = shadowMap;
  12058. return shadowOutput;
  12059. }
  12060. setup( builder ) {
  12061. if ( builder.renderer.shadowMap.enabled === false ) return;
  12062. return Fn( ( { material } ) => {
  12063. shadowWorldPosition.assign( material.shadowPositionNode || positionWorld );
  12064. let node = this._node;
  12065. if ( node === null ) {
  12066. this._node = node = this.setupShadow( builder );
  12067. }
  12068. if ( builder.material.shadowNode ) { // @deprecated, r171
  12069. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  12070. }
  12071. if ( builder.material.receivedShadowNode ) {
  12072. node = builder.material.receivedShadowNode( node );
  12073. }
  12074. return node;
  12075. } )();
  12076. }
  12077. renderShadow( frame ) {
  12078. const { shadow, shadowMap } = this;
  12079. const { renderer, scene } = frame;
  12080. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  12081. renderer.render( scene, shadow.camera );
  12082. }
  12083. updateShadow( frame ) {
  12084. const { shadowMap, light, shadow } = this;
  12085. const { renderer, scene, camera } = frame;
  12086. const shadowType = renderer.shadowMap.type;
  12087. const depthVersion = shadowMap.depthTexture.version;
  12088. this._depthVersionCached = depthVersion;
  12089. const currentOverrideMaterial = scene.overrideMaterial;
  12090. scene.overrideMaterial = getShadowMaterial( light );
  12091. shadow.camera.layers.mask = camera.layers.mask;
  12092. const currentRenderTarget = renderer.getRenderTarget();
  12093. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  12094. const currentMRT = renderer.getMRT();
  12095. renderer.setMRT( null );
  12096. renderer.setRenderObjectFunction( ( object, ...params ) => {
  12097. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  12098. renderer.renderObject( object, ...params );
  12099. }
  12100. } );
  12101. renderer.setRenderTarget( shadowMap );
  12102. this.renderShadow( frame );
  12103. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  12104. // vsm blur pass
  12105. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  12106. this.vsmPass( renderer );
  12107. }
  12108. renderer.setRenderTarget( currentRenderTarget );
  12109. renderer.setMRT( currentMRT );
  12110. scene.overrideMaterial = currentOverrideMaterial;
  12111. }
  12112. vsmPass( renderer ) {
  12113. const { shadow } = this;
  12114. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  12115. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  12116. renderer.setRenderTarget( this.vsmShadowMapVertical );
  12117. _quadMesh$1.material = this.vsmMaterialVertical;
  12118. _quadMesh$1.render( renderer );
  12119. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  12120. _quadMesh$1.material = this.vsmMaterialHorizontal;
  12121. _quadMesh$1.render( renderer );
  12122. }
  12123. dispose() {
  12124. this.shadowMap.dispose();
  12125. this.shadowMap = null;
  12126. if ( this.vsmShadowMapVertical !== null ) {
  12127. this.vsmShadowMapVertical.dispose();
  12128. this.vsmShadowMapVertical = null;
  12129. this.vsmMaterialVertical.dispose();
  12130. this.vsmMaterialVertical = null;
  12131. }
  12132. if ( this.vsmShadowMapHorizontal !== null ) {
  12133. this.vsmShadowMapHorizontal.dispose();
  12134. this.vsmShadowMapHorizontal = null;
  12135. this.vsmMaterialHorizontal.dispose();
  12136. this.vsmMaterialHorizontal = null;
  12137. }
  12138. this.updateBeforeType = NodeUpdateType.NONE;
  12139. }
  12140. updateBefore( frame ) {
  12141. const { shadow } = this;
  12142. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  12143. if ( needsUpdate ) {
  12144. this.updateShadow( frame );
  12145. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  12146. shadow.needsUpdate = false;
  12147. }
  12148. }
  12149. }
  12150. }
  12151. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  12152. class AnalyticLightNode extends LightingNode {
  12153. static get type() {
  12154. return 'AnalyticLightNode';
  12155. }
  12156. constructor( light = null ) {
  12157. super();
  12158. this.light = light;
  12159. this.color = new Color();
  12160. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  12161. this.baseColorNode = null;
  12162. this.shadowNode = null;
  12163. this.shadowColorNode = null;
  12164. this.isAnalyticLightNode = true;
  12165. this.updateType = NodeUpdateType.FRAME;
  12166. }
  12167. getCacheKey() {
  12168. return hash$1( super.getCacheKey(), this.light.id, this.light.castShadow ? 1 : 0 );
  12169. }
  12170. getHash() {
  12171. return this.light.uuid;
  12172. }
  12173. setupShadowNode() {
  12174. return shadow( this.light );
  12175. }
  12176. setupShadow( builder ) {
  12177. const { renderer } = builder;
  12178. if ( renderer.shadowMap.enabled === false ) return;
  12179. let shadowColorNode = this.shadowColorNode;
  12180. if ( shadowColorNode === null ) {
  12181. const customShadowNode = this.light.shadow.shadowNode;
  12182. let shadowNode;
  12183. if ( customShadowNode !== undefined ) {
  12184. shadowNode = nodeObject( customShadowNode );
  12185. } else {
  12186. shadowNode = this.setupShadowNode( builder );
  12187. }
  12188. this.shadowNode = shadowNode;
  12189. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  12190. this.baseColorNode = this.colorNode;
  12191. }
  12192. //
  12193. this.colorNode = shadowColorNode;
  12194. }
  12195. setup( builder ) {
  12196. this.colorNode = this.baseColorNode || this.colorNode;
  12197. if ( this.light.castShadow ) {
  12198. if ( builder.object.receiveShadow ) {
  12199. this.setupShadow( builder );
  12200. }
  12201. } else if ( this.shadowNode !== null ) {
  12202. this.shadowNode.dispose();
  12203. this.shadowNode = null;
  12204. this.shadowColorNode = null;
  12205. }
  12206. }
  12207. update( /*frame*/ ) {
  12208. const { light } = this;
  12209. this.color.copy( light.color ).multiplyScalar( light.intensity );
  12210. }
  12211. }
  12212. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  12213. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  12214. // based upon Frostbite 3 Moving to Physically-based Rendering
  12215. // page 32, equation 26: E[window1]
  12216. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  12217. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  12218. return cutoffDistance.greaterThan( 0 ).select(
  12219. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  12220. distanceFalloff
  12221. );
  12222. } ); // validated
  12223. const _clearColor$2 = /*@__PURE__*/ new Color();
  12224. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  12225. // vector suitable for 2D texture mapping. This code uses the following layout for the
  12226. // 2D texture:
  12227. //
  12228. // xzXZ
  12229. // y Y
  12230. //
  12231. // Y - Positive y direction
  12232. // y - Negative y direction
  12233. // X - Positive x direction
  12234. // x - Negative x direction
  12235. // Z - Positive z direction
  12236. // z - Negative z direction
  12237. //
  12238. // Source and test bed:
  12239. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  12240. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  12241. const v = pos.toVar();
  12242. // Number of texels to avoid at the edge of each square
  12243. const absV = abs( v );
  12244. // Intersect unit cube
  12245. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  12246. absV.mulAssign( scaleToCube );
  12247. // Apply scale to avoid seams
  12248. // two texels less per square (one texel will do for NEAREST)
  12249. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  12250. // Unwrap
  12251. // space: -1 ... 1 range for each square
  12252. //
  12253. // #X## dim := ( 4 , 2 )
  12254. // # # center := ( 1 , 1 )
  12255. const planar = vec2( v.xy ).toVar();
  12256. const almostATexel = texelSizeY.mul( 1.5 );
  12257. const almostOne = almostATexel.oneMinus();
  12258. If( absV.z.greaterThanEqual( almostOne ), () => {
  12259. If( v.z.greaterThan( 0.0 ), () => {
  12260. planar.x.assign( sub( 4.0, v.x ) );
  12261. } );
  12262. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  12263. const signX = sign( v.x );
  12264. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  12265. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  12266. const signY = sign( v.y );
  12267. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  12268. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  12269. } );
  12270. // Transform to UV space
  12271. // scale := 0.5 / dim
  12272. // translate := ( center + 0.5 ) / dim
  12273. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  12274. } ).setLayout( {
  12275. name: 'cubeToUV',
  12276. type: 'vec2',
  12277. inputs: [
  12278. { name: 'pos', type: 'vec3' },
  12279. { name: 'texelSizeY', type: 'float' }
  12280. ]
  12281. } );
  12282. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  12283. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  12284. } );
  12285. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  12286. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  12287. const offset = vec2( - 1.0, 1.0 ).mul( radius ).mul( texelSize.y );
  12288. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  12289. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  12290. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  12291. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  12292. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  12293. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  12294. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  12295. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  12296. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  12297. .mul( 1.0 / 9.0 );
  12298. } );
  12299. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  12300. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  12301. // the vector from the light to the world-space position of the fragment.
  12302. const lightToPosition = shadowCoord.xyz.toVar();
  12303. const lightToPositionLength = lightToPosition.length();
  12304. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  12305. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  12306. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  12307. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  12308. const result = float( 1.0 ).toVar();
  12309. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  12310. // dp = normalized distance from light to fragment position
  12311. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  12312. dp.addAssign( bias );
  12313. // bd3D = base direction 3D
  12314. const bd3D = lightToPosition.normalize();
  12315. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  12316. // percentage-closer filtering
  12317. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  12318. } );
  12319. return result;
  12320. } );
  12321. const _viewport = /*@__PURE__*/ new Vector4();
  12322. const _viewportSize = /*@__PURE__*/ new Vector2();
  12323. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  12324. //
  12325. class PointShadowNode extends ShadowNode {
  12326. static get type() {
  12327. return 'PointShadowNode';
  12328. }
  12329. constructor( light, shadow = null ) {
  12330. super( light, shadow );
  12331. }
  12332. getShadowFilterFn( type ) {
  12333. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  12334. }
  12335. setupShadowCoord( builder, shadowPosition ) {
  12336. return shadowPosition;
  12337. }
  12338. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  12339. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  12340. }
  12341. renderShadow( frame ) {
  12342. const { shadow, shadowMap, light } = this;
  12343. const { renderer, scene } = frame;
  12344. const shadowFrameExtents = shadow.getFrameExtents();
  12345. _shadowMapSize.copy( shadow.mapSize );
  12346. _shadowMapSize.multiply( shadowFrameExtents );
  12347. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  12348. _viewportSize.copy( shadow.mapSize );
  12349. //
  12350. const previousAutoClear = renderer.autoClear;
  12351. const previousClearColor = renderer.getClearColor( _clearColor$2 );
  12352. const previousClearAlpha = renderer.getClearAlpha();
  12353. renderer.autoClear = false;
  12354. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  12355. renderer.clear();
  12356. const viewportCount = shadow.getViewportCount();
  12357. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  12358. const viewport = shadow.getViewport( vp );
  12359. const x = _viewportSize.x * viewport.x;
  12360. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  12361. _viewport.set(
  12362. x,
  12363. y,
  12364. _viewportSize.x * viewport.z,
  12365. _viewportSize.y * viewport.w
  12366. );
  12367. shadowMap.viewport.copy( _viewport );
  12368. shadow.updateMatrices( light, vp );
  12369. renderer.render( scene, shadow.camera );
  12370. }
  12371. //
  12372. renderer.autoClear = previousAutoClear;
  12373. renderer.setClearColor( previousClearColor, previousClearAlpha );
  12374. }
  12375. }
  12376. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  12377. const directPointLight = Fn( ( { color, lightViewPosition, cutoffDistance, decayExponent }, builder ) => {
  12378. const lightingModel = builder.context.lightingModel;
  12379. const lVector = lightViewPosition.sub( positionView ); // @TODO: Add it into LightNode
  12380. const lightDirection = lVector.normalize();
  12381. const lightDistance = lVector.length();
  12382. const lightAttenuation = getDistanceAttenuation( {
  12383. lightDistance,
  12384. cutoffDistance,
  12385. decayExponent
  12386. } );
  12387. const lightColor = color.mul( lightAttenuation );
  12388. const reflectedLight = builder.context.reflectedLight;
  12389. lightingModel.direct( {
  12390. lightDirection,
  12391. lightColor,
  12392. reflectedLight
  12393. }, builder.stack, builder );
  12394. } );
  12395. class PointLightNode extends AnalyticLightNode {
  12396. static get type() {
  12397. return 'PointLightNode';
  12398. }
  12399. constructor( light = null ) {
  12400. super( light );
  12401. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  12402. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  12403. }
  12404. update( frame ) {
  12405. const { light } = this;
  12406. super.update( frame );
  12407. this.cutoffDistanceNode.value = light.distance;
  12408. this.decayExponentNode.value = light.decay;
  12409. }
  12410. setupShadowNode() {
  12411. return pointShadow( this.light );
  12412. }
  12413. setup( builder ) {
  12414. super.setup( builder );
  12415. directPointLight( {
  12416. color: this.colorNode,
  12417. lightViewPosition: lightViewPosition( this.light ),
  12418. cutoffDistance: this.cutoffDistanceNode,
  12419. decayExponent: this.decayExponentNode
  12420. } ).append();
  12421. }
  12422. }
  12423. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  12424. const uv = coord.mul( 2.0 );
  12425. const cx = uv.x.floor();
  12426. const cy = uv.y.floor();
  12427. const result = cx.add( cy ).mod( 2.0 );
  12428. return result.sign();
  12429. } );
  12430. // Three.js Transpiler
  12431. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  12432. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  12433. const f = float( f_immutable ).toVar();
  12434. const t = float( t_immutable ).toVar();
  12435. const b = bool( b_immutable ).toVar();
  12436. return select( b, t, f );
  12437. } ).setLayout( {
  12438. name: 'mx_select',
  12439. type: 'float',
  12440. inputs: [
  12441. { name: 'b', type: 'bool' },
  12442. { name: 't', type: 'float' },
  12443. { name: 'f', type: 'float' }
  12444. ]
  12445. } );
  12446. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  12447. const b = bool( b_immutable ).toVar();
  12448. const val = float( val_immutable ).toVar();
  12449. return select( b, val.negate(), val );
  12450. } ).setLayout( {
  12451. name: 'mx_negate_if',
  12452. type: 'float',
  12453. inputs: [
  12454. { name: 'val', type: 'float' },
  12455. { name: 'b', type: 'bool' }
  12456. ]
  12457. } );
  12458. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  12459. const x = float( x_immutable ).toVar();
  12460. return int( floor( x ) );
  12461. } ).setLayout( {
  12462. name: 'mx_floor',
  12463. type: 'int',
  12464. inputs: [
  12465. { name: 'x', type: 'float' }
  12466. ]
  12467. } );
  12468. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  12469. const x = float( x_immutable ).toVar();
  12470. i.assign( mx_floor( x ) );
  12471. return x.sub( float( i ) );
  12472. } );
  12473. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  12474. const t = float( t_immutable ).toVar();
  12475. const s = float( s_immutable ).toVar();
  12476. const v3 = float( v3_immutable ).toVar();
  12477. const v2 = float( v2_immutable ).toVar();
  12478. const v1 = float( v1_immutable ).toVar();
  12479. const v0 = float( v0_immutable ).toVar();
  12480. const s1 = float( sub( 1.0, s ) ).toVar();
  12481. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  12482. } ).setLayout( {
  12483. name: 'mx_bilerp_0',
  12484. type: 'float',
  12485. inputs: [
  12486. { name: 'v0', type: 'float' },
  12487. { name: 'v1', type: 'float' },
  12488. { name: 'v2', type: 'float' },
  12489. { name: 'v3', type: 'float' },
  12490. { name: 's', type: 'float' },
  12491. { name: 't', type: 'float' }
  12492. ]
  12493. } );
  12494. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  12495. const t = float( t_immutable ).toVar();
  12496. const s = float( s_immutable ).toVar();
  12497. const v3 = vec3( v3_immutable ).toVar();
  12498. const v2 = vec3( v2_immutable ).toVar();
  12499. const v1 = vec3( v1_immutable ).toVar();
  12500. const v0 = vec3( v0_immutable ).toVar();
  12501. const s1 = float( sub( 1.0, s ) ).toVar();
  12502. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  12503. } ).setLayout( {
  12504. name: 'mx_bilerp_1',
  12505. type: 'vec3',
  12506. inputs: [
  12507. { name: 'v0', type: 'vec3' },
  12508. { name: 'v1', type: 'vec3' },
  12509. { name: 'v2', type: 'vec3' },
  12510. { name: 'v3', type: 'vec3' },
  12511. { name: 's', type: 'float' },
  12512. { name: 't', type: 'float' }
  12513. ]
  12514. } );
  12515. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  12516. 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 ] ) => {
  12517. const r = float( r_immutable ).toVar();
  12518. const t = float( t_immutable ).toVar();
  12519. const s = float( s_immutable ).toVar();
  12520. const v7 = float( v7_immutable ).toVar();
  12521. const v6 = float( v6_immutable ).toVar();
  12522. const v5 = float( v5_immutable ).toVar();
  12523. const v4 = float( v4_immutable ).toVar();
  12524. const v3 = float( v3_immutable ).toVar();
  12525. const v2 = float( v2_immutable ).toVar();
  12526. const v1 = float( v1_immutable ).toVar();
  12527. const v0 = float( v0_immutable ).toVar();
  12528. const s1 = float( sub( 1.0, s ) ).toVar();
  12529. const t1 = float( sub( 1.0, t ) ).toVar();
  12530. const r1 = float( sub( 1.0, r ) ).toVar();
  12531. 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 ) ) ) ) ) );
  12532. } ).setLayout( {
  12533. name: 'mx_trilerp_0',
  12534. type: 'float',
  12535. inputs: [
  12536. { name: 'v0', type: 'float' },
  12537. { name: 'v1', type: 'float' },
  12538. { name: 'v2', type: 'float' },
  12539. { name: 'v3', type: 'float' },
  12540. { name: 'v4', type: 'float' },
  12541. { name: 'v5', type: 'float' },
  12542. { name: 'v6', type: 'float' },
  12543. { name: 'v7', type: 'float' },
  12544. { name: 's', type: 'float' },
  12545. { name: 't', type: 'float' },
  12546. { name: 'r', type: 'float' }
  12547. ]
  12548. } );
  12549. 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 ] ) => {
  12550. const r = float( r_immutable ).toVar();
  12551. const t = float( t_immutable ).toVar();
  12552. const s = float( s_immutable ).toVar();
  12553. const v7 = vec3( v7_immutable ).toVar();
  12554. const v6 = vec3( v6_immutable ).toVar();
  12555. const v5 = vec3( v5_immutable ).toVar();
  12556. const v4 = vec3( v4_immutable ).toVar();
  12557. const v3 = vec3( v3_immutable ).toVar();
  12558. const v2 = vec3( v2_immutable ).toVar();
  12559. const v1 = vec3( v1_immutable ).toVar();
  12560. const v0 = vec3( v0_immutable ).toVar();
  12561. const s1 = float( sub( 1.0, s ) ).toVar();
  12562. const t1 = float( sub( 1.0, t ) ).toVar();
  12563. const r1 = float( sub( 1.0, r ) ).toVar();
  12564. 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 ) ) ) ) ) );
  12565. } ).setLayout( {
  12566. name: 'mx_trilerp_1',
  12567. type: 'vec3',
  12568. inputs: [
  12569. { name: 'v0', type: 'vec3' },
  12570. { name: 'v1', type: 'vec3' },
  12571. { name: 'v2', type: 'vec3' },
  12572. { name: 'v3', type: 'vec3' },
  12573. { name: 'v4', type: 'vec3' },
  12574. { name: 'v5', type: 'vec3' },
  12575. { name: 'v6', type: 'vec3' },
  12576. { name: 'v7', type: 'vec3' },
  12577. { name: 's', type: 'float' },
  12578. { name: 't', type: 'float' },
  12579. { name: 'r', type: 'float' }
  12580. ]
  12581. } );
  12582. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  12583. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  12584. const y = float( y_immutable ).toVar();
  12585. const x = float( x_immutable ).toVar();
  12586. const hash = uint( hash_immutable ).toVar();
  12587. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  12588. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  12589. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  12590. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  12591. } ).setLayout( {
  12592. name: 'mx_gradient_float_0',
  12593. type: 'float',
  12594. inputs: [
  12595. { name: 'hash', type: 'uint' },
  12596. { name: 'x', type: 'float' },
  12597. { name: 'y', type: 'float' }
  12598. ]
  12599. } );
  12600. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  12601. const z = float( z_immutable ).toVar();
  12602. const y = float( y_immutable ).toVar();
  12603. const x = float( x_immutable ).toVar();
  12604. const hash = uint( hash_immutable ).toVar();
  12605. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  12606. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  12607. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  12608. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  12609. } ).setLayout( {
  12610. name: 'mx_gradient_float_1',
  12611. type: 'float',
  12612. inputs: [
  12613. { name: 'hash', type: 'uint' },
  12614. { name: 'x', type: 'float' },
  12615. { name: 'y', type: 'float' },
  12616. { name: 'z', type: 'float' }
  12617. ]
  12618. } );
  12619. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  12620. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  12621. const y = float( y_immutable ).toVar();
  12622. const x = float( x_immutable ).toVar();
  12623. const hash = uvec3( hash_immutable ).toVar();
  12624. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  12625. } ).setLayout( {
  12626. name: 'mx_gradient_vec3_0',
  12627. type: 'vec3',
  12628. inputs: [
  12629. { name: 'hash', type: 'uvec3' },
  12630. { name: 'x', type: 'float' },
  12631. { name: 'y', type: 'float' }
  12632. ]
  12633. } );
  12634. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  12635. const z = float( z_immutable ).toVar();
  12636. const y = float( y_immutable ).toVar();
  12637. const x = float( x_immutable ).toVar();
  12638. const hash = uvec3( hash_immutable ).toVar();
  12639. 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 ) );
  12640. } ).setLayout( {
  12641. name: 'mx_gradient_vec3_1',
  12642. type: 'vec3',
  12643. inputs: [
  12644. { name: 'hash', type: 'uvec3' },
  12645. { name: 'x', type: 'float' },
  12646. { name: 'y', type: 'float' },
  12647. { name: 'z', type: 'float' }
  12648. ]
  12649. } );
  12650. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  12651. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  12652. const v = float( v_immutable ).toVar();
  12653. return mul( 0.6616, v );
  12654. } ).setLayout( {
  12655. name: 'mx_gradient_scale2d_0',
  12656. type: 'float',
  12657. inputs: [
  12658. { name: 'v', type: 'float' }
  12659. ]
  12660. } );
  12661. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  12662. const v = float( v_immutable ).toVar();
  12663. return mul( 0.9820, v );
  12664. } ).setLayout( {
  12665. name: 'mx_gradient_scale3d_0',
  12666. type: 'float',
  12667. inputs: [
  12668. { name: 'v', type: 'float' }
  12669. ]
  12670. } );
  12671. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  12672. const v = vec3( v_immutable ).toVar();
  12673. return mul( 0.6616, v );
  12674. } ).setLayout( {
  12675. name: 'mx_gradient_scale2d_1',
  12676. type: 'vec3',
  12677. inputs: [
  12678. { name: 'v', type: 'vec3' }
  12679. ]
  12680. } );
  12681. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  12682. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  12683. const v = vec3( v_immutable ).toVar();
  12684. return mul( 0.9820, v );
  12685. } ).setLayout( {
  12686. name: 'mx_gradient_scale3d_1',
  12687. type: 'vec3',
  12688. inputs: [
  12689. { name: 'v', type: 'vec3' }
  12690. ]
  12691. } );
  12692. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  12693. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  12694. const k = int( k_immutable ).toVar();
  12695. const x = uint( x_immutable ).toVar();
  12696. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  12697. } ).setLayout( {
  12698. name: 'mx_rotl32',
  12699. type: 'uint',
  12700. inputs: [
  12701. { name: 'x', type: 'uint' },
  12702. { name: 'k', type: 'int' }
  12703. ]
  12704. } );
  12705. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  12706. a.subAssign( c );
  12707. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  12708. c.addAssign( b );
  12709. b.subAssign( a );
  12710. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  12711. a.addAssign( c );
  12712. c.subAssign( b );
  12713. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  12714. b.addAssign( a );
  12715. a.subAssign( c );
  12716. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  12717. c.addAssign( b );
  12718. b.subAssign( a );
  12719. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  12720. a.addAssign( c );
  12721. c.subAssign( b );
  12722. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  12723. b.addAssign( a );
  12724. } );
  12725. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  12726. const c = uint( c_immutable ).toVar();
  12727. const b = uint( b_immutable ).toVar();
  12728. const a = uint( a_immutable ).toVar();
  12729. c.bitXorAssign( b );
  12730. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  12731. a.bitXorAssign( c );
  12732. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  12733. b.bitXorAssign( a );
  12734. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  12735. c.bitXorAssign( b );
  12736. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  12737. a.bitXorAssign( c );
  12738. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  12739. b.bitXorAssign( a );
  12740. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  12741. c.bitXorAssign( b );
  12742. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  12743. return c;
  12744. } ).setLayout( {
  12745. name: 'mx_bjfinal',
  12746. type: 'uint',
  12747. inputs: [
  12748. { name: 'a', type: 'uint' },
  12749. { name: 'b', type: 'uint' },
  12750. { name: 'c', type: 'uint' }
  12751. ]
  12752. } );
  12753. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  12754. const bits = uint( bits_immutable ).toVar();
  12755. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  12756. } ).setLayout( {
  12757. name: 'mx_bits_to_01',
  12758. type: 'float',
  12759. inputs: [
  12760. { name: 'bits', type: 'uint' }
  12761. ]
  12762. } );
  12763. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  12764. const t = float( t_immutable ).toVar();
  12765. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  12766. } ).setLayout( {
  12767. name: 'mx_fade',
  12768. type: 'float',
  12769. inputs: [
  12770. { name: 't', type: 'float' }
  12771. ]
  12772. } );
  12773. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  12774. const x = int( x_immutable ).toVar();
  12775. const len = uint( uint( 1 ) ).toVar();
  12776. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  12777. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  12778. } ).setLayout( {
  12779. name: 'mx_hash_int_0',
  12780. type: 'uint',
  12781. inputs: [
  12782. { name: 'x', type: 'int' }
  12783. ]
  12784. } );
  12785. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  12786. const y = int( y_immutable ).toVar();
  12787. const x = int( x_immutable ).toVar();
  12788. const len = uint( uint( 2 ) ).toVar();
  12789. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  12790. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  12791. a.addAssign( uint( x ) );
  12792. b.addAssign( uint( y ) );
  12793. return mx_bjfinal( a, b, c );
  12794. } ).setLayout( {
  12795. name: 'mx_hash_int_1',
  12796. type: 'uint',
  12797. inputs: [
  12798. { name: 'x', type: 'int' },
  12799. { name: 'y', type: 'int' }
  12800. ]
  12801. } );
  12802. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  12803. const z = int( z_immutable ).toVar();
  12804. const y = int( y_immutable ).toVar();
  12805. const x = int( x_immutable ).toVar();
  12806. const len = uint( uint( 3 ) ).toVar();
  12807. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  12808. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  12809. a.addAssign( uint( x ) );
  12810. b.addAssign( uint( y ) );
  12811. c.addAssign( uint( z ) );
  12812. return mx_bjfinal( a, b, c );
  12813. } ).setLayout( {
  12814. name: 'mx_hash_int_2',
  12815. type: 'uint',
  12816. inputs: [
  12817. { name: 'x', type: 'int' },
  12818. { name: 'y', type: 'int' },
  12819. { name: 'z', type: 'int' }
  12820. ]
  12821. } );
  12822. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  12823. const xx = int( xx_immutable ).toVar();
  12824. const z = int( z_immutable ).toVar();
  12825. const y = int( y_immutable ).toVar();
  12826. const x = int( x_immutable ).toVar();
  12827. const len = uint( uint( 4 ) ).toVar();
  12828. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  12829. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  12830. a.addAssign( uint( x ) );
  12831. b.addAssign( uint( y ) );
  12832. c.addAssign( uint( z ) );
  12833. mx_bjmix( a, b, c );
  12834. a.addAssign( uint( xx ) );
  12835. return mx_bjfinal( a, b, c );
  12836. } ).setLayout( {
  12837. name: 'mx_hash_int_3',
  12838. type: 'uint',
  12839. inputs: [
  12840. { name: 'x', type: 'int' },
  12841. { name: 'y', type: 'int' },
  12842. { name: 'z', type: 'int' },
  12843. { name: 'xx', type: 'int' }
  12844. ]
  12845. } );
  12846. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  12847. const yy = int( yy_immutable ).toVar();
  12848. const xx = int( xx_immutable ).toVar();
  12849. const z = int( z_immutable ).toVar();
  12850. const y = int( y_immutable ).toVar();
  12851. const x = int( x_immutable ).toVar();
  12852. const len = uint( uint( 5 ) ).toVar();
  12853. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  12854. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  12855. a.addAssign( uint( x ) );
  12856. b.addAssign( uint( y ) );
  12857. c.addAssign( uint( z ) );
  12858. mx_bjmix( a, b, c );
  12859. a.addAssign( uint( xx ) );
  12860. b.addAssign( uint( yy ) );
  12861. return mx_bjfinal( a, b, c );
  12862. } ).setLayout( {
  12863. name: 'mx_hash_int_4',
  12864. type: 'uint',
  12865. inputs: [
  12866. { name: 'x', type: 'int' },
  12867. { name: 'y', type: 'int' },
  12868. { name: 'z', type: 'int' },
  12869. { name: 'xx', type: 'int' },
  12870. { name: 'yy', type: 'int' }
  12871. ]
  12872. } );
  12873. 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 ] );
  12874. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  12875. const y = int( y_immutable ).toVar();
  12876. const x = int( x_immutable ).toVar();
  12877. const h = uint( mx_hash_int( x, y ) ).toVar();
  12878. const result = uvec3().toVar();
  12879. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  12880. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  12881. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  12882. return result;
  12883. } ).setLayout( {
  12884. name: 'mx_hash_vec3_0',
  12885. type: 'uvec3',
  12886. inputs: [
  12887. { name: 'x', type: 'int' },
  12888. { name: 'y', type: 'int' }
  12889. ]
  12890. } );
  12891. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  12892. const z = int( z_immutable ).toVar();
  12893. const y = int( y_immutable ).toVar();
  12894. const x = int( x_immutable ).toVar();
  12895. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  12896. const result = uvec3().toVar();
  12897. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  12898. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  12899. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  12900. return result;
  12901. } ).setLayout( {
  12902. name: 'mx_hash_vec3_1',
  12903. type: 'uvec3',
  12904. inputs: [
  12905. { name: 'x', type: 'int' },
  12906. { name: 'y', type: 'int' },
  12907. { name: 'z', type: 'int' }
  12908. ]
  12909. } );
  12910. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  12911. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12912. const p = vec2( p_immutable ).toVar();
  12913. const X = int().toVar(), Y = int().toVar();
  12914. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  12915. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  12916. const u = float( mx_fade( fx ) ).toVar();
  12917. const v = float( mx_fade( fy ) ).toVar();
  12918. 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();
  12919. return mx_gradient_scale2d( result );
  12920. } ).setLayout( {
  12921. name: 'mx_perlin_noise_float_0',
  12922. type: 'float',
  12923. inputs: [
  12924. { name: 'p', type: 'vec2' }
  12925. ]
  12926. } );
  12927. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12928. const p = vec3( p_immutable ).toVar();
  12929. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  12930. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  12931. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  12932. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  12933. const u = float( mx_fade( fx ) ).toVar();
  12934. const v = float( mx_fade( fy ) ).toVar();
  12935. const w = float( mx_fade( fz ) ).toVar();
  12936. 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();
  12937. return mx_gradient_scale3d( result );
  12938. } ).setLayout( {
  12939. name: 'mx_perlin_noise_float_1',
  12940. type: 'float',
  12941. inputs: [
  12942. { name: 'p', type: 'vec3' }
  12943. ]
  12944. } );
  12945. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  12946. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12947. const p = vec2( p_immutable ).toVar();
  12948. const X = int().toVar(), Y = int().toVar();
  12949. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  12950. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  12951. const u = float( mx_fade( fx ) ).toVar();
  12952. const v = float( mx_fade( fy ) ).toVar();
  12953. 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();
  12954. return mx_gradient_scale2d( result );
  12955. } ).setLayout( {
  12956. name: 'mx_perlin_noise_vec3_0',
  12957. type: 'vec3',
  12958. inputs: [
  12959. { name: 'p', type: 'vec2' }
  12960. ]
  12961. } );
  12962. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12963. const p = vec3( p_immutable ).toVar();
  12964. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  12965. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  12966. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  12967. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  12968. const u = float( mx_fade( fx ) ).toVar();
  12969. const v = float( mx_fade( fy ) ).toVar();
  12970. const w = float( mx_fade( fz ) ).toVar();
  12971. 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();
  12972. return mx_gradient_scale3d( result );
  12973. } ).setLayout( {
  12974. name: 'mx_perlin_noise_vec3_1',
  12975. type: 'vec3',
  12976. inputs: [
  12977. { name: 'p', type: 'vec3' }
  12978. ]
  12979. } );
  12980. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  12981. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12982. const p = float( p_immutable ).toVar();
  12983. const ix = int( mx_floor( p ) ).toVar();
  12984. return mx_bits_to_01( mx_hash_int( ix ) );
  12985. } ).setLayout( {
  12986. name: 'mx_cell_noise_float_0',
  12987. type: 'float',
  12988. inputs: [
  12989. { name: 'p', type: 'float' }
  12990. ]
  12991. } );
  12992. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12993. const p = vec2( p_immutable ).toVar();
  12994. const ix = int( mx_floor( p.x ) ).toVar();
  12995. const iy = int( mx_floor( p.y ) ).toVar();
  12996. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  12997. } ).setLayout( {
  12998. name: 'mx_cell_noise_float_1',
  12999. type: 'float',
  13000. inputs: [
  13001. { name: 'p', type: 'vec2' }
  13002. ]
  13003. } );
  13004. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13005. const p = vec3( p_immutable ).toVar();
  13006. const ix = int( mx_floor( p.x ) ).toVar();
  13007. const iy = int( mx_floor( p.y ) ).toVar();
  13008. const iz = int( mx_floor( p.z ) ).toVar();
  13009. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  13010. } ).setLayout( {
  13011. name: 'mx_cell_noise_float_2',
  13012. type: 'float',
  13013. inputs: [
  13014. { name: 'p', type: 'vec3' }
  13015. ]
  13016. } );
  13017. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13018. const p = vec4( p_immutable ).toVar();
  13019. const ix = int( mx_floor( p.x ) ).toVar();
  13020. const iy = int( mx_floor( p.y ) ).toVar();
  13021. const iz = int( mx_floor( p.z ) ).toVar();
  13022. const iw = int( mx_floor( p.w ) ).toVar();
  13023. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  13024. } ).setLayout( {
  13025. name: 'mx_cell_noise_float_3',
  13026. type: 'float',
  13027. inputs: [
  13028. { name: 'p', type: 'vec4' }
  13029. ]
  13030. } );
  13031. 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 ] );
  13032. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13033. const p = float( p_immutable ).toVar();
  13034. const ix = int( mx_floor( p ) ).toVar();
  13035. 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 ) ) ) );
  13036. } ).setLayout( {
  13037. name: 'mx_cell_noise_vec3_0',
  13038. type: 'vec3',
  13039. inputs: [
  13040. { name: 'p', type: 'float' }
  13041. ]
  13042. } );
  13043. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13044. const p = vec2( p_immutable ).toVar();
  13045. const ix = int( mx_floor( p.x ) ).toVar();
  13046. const iy = int( mx_floor( p.y ) ).toVar();
  13047. 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 ) ) ) );
  13048. } ).setLayout( {
  13049. name: 'mx_cell_noise_vec3_1',
  13050. type: 'vec3',
  13051. inputs: [
  13052. { name: 'p', type: 'vec2' }
  13053. ]
  13054. } );
  13055. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13056. const p = vec3( p_immutable ).toVar();
  13057. const ix = int( mx_floor( p.x ) ).toVar();
  13058. const iy = int( mx_floor( p.y ) ).toVar();
  13059. const iz = int( mx_floor( p.z ) ).toVar();
  13060. 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 ) ) ) );
  13061. } ).setLayout( {
  13062. name: 'mx_cell_noise_vec3_2',
  13063. type: 'vec3',
  13064. inputs: [
  13065. { name: 'p', type: 'vec3' }
  13066. ]
  13067. } );
  13068. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13069. const p = vec4( p_immutable ).toVar();
  13070. const ix = int( mx_floor( p.x ) ).toVar();
  13071. const iy = int( mx_floor( p.y ) ).toVar();
  13072. const iz = int( mx_floor( p.z ) ).toVar();
  13073. const iw = int( mx_floor( p.w ) ).toVar();
  13074. 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 ) ) ) );
  13075. } ).setLayout( {
  13076. name: 'mx_cell_noise_vec3_3',
  13077. type: 'vec3',
  13078. inputs: [
  13079. { name: 'p', type: 'vec4' }
  13080. ]
  13081. } );
  13082. 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 ] );
  13083. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  13084. const diminish = float( diminish_immutable ).toVar();
  13085. const lacunarity = float( lacunarity_immutable ).toVar();
  13086. const octaves = int( octaves_immutable ).toVar();
  13087. const p = vec3( p_immutable ).toVar();
  13088. const result = float( 0.0 ).toVar();
  13089. const amplitude = float( 1.0 ).toVar();
  13090. Loop( octaves, () => {
  13091. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  13092. amplitude.mulAssign( diminish );
  13093. p.mulAssign( lacunarity );
  13094. } );
  13095. return result;
  13096. } ).setLayout( {
  13097. name: 'mx_fractal_noise_float',
  13098. type: 'float',
  13099. inputs: [
  13100. { name: 'p', type: 'vec3' },
  13101. { name: 'octaves', type: 'int' },
  13102. { name: 'lacunarity', type: 'float' },
  13103. { name: 'diminish', type: 'float' }
  13104. ]
  13105. } );
  13106. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  13107. const diminish = float( diminish_immutable ).toVar();
  13108. const lacunarity = float( lacunarity_immutable ).toVar();
  13109. const octaves = int( octaves_immutable ).toVar();
  13110. const p = vec3( p_immutable ).toVar();
  13111. const result = vec3( 0.0 ).toVar();
  13112. const amplitude = float( 1.0 ).toVar();
  13113. Loop( octaves, () => {
  13114. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  13115. amplitude.mulAssign( diminish );
  13116. p.mulAssign( lacunarity );
  13117. } );
  13118. return result;
  13119. } ).setLayout( {
  13120. name: 'mx_fractal_noise_vec3',
  13121. type: 'vec3',
  13122. inputs: [
  13123. { name: 'p', type: 'vec3' },
  13124. { name: 'octaves', type: 'int' },
  13125. { name: 'lacunarity', type: 'float' },
  13126. { name: 'diminish', type: 'float' }
  13127. ]
  13128. } );
  13129. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  13130. const diminish = float( diminish_immutable ).toVar();
  13131. const lacunarity = float( lacunarity_immutable ).toVar();
  13132. const octaves = int( octaves_immutable ).toVar();
  13133. const p = vec3( p_immutable ).toVar();
  13134. 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 ) );
  13135. } ).setLayout( {
  13136. name: 'mx_fractal_noise_vec2',
  13137. type: 'vec2',
  13138. inputs: [
  13139. { name: 'p', type: 'vec3' },
  13140. { name: 'octaves', type: 'int' },
  13141. { name: 'lacunarity', type: 'float' },
  13142. { name: 'diminish', type: 'float' }
  13143. ]
  13144. } );
  13145. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  13146. const diminish = float( diminish_immutable ).toVar();
  13147. const lacunarity = float( lacunarity_immutable ).toVar();
  13148. const octaves = int( octaves_immutable ).toVar();
  13149. const p = vec3( p_immutable ).toVar();
  13150. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  13151. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  13152. return vec4( c, f );
  13153. } ).setLayout( {
  13154. name: 'mx_fractal_noise_vec4',
  13155. type: 'vec4',
  13156. inputs: [
  13157. { name: 'p', type: 'vec3' },
  13158. { name: 'octaves', type: 'int' },
  13159. { name: 'lacunarity', type: 'float' },
  13160. { name: 'diminish', type: 'float' }
  13161. ]
  13162. } );
  13163. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  13164. const metric = int( metric_immutable ).toVar();
  13165. const jitter = float( jitter_immutable ).toVar();
  13166. const yoff = int( yoff_immutable ).toVar();
  13167. const xoff = int( xoff_immutable ).toVar();
  13168. const y = int( y_immutable ).toVar();
  13169. const x = int( x_immutable ).toVar();
  13170. const p = vec2( p_immutable ).toVar();
  13171. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  13172. const off = vec2( tmp.x, tmp.y ).toVar();
  13173. off.subAssign( 0.5 );
  13174. off.mulAssign( jitter );
  13175. off.addAssign( 0.5 );
  13176. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  13177. const diff = vec2( cellpos.sub( p ) ).toVar();
  13178. If( metric.equal( int( 2 ) ), () => {
  13179. return abs( diff.x ).add( abs( diff.y ) );
  13180. } );
  13181. If( metric.equal( int( 3 ) ), () => {
  13182. return max$1( abs( diff.x ), abs( diff.y ) );
  13183. } );
  13184. return dot( diff, diff );
  13185. } ).setLayout( {
  13186. name: 'mx_worley_distance_0',
  13187. type: 'float',
  13188. inputs: [
  13189. { name: 'p', type: 'vec2' },
  13190. { name: 'x', type: 'int' },
  13191. { name: 'y', type: 'int' },
  13192. { name: 'xoff', type: 'int' },
  13193. { name: 'yoff', type: 'int' },
  13194. { name: 'jitter', type: 'float' },
  13195. { name: 'metric', type: 'int' }
  13196. ]
  13197. } );
  13198. 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 ] ) => {
  13199. const metric = int( metric_immutable ).toVar();
  13200. const jitter = float( jitter_immutable ).toVar();
  13201. const zoff = int( zoff_immutable ).toVar();
  13202. const yoff = int( yoff_immutable ).toVar();
  13203. const xoff = int( xoff_immutable ).toVar();
  13204. const z = int( z_immutable ).toVar();
  13205. const y = int( y_immutable ).toVar();
  13206. const x = int( x_immutable ).toVar();
  13207. const p = vec3( p_immutable ).toVar();
  13208. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  13209. off.subAssign( 0.5 );
  13210. off.mulAssign( jitter );
  13211. off.addAssign( 0.5 );
  13212. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  13213. const diff = vec3( cellpos.sub( p ) ).toVar();
  13214. If( metric.equal( int( 2 ) ), () => {
  13215. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  13216. } );
  13217. If( metric.equal( int( 3 ) ), () => {
  13218. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  13219. } );
  13220. return dot( diff, diff );
  13221. } ).setLayout( {
  13222. name: 'mx_worley_distance_1',
  13223. type: 'float',
  13224. inputs: [
  13225. { name: 'p', type: 'vec3' },
  13226. { name: 'x', type: 'int' },
  13227. { name: 'y', type: 'int' },
  13228. { name: 'z', type: 'int' },
  13229. { name: 'xoff', type: 'int' },
  13230. { name: 'yoff', type: 'int' },
  13231. { name: 'zoff', type: 'int' },
  13232. { name: 'jitter', type: 'float' },
  13233. { name: 'metric', type: 'int' }
  13234. ]
  13235. } );
  13236. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  13237. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13238. const metric = int( metric_immutable ).toVar();
  13239. const jitter = float( jitter_immutable ).toVar();
  13240. const p = vec2( p_immutable ).toVar();
  13241. const X = int().toVar(), Y = int().toVar();
  13242. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  13243. const sqdist = float( 1e6 ).toVar();
  13244. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13245. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13246. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  13247. sqdist.assign( min$1( sqdist, dist ) );
  13248. } );
  13249. } );
  13250. If( metric.equal( int( 0 ) ), () => {
  13251. sqdist.assign( sqrt( sqdist ) );
  13252. } );
  13253. return sqdist;
  13254. } ).setLayout( {
  13255. name: 'mx_worley_noise_float_0',
  13256. type: 'float',
  13257. inputs: [
  13258. { name: 'p', type: 'vec2' },
  13259. { name: 'jitter', type: 'float' },
  13260. { name: 'metric', type: 'int' }
  13261. ]
  13262. } );
  13263. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13264. const metric = int( metric_immutable ).toVar();
  13265. const jitter = float( jitter_immutable ).toVar();
  13266. const p = vec2( p_immutable ).toVar();
  13267. const X = int().toVar(), Y = int().toVar();
  13268. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  13269. const sqdist = vec2( 1e6, 1e6 ).toVar();
  13270. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13271. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13272. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  13273. If( dist.lessThan( sqdist.x ), () => {
  13274. sqdist.y.assign( sqdist.x );
  13275. sqdist.x.assign( dist );
  13276. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  13277. sqdist.y.assign( dist );
  13278. } );
  13279. } );
  13280. } );
  13281. If( metric.equal( int( 0 ) ), () => {
  13282. sqdist.assign( sqrt( sqdist ) );
  13283. } );
  13284. return sqdist;
  13285. } ).setLayout( {
  13286. name: 'mx_worley_noise_vec2_0',
  13287. type: 'vec2',
  13288. inputs: [
  13289. { name: 'p', type: 'vec2' },
  13290. { name: 'jitter', type: 'float' },
  13291. { name: 'metric', type: 'int' }
  13292. ]
  13293. } );
  13294. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13295. const metric = int( metric_immutable ).toVar();
  13296. const jitter = float( jitter_immutable ).toVar();
  13297. const p = vec2( p_immutable ).toVar();
  13298. const X = int().toVar(), Y = int().toVar();
  13299. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  13300. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  13301. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13302. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13303. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  13304. If( dist.lessThan( sqdist.x ), () => {
  13305. sqdist.z.assign( sqdist.y );
  13306. sqdist.y.assign( sqdist.x );
  13307. sqdist.x.assign( dist );
  13308. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  13309. sqdist.z.assign( sqdist.y );
  13310. sqdist.y.assign( dist );
  13311. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  13312. sqdist.z.assign( dist );
  13313. } );
  13314. } );
  13315. } );
  13316. If( metric.equal( int( 0 ) ), () => {
  13317. sqdist.assign( sqrt( sqdist ) );
  13318. } );
  13319. return sqdist;
  13320. } ).setLayout( {
  13321. name: 'mx_worley_noise_vec3_0',
  13322. type: 'vec3',
  13323. inputs: [
  13324. { name: 'p', type: 'vec2' },
  13325. { name: 'jitter', type: 'float' },
  13326. { name: 'metric', type: 'int' }
  13327. ]
  13328. } );
  13329. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13330. const metric = int( metric_immutable ).toVar();
  13331. const jitter = float( jitter_immutable ).toVar();
  13332. const p = vec3( p_immutable ).toVar();
  13333. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  13334. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  13335. const sqdist = float( 1e6 ).toVar();
  13336. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13337. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13338. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  13339. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  13340. sqdist.assign( min$1( sqdist, dist ) );
  13341. } );
  13342. } );
  13343. } );
  13344. If( metric.equal( int( 0 ) ), () => {
  13345. sqdist.assign( sqrt( sqdist ) );
  13346. } );
  13347. return sqdist;
  13348. } ).setLayout( {
  13349. name: 'mx_worley_noise_float_1',
  13350. type: 'float',
  13351. inputs: [
  13352. { name: 'p', type: 'vec3' },
  13353. { name: 'jitter', type: 'float' },
  13354. { name: 'metric', type: 'int' }
  13355. ]
  13356. } );
  13357. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  13358. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13359. const metric = int( metric_immutable ).toVar();
  13360. const jitter = float( jitter_immutable ).toVar();
  13361. const p = vec3( p_immutable ).toVar();
  13362. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  13363. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  13364. const sqdist = vec2( 1e6, 1e6 ).toVar();
  13365. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13366. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13367. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  13368. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  13369. If( dist.lessThan( sqdist.x ), () => {
  13370. sqdist.y.assign( sqdist.x );
  13371. sqdist.x.assign( dist );
  13372. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  13373. sqdist.y.assign( dist );
  13374. } );
  13375. } );
  13376. } );
  13377. } );
  13378. If( metric.equal( int( 0 ) ), () => {
  13379. sqdist.assign( sqrt( sqdist ) );
  13380. } );
  13381. return sqdist;
  13382. } ).setLayout( {
  13383. name: 'mx_worley_noise_vec2_1',
  13384. type: 'vec2',
  13385. inputs: [
  13386. { name: 'p', type: 'vec3' },
  13387. { name: 'jitter', type: 'float' },
  13388. { name: 'metric', type: 'int' }
  13389. ]
  13390. } );
  13391. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  13392. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13393. const metric = int( metric_immutable ).toVar();
  13394. const jitter = float( jitter_immutable ).toVar();
  13395. const p = vec3( p_immutable ).toVar();
  13396. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  13397. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  13398. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  13399. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13400. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13401. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  13402. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  13403. If( dist.lessThan( sqdist.x ), () => {
  13404. sqdist.z.assign( sqdist.y );
  13405. sqdist.y.assign( sqdist.x );
  13406. sqdist.x.assign( dist );
  13407. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  13408. sqdist.z.assign( sqdist.y );
  13409. sqdist.y.assign( dist );
  13410. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  13411. sqdist.z.assign( dist );
  13412. } );
  13413. } );
  13414. } );
  13415. } );
  13416. If( metric.equal( int( 0 ) ), () => {
  13417. sqdist.assign( sqrt( sqdist ) );
  13418. } );
  13419. return sqdist;
  13420. } ).setLayout( {
  13421. name: 'mx_worley_noise_vec3_1',
  13422. type: 'vec3',
  13423. inputs: [
  13424. { name: 'p', type: 'vec3' },
  13425. { name: 'jitter', type: 'float' },
  13426. { name: 'metric', type: 'int' }
  13427. ]
  13428. } );
  13429. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  13430. // Three.js Transpiler
  13431. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  13432. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  13433. const s = hsv.y;
  13434. const v = hsv.z;
  13435. const result = vec3().toVar();
  13436. If( s.lessThan( 0.0001 ), () => {
  13437. result.assign( vec3( v, v, v ) );
  13438. } ).Else( () => {
  13439. let h = hsv.x;
  13440. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  13441. const hi = int( trunc( h ) );
  13442. const f = h.sub( float( hi ) );
  13443. const p = v.mul( s.oneMinus() );
  13444. const q = v.mul( s.mul( f ).oneMinus() );
  13445. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  13446. If( hi.equal( int( 0 ) ), () => {
  13447. result.assign( vec3( v, t, p ) );
  13448. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  13449. result.assign( vec3( q, v, p ) );
  13450. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  13451. result.assign( vec3( p, v, t ) );
  13452. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  13453. result.assign( vec3( p, q, v ) );
  13454. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  13455. result.assign( vec3( t, p, v ) );
  13456. } ).Else( () => {
  13457. result.assign( vec3( v, p, q ) );
  13458. } );
  13459. } );
  13460. return result;
  13461. } ).setLayout( {
  13462. name: 'mx_hsvtorgb',
  13463. type: 'vec3',
  13464. inputs: [
  13465. { name: 'hsv', type: 'vec3' }
  13466. ]
  13467. } );
  13468. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  13469. const c = vec3( c_immutable ).toVar();
  13470. const r = float( c.x ).toVar();
  13471. const g = float( c.y ).toVar();
  13472. const b = float( c.z ).toVar();
  13473. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  13474. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  13475. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  13476. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  13477. v.assign( maxcomp );
  13478. If( maxcomp.greaterThan( 0.0 ), () => {
  13479. s.assign( delta.div( maxcomp ) );
  13480. } ).Else( () => {
  13481. s.assign( 0.0 );
  13482. } );
  13483. If( s.lessThanEqual( 0.0 ), () => {
  13484. h.assign( 0.0 );
  13485. } ).Else( () => {
  13486. If( r.greaterThanEqual( maxcomp ), () => {
  13487. h.assign( g.sub( b ).div( delta ) );
  13488. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  13489. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  13490. } ).Else( () => {
  13491. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  13492. } );
  13493. h.mulAssign( 1.0 / 6.0 );
  13494. If( h.lessThan( 0.0 ), () => {
  13495. h.addAssign( 1.0 );
  13496. } );
  13497. } );
  13498. return vec3( h, s, v );
  13499. } ).setLayout( {
  13500. name: 'mx_rgbtohsv',
  13501. type: 'vec3',
  13502. inputs: [
  13503. { name: 'c', type: 'vec3' }
  13504. ]
  13505. } );
  13506. // Three.js Transpiler
  13507. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  13508. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  13509. const color = vec3( color_immutable ).toVar();
  13510. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  13511. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  13512. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  13513. return mix( linSeg, powSeg, isAbove );
  13514. } ).setLayout( {
  13515. name: 'mx_srgb_texture_to_lin_rec709',
  13516. type: 'vec3',
  13517. inputs: [
  13518. { name: 'color', type: 'vec3' }
  13519. ]
  13520. } );
  13521. const mx_aastep = ( threshold, value ) => {
  13522. threshold = float( threshold );
  13523. value = float( value );
  13524. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  13525. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  13526. };
  13527. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  13528. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  13529. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  13530. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  13531. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  13532. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  13533. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  13534. const mx_safepower = ( in1, in2 = 1 ) => {
  13535. in1 = float( in1 );
  13536. return in1.abs().pow( in2 ).mul( in1.sign() );
  13537. };
  13538. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  13539. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  13540. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  13541. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  13542. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  13543. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  13544. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  13545. return noise_vec4.mul( amplitude ).add( pivot );
  13546. };
  13547. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  13548. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  13549. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  13550. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  13551. 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 );
  13552. 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 );
  13553. 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 );
  13554. 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 );
  13555. // https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html
  13556. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  13557. const nDir = normalize( normal ).toVar( 'nDir' );
  13558. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmax' );
  13559. const rbmin = sub( float( - 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmin' );
  13560. const rbminmax = vec3().toVar( 'rbminmax' );
  13561. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  13562. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  13563. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  13564. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar( 'correction' );
  13565. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar( 'boxIntersection' );
  13566. return boxIntersection.sub( cubePos );
  13567. } );
  13568. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  13569. // normal is assumed to have unit length
  13570. const x = normal.x, y = normal.y, z = normal.z;
  13571. // band 0
  13572. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  13573. // band 1
  13574. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  13575. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  13576. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  13577. // band 2
  13578. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  13579. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  13580. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  13581. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  13582. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  13583. return result;
  13584. } );
  13585. // constants
  13586. var TSL = /*#__PURE__*/Object.freeze({
  13587. __proto__: null,
  13588. BRDF_GGX: BRDF_GGX,
  13589. BRDF_Lambert: BRDF_Lambert,
  13590. BasicShadowFilter: BasicShadowFilter,
  13591. Break: Break,
  13592. Continue: Continue,
  13593. DFGApprox: DFGApprox,
  13594. D_GGX: D_GGX,
  13595. Discard: Discard,
  13596. EPSILON: EPSILON,
  13597. F_Schlick: F_Schlick,
  13598. Fn: Fn,
  13599. INFINITY: INFINITY,
  13600. If: If,
  13601. Loop: Loop,
  13602. NodeAccess: NodeAccess,
  13603. NodeShaderStage: NodeShaderStage,
  13604. NodeType: NodeType,
  13605. NodeUpdateType: NodeUpdateType,
  13606. PCFShadowFilter: PCFShadowFilter,
  13607. PCFSoftShadowFilter: PCFSoftShadowFilter,
  13608. PI: PI,
  13609. PI2: PI2,
  13610. Return: Return,
  13611. Schlick_to_F0: Schlick_to_F0,
  13612. ScriptableNodeResources: ScriptableNodeResources,
  13613. ShaderNode: ShaderNode,
  13614. TBNViewMatrix: TBNViewMatrix,
  13615. VSMShadowFilter: VSMShadowFilter,
  13616. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  13617. abs: abs,
  13618. acesFilmicToneMapping: acesFilmicToneMapping,
  13619. acos: acos,
  13620. add: add,
  13621. addMethodChaining: addMethodChaining,
  13622. addNodeElement: addNodeElement,
  13623. agxToneMapping: agxToneMapping,
  13624. all: all,
  13625. alphaT: alphaT,
  13626. and: and,
  13627. anisotropy: anisotropy,
  13628. anisotropyB: anisotropyB,
  13629. anisotropyT: anisotropyT,
  13630. any: any,
  13631. append: append,
  13632. arrayBuffer: arrayBuffer,
  13633. asin: asin,
  13634. assign: assign,
  13635. atan: atan,
  13636. atan2: atan2,
  13637. atomicAdd: atomicAdd,
  13638. atomicAnd: atomicAnd,
  13639. atomicFunc: atomicFunc,
  13640. atomicMax: atomicMax,
  13641. atomicMin: atomicMin,
  13642. atomicOr: atomicOr,
  13643. atomicStore: atomicStore,
  13644. atomicSub: atomicSub,
  13645. atomicXor: atomicXor,
  13646. attenuationColor: attenuationColor,
  13647. attenuationDistance: attenuationDistance,
  13648. attribute: attribute,
  13649. attributeArray: attributeArray,
  13650. backgroundBlurriness: backgroundBlurriness,
  13651. backgroundIntensity: backgroundIntensity,
  13652. backgroundRotation: backgroundRotation,
  13653. batch: batch,
  13654. billboarding: billboarding,
  13655. bitAnd: bitAnd,
  13656. bitNot: bitNot,
  13657. bitOr: bitOr,
  13658. bitXor: bitXor,
  13659. bitangentGeometry: bitangentGeometry,
  13660. bitangentLocal: bitangentLocal,
  13661. bitangentView: bitangentView,
  13662. bitangentWorld: bitangentWorld,
  13663. bitcast: bitcast,
  13664. blendBurn: blendBurn,
  13665. blendColor: blendColor,
  13666. blendDodge: blendDodge,
  13667. blendOverlay: blendOverlay,
  13668. blendScreen: blendScreen,
  13669. blur: blur,
  13670. bool: bool,
  13671. buffer: buffer,
  13672. bufferAttribute: bufferAttribute,
  13673. bumpMap: bumpMap,
  13674. burn: burn,
  13675. bvec2: bvec2,
  13676. bvec3: bvec3,
  13677. bvec4: bvec4,
  13678. bypass: bypass,
  13679. cache: cache,
  13680. call: call,
  13681. cameraFar: cameraFar,
  13682. cameraNear: cameraNear,
  13683. cameraNormalMatrix: cameraNormalMatrix,
  13684. cameraPosition: cameraPosition,
  13685. cameraProjectionMatrix: cameraProjectionMatrix,
  13686. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  13687. cameraViewMatrix: cameraViewMatrix,
  13688. cameraWorldMatrix: cameraWorldMatrix,
  13689. cbrt: cbrt,
  13690. cdl: cdl,
  13691. ceil: ceil,
  13692. checker: checker,
  13693. cineonToneMapping: cineonToneMapping,
  13694. clamp: clamp,
  13695. clearcoat: clearcoat,
  13696. clearcoatRoughness: clearcoatRoughness,
  13697. code: code,
  13698. color: color,
  13699. colorSpaceToWorking: colorSpaceToWorking,
  13700. colorToDirection: colorToDirection,
  13701. compute: compute,
  13702. cond: cond,
  13703. context: context,
  13704. convert: convert,
  13705. convertColorSpace: convertColorSpace,
  13706. convertToTexture: convertToTexture,
  13707. cos: cos,
  13708. cross: cross,
  13709. cubeTexture: cubeTexture,
  13710. dFdx: dFdx,
  13711. dFdy: dFdy,
  13712. dashSize: dashSize,
  13713. defaultBuildStages: defaultBuildStages,
  13714. defaultShaderStages: defaultShaderStages,
  13715. defined: defined,
  13716. degrees: degrees,
  13717. deltaTime: deltaTime,
  13718. densityFog: densityFog,
  13719. depth: depth,
  13720. depthPass: depthPass,
  13721. difference: difference,
  13722. diffuseColor: diffuseColor,
  13723. directPointLight: directPointLight,
  13724. directionToColor: directionToColor,
  13725. dispersion: dispersion,
  13726. distance: distance,
  13727. div: div,
  13728. dodge: dodge,
  13729. dot: dot,
  13730. drawIndex: drawIndex,
  13731. dynamicBufferAttribute: dynamicBufferAttribute,
  13732. element: element,
  13733. emissive: emissive,
  13734. equal: equal,
  13735. equals: equals,
  13736. equirectUV: equirectUV,
  13737. exp: exp,
  13738. exp2: exp2,
  13739. expression: expression,
  13740. faceDirection: faceDirection,
  13741. faceForward: faceForward,
  13742. float: float,
  13743. floor: floor,
  13744. fog: fog,
  13745. fract: fract,
  13746. frameGroup: frameGroup,
  13747. frameId: frameId,
  13748. frontFacing: frontFacing,
  13749. fwidth: fwidth,
  13750. gain: gain,
  13751. gapSize: gapSize,
  13752. getConstNodeType: getConstNodeType,
  13753. getCurrentStack: getCurrentStack,
  13754. getDirection: getDirection,
  13755. getDistanceAttenuation: getDistanceAttenuation,
  13756. getGeometryRoughness: getGeometryRoughness,
  13757. getNormalFromDepth: getNormalFromDepth,
  13758. getParallaxCorrectNormal: getParallaxCorrectNormal,
  13759. getRoughness: getRoughness,
  13760. getScreenPosition: getScreenPosition,
  13761. getShIrradianceAt: getShIrradianceAt,
  13762. getTextureIndex: getTextureIndex,
  13763. getViewPosition: getViewPosition,
  13764. glsl: glsl,
  13765. glslFn: glslFn,
  13766. grayscale: grayscale,
  13767. greaterThan: greaterThan,
  13768. greaterThanEqual: greaterThanEqual,
  13769. hash: hash,
  13770. highPrecisionModelNormalViewMatrix: highPrecisionModelNormalViewMatrix,
  13771. highPrecisionModelViewMatrix: highPrecisionModelViewMatrix,
  13772. hue: hue,
  13773. instance: instance,
  13774. instanceIndex: instanceIndex,
  13775. instancedArray: instancedArray,
  13776. instancedBufferAttribute: instancedBufferAttribute,
  13777. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  13778. instancedMesh: instancedMesh,
  13779. int: int,
  13780. inverseSqrt: inverseSqrt,
  13781. invocationLocalIndex: invocationLocalIndex,
  13782. invocationSubgroupIndex: invocationSubgroupIndex,
  13783. ior: ior,
  13784. iridescence: iridescence,
  13785. iridescenceIOR: iridescenceIOR,
  13786. iridescenceThickness: iridescenceThickness,
  13787. ivec2: ivec2,
  13788. ivec3: ivec3,
  13789. ivec4: ivec4,
  13790. js: js,
  13791. label: label,
  13792. length: length,
  13793. lengthSq: lengthSq,
  13794. lessThan: lessThan,
  13795. lessThanEqual: lessThanEqual,
  13796. lightPosition: lightPosition,
  13797. lightProjectionUV: lightProjectionUV,
  13798. lightShadowMatrix: lightShadowMatrix,
  13799. lightTargetDirection: lightTargetDirection,
  13800. lightTargetPosition: lightTargetPosition,
  13801. lightViewPosition: lightViewPosition,
  13802. lightingContext: lightingContext,
  13803. lights: lights,
  13804. linearDepth: linearDepth,
  13805. linearToneMapping: linearToneMapping,
  13806. localId: localId,
  13807. log: log,
  13808. log2: log2,
  13809. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  13810. loop: loop,
  13811. luminance: luminance,
  13812. mat2: mat2,
  13813. mat3: mat3,
  13814. mat4: mat4,
  13815. matcapUV: matcapUV,
  13816. materialAOMap: materialAOMap,
  13817. materialAlphaTest: materialAlphaTest,
  13818. materialAnisotropy: materialAnisotropy,
  13819. materialAnisotropyVector: materialAnisotropyVector,
  13820. materialAttenuationColor: materialAttenuationColor,
  13821. materialAttenuationDistance: materialAttenuationDistance,
  13822. materialClearcoat: materialClearcoat,
  13823. materialClearcoatNormal: materialClearcoatNormal,
  13824. materialClearcoatRoughness: materialClearcoatRoughness,
  13825. materialColor: materialColor,
  13826. materialDispersion: materialDispersion,
  13827. materialEmissive: materialEmissive,
  13828. materialIOR: materialIOR,
  13829. materialIridescence: materialIridescence,
  13830. materialIridescenceIOR: materialIridescenceIOR,
  13831. materialIridescenceThickness: materialIridescenceThickness,
  13832. materialLightMap: materialLightMap,
  13833. materialLineDashOffset: materialLineDashOffset,
  13834. materialLineDashSize: materialLineDashSize,
  13835. materialLineGapSize: materialLineGapSize,
  13836. materialLineScale: materialLineScale,
  13837. materialLineWidth: materialLineWidth,
  13838. materialMetalness: materialMetalness,
  13839. materialNormal: materialNormal,
  13840. materialOpacity: materialOpacity,
  13841. materialPointWidth: materialPointWidth,
  13842. materialReference: materialReference,
  13843. materialReflectivity: materialReflectivity,
  13844. materialRefractionRatio: materialRefractionRatio,
  13845. materialRotation: materialRotation,
  13846. materialRoughness: materialRoughness,
  13847. materialSheen: materialSheen,
  13848. materialSheenRoughness: materialSheenRoughness,
  13849. materialShininess: materialShininess,
  13850. materialSpecular: materialSpecular,
  13851. materialSpecularColor: materialSpecularColor,
  13852. materialSpecularIntensity: materialSpecularIntensity,
  13853. materialSpecularStrength: materialSpecularStrength,
  13854. materialThickness: materialThickness,
  13855. materialTransmission: materialTransmission,
  13856. max: max$1,
  13857. maxMipLevel: maxMipLevel,
  13858. metalness: metalness,
  13859. min: min$1,
  13860. mix: mix,
  13861. mixElement: mixElement,
  13862. mod: mod,
  13863. modInt: modInt,
  13864. modelDirection: modelDirection,
  13865. modelNormalMatrix: modelNormalMatrix,
  13866. modelPosition: modelPosition,
  13867. modelScale: modelScale,
  13868. modelViewMatrix: modelViewMatrix,
  13869. modelViewPosition: modelViewPosition,
  13870. modelViewProjection: modelViewProjection,
  13871. modelWorldMatrix: modelWorldMatrix,
  13872. modelWorldMatrixInverse: modelWorldMatrixInverse,
  13873. morphReference: morphReference,
  13874. mrt: mrt,
  13875. mul: mul,
  13876. mx_aastep: mx_aastep,
  13877. mx_cell_noise_float: mx_cell_noise_float,
  13878. mx_contrast: mx_contrast,
  13879. mx_fractal_noise_float: mx_fractal_noise_float,
  13880. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  13881. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  13882. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  13883. mx_hsvtorgb: mx_hsvtorgb,
  13884. mx_noise_float: mx_noise_float,
  13885. mx_noise_vec3: mx_noise_vec3,
  13886. mx_noise_vec4: mx_noise_vec4,
  13887. mx_ramplr: mx_ramplr,
  13888. mx_ramptb: mx_ramptb,
  13889. mx_rgbtohsv: mx_rgbtohsv,
  13890. mx_safepower: mx_safepower,
  13891. mx_splitlr: mx_splitlr,
  13892. mx_splittb: mx_splittb,
  13893. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  13894. mx_transform_uv: mx_transform_uv,
  13895. mx_worley_noise_float: mx_worley_noise_float,
  13896. mx_worley_noise_vec2: mx_worley_noise_vec2,
  13897. mx_worley_noise_vec3: mx_worley_noise_vec3,
  13898. negate: negate,
  13899. neutralToneMapping: neutralToneMapping,
  13900. nodeArray: nodeArray,
  13901. nodeImmutable: nodeImmutable,
  13902. nodeObject: nodeObject,
  13903. nodeObjects: nodeObjects,
  13904. nodeProxy: nodeProxy,
  13905. normalFlat: normalFlat,
  13906. normalGeometry: normalGeometry,
  13907. normalLocal: normalLocal,
  13908. normalMap: normalMap,
  13909. normalView: normalView,
  13910. normalWorld: normalWorld,
  13911. normalize: normalize,
  13912. not: not,
  13913. notEqual: notEqual,
  13914. numWorkgroups: numWorkgroups,
  13915. objectDirection: objectDirection,
  13916. objectGroup: objectGroup,
  13917. objectPosition: objectPosition,
  13918. objectScale: objectScale,
  13919. objectViewPosition: objectViewPosition,
  13920. objectWorldMatrix: objectWorldMatrix,
  13921. oneMinus: oneMinus,
  13922. or: or,
  13923. orthographicDepthToViewZ: orthographicDepthToViewZ,
  13924. oscSawtooth: oscSawtooth,
  13925. oscSine: oscSine,
  13926. oscSquare: oscSquare,
  13927. oscTriangle: oscTriangle,
  13928. output: output,
  13929. outputStruct: outputStruct,
  13930. overlay: overlay,
  13931. overloadingFn: overloadingFn,
  13932. parabola: parabola,
  13933. parallaxDirection: parallaxDirection,
  13934. parallaxUV: parallaxUV,
  13935. parameter: parameter,
  13936. pass: pass,
  13937. passTexture: passTexture,
  13938. pcurve: pcurve,
  13939. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  13940. pmremTexture: pmremTexture,
  13941. pointUV: pointUV,
  13942. pointWidth: pointWidth,
  13943. positionGeometry: positionGeometry,
  13944. positionLocal: positionLocal,
  13945. positionPrevious: positionPrevious,
  13946. positionView: positionView,
  13947. positionViewDirection: positionViewDirection,
  13948. positionWorld: positionWorld,
  13949. positionWorldDirection: positionWorldDirection,
  13950. posterize: posterize,
  13951. pow: pow,
  13952. pow2: pow2,
  13953. pow3: pow3,
  13954. pow4: pow4,
  13955. property: property,
  13956. radians: radians,
  13957. rand: rand,
  13958. range: range,
  13959. rangeFog: rangeFog,
  13960. reciprocal: reciprocal,
  13961. reference: reference,
  13962. referenceBuffer: referenceBuffer,
  13963. reflect: reflect,
  13964. reflectVector: reflectVector,
  13965. reflectView: reflectView,
  13966. reflector: reflector,
  13967. refract: refract,
  13968. refractVector: refractVector,
  13969. refractView: refractView,
  13970. reinhardToneMapping: reinhardToneMapping,
  13971. remainder: remainder,
  13972. remap: remap,
  13973. remapClamp: remapClamp,
  13974. renderGroup: renderGroup,
  13975. renderOutput: renderOutput,
  13976. rendererReference: rendererReference,
  13977. rotate: rotate,
  13978. rotateUV: rotateUV,
  13979. roughness: roughness,
  13980. round: round,
  13981. rtt: rtt,
  13982. sRGBTransferEOTF: sRGBTransferEOTF,
  13983. sRGBTransferOETF: sRGBTransferOETF,
  13984. sampler: sampler,
  13985. saturate: saturate,
  13986. saturation: saturation,
  13987. screen: screen,
  13988. screenCoordinate: screenCoordinate,
  13989. screenSize: screenSize,
  13990. screenUV: screenUV,
  13991. scriptable: scriptable,
  13992. scriptableValue: scriptableValue,
  13993. select: select,
  13994. setCurrentStack: setCurrentStack,
  13995. shaderStages: shaderStages,
  13996. shadow: shadow,
  13997. sharedUniformGroup: sharedUniformGroup,
  13998. sheen: sheen,
  13999. sheenRoughness: sheenRoughness,
  14000. shiftLeft: shiftLeft,
  14001. shiftRight: shiftRight,
  14002. shininess: shininess,
  14003. sign: sign,
  14004. sin: sin,
  14005. sinc: sinc,
  14006. skinning: skinning,
  14007. skinningReference: skinningReference,
  14008. smoothstep: smoothstep,
  14009. smoothstepElement: smoothstepElement,
  14010. specularColor: specularColor,
  14011. specularF90: specularF90,
  14012. spherizeUV: spherizeUV,
  14013. split: split,
  14014. spritesheetUV: spritesheetUV,
  14015. sqrt: sqrt,
  14016. stack: stack,
  14017. step: step,
  14018. storage: storage,
  14019. storageBarrier: storageBarrier,
  14020. storageObject: storageObject,
  14021. storageTexture: storageTexture,
  14022. string: string,
  14023. sub: sub,
  14024. subgroupIndex: subgroupIndex,
  14025. subgroupSize: subgroupSize,
  14026. tan: tan,
  14027. tangentGeometry: tangentGeometry,
  14028. tangentLocal: tangentLocal,
  14029. tangentView: tangentView,
  14030. tangentWorld: tangentWorld,
  14031. temp: temp,
  14032. texture: texture,
  14033. texture3D: texture3D,
  14034. textureBarrier: textureBarrier,
  14035. textureBicubic: textureBicubic,
  14036. textureCubeUV: textureCubeUV,
  14037. textureLoad: textureLoad,
  14038. textureSize: textureSize,
  14039. textureStore: textureStore,
  14040. thickness: thickness,
  14041. threshold: threshold,
  14042. time: time,
  14043. timerDelta: timerDelta,
  14044. timerGlobal: timerGlobal,
  14045. timerLocal: timerLocal,
  14046. toOutputColorSpace: toOutputColorSpace,
  14047. toWorkingColorSpace: toWorkingColorSpace,
  14048. toneMapping: toneMapping,
  14049. toneMappingExposure: toneMappingExposure,
  14050. toonOutlinePass: toonOutlinePass,
  14051. transformDirection: transformDirection,
  14052. transformNormal: transformNormal,
  14053. transformNormalToView: transformNormalToView,
  14054. transformedBentNormalView: transformedBentNormalView,
  14055. transformedBitangentView: transformedBitangentView,
  14056. transformedBitangentWorld: transformedBitangentWorld,
  14057. transformedClearcoatNormalView: transformedClearcoatNormalView,
  14058. transformedNormalView: transformedNormalView,
  14059. transformedNormalWorld: transformedNormalWorld,
  14060. transformedTangentView: transformedTangentView,
  14061. transformedTangentWorld: transformedTangentWorld,
  14062. transmission: transmission,
  14063. transpose: transpose,
  14064. tri: tri,
  14065. tri3: tri3,
  14066. triNoise3D: triNoise3D,
  14067. triplanarTexture: triplanarTexture,
  14068. triplanarTextures: triplanarTextures,
  14069. trunc: trunc,
  14070. tslFn: tslFn,
  14071. uint: uint,
  14072. uniform: uniform,
  14073. uniformArray: uniformArray,
  14074. uniformGroup: uniformGroup,
  14075. uniforms: uniforms,
  14076. userData: userData,
  14077. uv: uv,
  14078. uvec2: uvec2,
  14079. uvec3: uvec3,
  14080. uvec4: uvec4,
  14081. varying: varying,
  14082. varyingProperty: varyingProperty,
  14083. vec2: vec2,
  14084. vec3: vec3,
  14085. vec4: vec4,
  14086. vectorComponents: vectorComponents,
  14087. velocity: velocity,
  14088. vertexColor: vertexColor,
  14089. vertexIndex: vertexIndex,
  14090. vibrance: vibrance,
  14091. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  14092. viewZToOrthographicDepth: viewZToOrthographicDepth,
  14093. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  14094. viewport: viewport,
  14095. viewportBottomLeft: viewportBottomLeft,
  14096. viewportCoordinate: viewportCoordinate,
  14097. viewportDepthTexture: viewportDepthTexture,
  14098. viewportLinearDepth: viewportLinearDepth,
  14099. viewportMipTexture: viewportMipTexture,
  14100. viewportResolution: viewportResolution,
  14101. viewportSafeUV: viewportSafeUV,
  14102. viewportSharedTexture: viewportSharedTexture,
  14103. viewportSize: viewportSize,
  14104. viewportTexture: viewportTexture,
  14105. viewportTopLeft: viewportTopLeft,
  14106. viewportUV: viewportUV,
  14107. wgsl: wgsl,
  14108. wgslFn: wgslFn,
  14109. workgroupArray: workgroupArray,
  14110. workgroupBarrier: workgroupBarrier,
  14111. workgroupId: workgroupId,
  14112. workingToColorSpace: workingToColorSpace,
  14113. xor: xor
  14114. });
  14115. const _clearColor$1 = /*@__PURE__*/ new Color4();
  14116. class Background extends DataMap {
  14117. constructor( renderer, nodes ) {
  14118. super();
  14119. this.renderer = renderer;
  14120. this.nodes = nodes;
  14121. }
  14122. update( scene, renderList, renderContext ) {
  14123. const renderer = this.renderer;
  14124. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  14125. let forceClear = false;
  14126. if ( background === null ) {
  14127. // no background settings, use clear color configuration from the renderer
  14128. renderer._clearColor.getRGB( _clearColor$1, LinearSRGBColorSpace );
  14129. _clearColor$1.a = renderer._clearColor.a;
  14130. } else if ( background.isColor === true ) {
  14131. // background is an opaque color
  14132. background.getRGB( _clearColor$1, LinearSRGBColorSpace );
  14133. _clearColor$1.a = 1;
  14134. forceClear = true;
  14135. } else if ( background.isNode === true ) {
  14136. const sceneData = this.get( scene );
  14137. const backgroundNode = background;
  14138. _clearColor$1.copy( renderer._clearColor );
  14139. let backgroundMesh = sceneData.backgroundMesh;
  14140. if ( backgroundMesh === undefined ) {
  14141. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  14142. // @TODO: Add Texture2D support using node context
  14143. getUV: () => backgroundRotation.mul( normalWorld ),
  14144. getTextureLevel: () => backgroundBlurriness
  14145. } );
  14146. let viewProj = modelViewProjection();
  14147. viewProj = viewProj.setZ( viewProj.w );
  14148. const nodeMaterial = new NodeMaterial();
  14149. nodeMaterial.name = 'Background.material';
  14150. nodeMaterial.side = BackSide;
  14151. nodeMaterial.depthTest = false;
  14152. nodeMaterial.depthWrite = false;
  14153. nodeMaterial.fog = false;
  14154. nodeMaterial.lights = false;
  14155. nodeMaterial.vertexNode = viewProj;
  14156. nodeMaterial.colorNode = backgroundMeshNode;
  14157. sceneData.backgroundMeshNode = backgroundMeshNode;
  14158. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  14159. backgroundMesh.frustumCulled = false;
  14160. backgroundMesh.name = 'Background.mesh';
  14161. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  14162. this.matrixWorld.copyPosition( camera.matrixWorld );
  14163. };
  14164. }
  14165. const backgroundCacheKey = backgroundNode.getCacheKey();
  14166. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  14167. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  14168. sceneData.backgroundMeshNode.needsUpdate = true;
  14169. backgroundMesh.material.needsUpdate = true;
  14170. sceneData.backgroundCacheKey = backgroundCacheKey;
  14171. }
  14172. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  14173. } else {
  14174. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  14175. }
  14176. //
  14177. if ( renderer.autoClear === true || forceClear === true ) {
  14178. const clearColorValue = renderContext.clearColorValue;
  14179. clearColorValue.r = _clearColor$1.r;
  14180. clearColorValue.g = _clearColor$1.g;
  14181. clearColorValue.b = _clearColor$1.b;
  14182. clearColorValue.a = _clearColor$1.a;
  14183. // premultiply alpha
  14184. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  14185. clearColorValue.r *= clearColorValue.a;
  14186. clearColorValue.g *= clearColorValue.a;
  14187. clearColorValue.b *= clearColorValue.a;
  14188. }
  14189. //
  14190. renderContext.depthClearValue = renderer._clearDepth;
  14191. renderContext.stencilClearValue = renderer._clearStencil;
  14192. renderContext.clearColor = renderer.autoClearColor === true;
  14193. renderContext.clearDepth = renderer.autoClearDepth === true;
  14194. renderContext.clearStencil = renderer.autoClearStencil === true;
  14195. } else {
  14196. renderContext.clearColor = false;
  14197. renderContext.clearDepth = false;
  14198. renderContext.clearStencil = false;
  14199. }
  14200. }
  14201. }
  14202. let _id$5 = 0;
  14203. class BindGroup {
  14204. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  14205. this.name = name;
  14206. this.bindings = bindings;
  14207. this.index = index;
  14208. this.bindingsReference = bindingsReference;
  14209. this.id = _id$5 ++;
  14210. }
  14211. }
  14212. class NodeBuilderState {
  14213. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, monitor, transforms = [] ) {
  14214. this.vertexShader = vertexShader;
  14215. this.fragmentShader = fragmentShader;
  14216. this.computeShader = computeShader;
  14217. this.transforms = transforms;
  14218. this.nodeAttributes = nodeAttributes;
  14219. this.bindings = bindings;
  14220. this.updateNodes = updateNodes;
  14221. this.updateBeforeNodes = updateBeforeNodes;
  14222. this.updateAfterNodes = updateAfterNodes;
  14223. this.monitor = monitor;
  14224. this.usedTimes = 0;
  14225. }
  14226. createBindings() {
  14227. const bindings = [];
  14228. for ( const instanceGroup of this.bindings ) {
  14229. const shared = instanceGroup.bindings[ 0 ].groupNode.shared;
  14230. if ( shared !== true ) {
  14231. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  14232. bindings.push( bindingsGroup );
  14233. for ( const instanceBinding of instanceGroup.bindings ) {
  14234. bindingsGroup.bindings.push( instanceBinding.clone() );
  14235. }
  14236. } else {
  14237. bindings.push( instanceGroup );
  14238. }
  14239. }
  14240. return bindings;
  14241. }
  14242. }
  14243. class NodeAttribute {
  14244. constructor( name, type, node = null ) {
  14245. this.isNodeAttribute = true;
  14246. this.name = name;
  14247. this.type = type;
  14248. this.node = node;
  14249. }
  14250. }
  14251. class NodeUniform {
  14252. constructor( name, type, node ) {
  14253. this.isNodeUniform = true;
  14254. this.name = name;
  14255. this.type = type;
  14256. this.node = node.getSelf();
  14257. }
  14258. get value() {
  14259. return this.node.value;
  14260. }
  14261. set value( val ) {
  14262. this.node.value = val;
  14263. }
  14264. get id() {
  14265. return this.node.id;
  14266. }
  14267. get groupNode() {
  14268. return this.node.groupNode;
  14269. }
  14270. }
  14271. class NodeVar {
  14272. constructor( name, type ) {
  14273. this.isNodeVar = true;
  14274. this.name = name;
  14275. this.type = type;
  14276. }
  14277. }
  14278. class NodeVarying extends NodeVar {
  14279. constructor( name, type ) {
  14280. super( name, type );
  14281. this.needsInterpolation = false;
  14282. this.isNodeVarying = true;
  14283. }
  14284. }
  14285. class NodeCode {
  14286. constructor( name, type, code = '' ) {
  14287. this.name = name;
  14288. this.type = type;
  14289. this.code = code;
  14290. Object.defineProperty( this, 'isNodeCode', { value: true } );
  14291. }
  14292. }
  14293. let id = 0;
  14294. class NodeCache {
  14295. constructor( parent = null ) {
  14296. this.id = id ++;
  14297. this.nodesData = new WeakMap();
  14298. this.parent = parent;
  14299. }
  14300. getData( node ) {
  14301. let data = this.nodesData.get( node );
  14302. if ( data === undefined && this.parent !== null ) {
  14303. data = this.parent.getData( node );
  14304. }
  14305. return data;
  14306. }
  14307. setData( node, data ) {
  14308. this.nodesData.set( node, data );
  14309. }
  14310. }
  14311. class Uniform {
  14312. constructor( name, value ) {
  14313. this.name = name;
  14314. this.value = value;
  14315. this.boundary = 0; // used to build the uniform buffer according to the STD140 layout
  14316. this.itemSize = 0;
  14317. this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer
  14318. }
  14319. setValue( value ) {
  14320. this.value = value;
  14321. }
  14322. getValue() {
  14323. return this.value;
  14324. }
  14325. }
  14326. class NumberUniform extends Uniform {
  14327. constructor( name, value = 0 ) {
  14328. super( name, value );
  14329. this.isNumberUniform = true;
  14330. this.boundary = 4;
  14331. this.itemSize = 1;
  14332. }
  14333. }
  14334. class Vector2Uniform extends Uniform {
  14335. constructor( name, value = new Vector2() ) {
  14336. super( name, value );
  14337. this.isVector2Uniform = true;
  14338. this.boundary = 8;
  14339. this.itemSize = 2;
  14340. }
  14341. }
  14342. class Vector3Uniform extends Uniform {
  14343. constructor( name, value = new Vector3() ) {
  14344. super( name, value );
  14345. this.isVector3Uniform = true;
  14346. this.boundary = 16;
  14347. this.itemSize = 3;
  14348. }
  14349. }
  14350. class Vector4Uniform extends Uniform {
  14351. constructor( name, value = new Vector4() ) {
  14352. super( name, value );
  14353. this.isVector4Uniform = true;
  14354. this.boundary = 16;
  14355. this.itemSize = 4;
  14356. }
  14357. }
  14358. class ColorUniform extends Uniform {
  14359. constructor( name, value = new Color() ) {
  14360. super( name, value );
  14361. this.isColorUniform = true;
  14362. this.boundary = 16;
  14363. this.itemSize = 3;
  14364. }
  14365. }
  14366. class Matrix3Uniform extends Uniform {
  14367. constructor( name, value = new Matrix3() ) {
  14368. super( name, value );
  14369. this.isMatrix3Uniform = true;
  14370. this.boundary = 48;
  14371. this.itemSize = 12;
  14372. }
  14373. }
  14374. class Matrix4Uniform extends Uniform {
  14375. constructor( name, value = new Matrix4() ) {
  14376. super( name, value );
  14377. this.isMatrix4Uniform = true;
  14378. this.boundary = 64;
  14379. this.itemSize = 16;
  14380. }
  14381. }
  14382. class NumberNodeUniform extends NumberUniform {
  14383. constructor( nodeUniform ) {
  14384. super( nodeUniform.name, nodeUniform.value );
  14385. this.nodeUniform = nodeUniform;
  14386. }
  14387. getValue() {
  14388. return this.nodeUniform.value;
  14389. }
  14390. getType() {
  14391. return this.nodeUniform.type;
  14392. }
  14393. }
  14394. class Vector2NodeUniform extends Vector2Uniform {
  14395. constructor( nodeUniform ) {
  14396. super( nodeUniform.name, nodeUniform.value );
  14397. this.nodeUniform = nodeUniform;
  14398. }
  14399. getValue() {
  14400. return this.nodeUniform.value;
  14401. }
  14402. getType() {
  14403. return this.nodeUniform.type;
  14404. }
  14405. }
  14406. class Vector3NodeUniform extends Vector3Uniform {
  14407. constructor( nodeUniform ) {
  14408. super( nodeUniform.name, nodeUniform.value );
  14409. this.nodeUniform = nodeUniform;
  14410. }
  14411. getValue() {
  14412. return this.nodeUniform.value;
  14413. }
  14414. getType() {
  14415. return this.nodeUniform.type;
  14416. }
  14417. }
  14418. class Vector4NodeUniform extends Vector4Uniform {
  14419. constructor( nodeUniform ) {
  14420. super( nodeUniform.name, nodeUniform.value );
  14421. this.nodeUniform = nodeUniform;
  14422. }
  14423. getValue() {
  14424. return this.nodeUniform.value;
  14425. }
  14426. getType() {
  14427. return this.nodeUniform.type;
  14428. }
  14429. }
  14430. class ColorNodeUniform extends ColorUniform {
  14431. constructor( nodeUniform ) {
  14432. super( nodeUniform.name, nodeUniform.value );
  14433. this.nodeUniform = nodeUniform;
  14434. }
  14435. getValue() {
  14436. return this.nodeUniform.value;
  14437. }
  14438. getType() {
  14439. return this.nodeUniform.type;
  14440. }
  14441. }
  14442. class Matrix3NodeUniform extends Matrix3Uniform {
  14443. constructor( nodeUniform ) {
  14444. super( nodeUniform.name, nodeUniform.value );
  14445. this.nodeUniform = nodeUniform;
  14446. }
  14447. getValue() {
  14448. return this.nodeUniform.value;
  14449. }
  14450. getType() {
  14451. return this.nodeUniform.type;
  14452. }
  14453. }
  14454. class Matrix4NodeUniform extends Matrix4Uniform {
  14455. constructor( nodeUniform ) {
  14456. super( nodeUniform.name, nodeUniform.value );
  14457. this.nodeUniform = nodeUniform;
  14458. }
  14459. getValue() {
  14460. return this.nodeUniform.value;
  14461. }
  14462. getType() {
  14463. return this.nodeUniform.type;
  14464. }
  14465. }
  14466. const LOD_MIN = 4;
  14467. // The standard deviations (radians) associated with the extra mips. These are
  14468. // chosen to approximate a Trowbridge-Reitz distribution function times the
  14469. // geometric shadowing function. These sigma values squared must match the
  14470. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  14471. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  14472. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  14473. // samples and exit early, but not recompile the shader.
  14474. const MAX_SAMPLES = 20;
  14475. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  14476. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  14477. const _clearColor = /*@__PURE__*/ new Color();
  14478. let _oldTarget = null;
  14479. let _oldActiveCubeFace = 0;
  14480. let _oldActiveMipmapLevel = 0;
  14481. // Golden Ratio
  14482. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  14483. const INV_PHI = 1 / PHI;
  14484. // Vertices of a dodecahedron (except the opposites, which represent the
  14485. // same axis), used as axis directions evenly spread on a sphere.
  14486. const _axisDirections = [
  14487. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  14488. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  14489. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  14490. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  14491. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  14492. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  14493. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  14494. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  14495. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  14496. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  14497. ];
  14498. //
  14499. // WebGPU Face indices
  14500. const _faceLib = [
  14501. 3, 1, 5,
  14502. 0, 4, 2
  14503. ];
  14504. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  14505. const outputDirection = vec3( direction.x, direction.y.negate(), direction.z );
  14506. /**
  14507. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  14508. * (PMREM) from a cubeMap environment texture. This allows different levels of
  14509. * blur to be quickly accessed based on material roughness. It is packed into a
  14510. * special CubeUV format that allows us to perform custom interpolation so that
  14511. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  14512. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  14513. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  14514. * higher roughness levels. In this way we maintain resolution to smoothly
  14515. * interpolate diffuse lighting while limiting sampling computation.
  14516. *
  14517. * Paper: Fast, Accurate Image-Based Lighting
  14518. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  14519. */
  14520. class PMREMGenerator {
  14521. constructor( renderer ) {
  14522. this._renderer = renderer;
  14523. this._pingPongRenderTarget = null;
  14524. this._lodMax = 0;
  14525. this._cubeSize = 0;
  14526. this._lodPlanes = [];
  14527. this._sizeLods = [];
  14528. this._sigmas = [];
  14529. this._lodMeshes = [];
  14530. this._blurMaterial = null;
  14531. this._cubemapMaterial = null;
  14532. this._equirectMaterial = null;
  14533. this._backgroundBox = null;
  14534. }
  14535. get _hasInitialized() {
  14536. return this._renderer.hasInitialized();
  14537. }
  14538. /**
  14539. * Generates a PMREM from a supplied Scene, which can be faster than using an
  14540. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  14541. * in radians to be applied to the scene before PMREM generation. Optional near
  14542. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  14543. * is placed at the origin).
  14544. */
  14545. fromScene( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  14546. this._setSize( 256 );
  14547. if ( this._hasInitialized === false ) {
  14548. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  14549. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  14550. this.fromSceneAsync( scene, sigma, near, far, cubeUVRenderTarget );
  14551. return cubeUVRenderTarget;
  14552. }
  14553. _oldTarget = this._renderer.getRenderTarget();
  14554. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  14555. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  14556. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  14557. cubeUVRenderTarget.depthBuffer = true;
  14558. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  14559. if ( sigma > 0 ) {
  14560. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  14561. }
  14562. this._applyPMREM( cubeUVRenderTarget );
  14563. this._cleanup( cubeUVRenderTarget );
  14564. return cubeUVRenderTarget;
  14565. }
  14566. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  14567. if ( this._hasInitialized === false ) await this._renderer.init();
  14568. return this.fromScene( scene, sigma, near, far, renderTarget );
  14569. }
  14570. /**
  14571. * Generates a PMREM from an equirectangular texture, which can be either LDR
  14572. * or HDR. The ideal input image size is 1k (1024 x 512),
  14573. * as this matches best with the 256 x 256 cubemap output.
  14574. */
  14575. fromEquirectangular( equirectangular, renderTarget = null ) {
  14576. if ( this._hasInitialized === false ) {
  14577. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  14578. this._setSizeFromTexture( equirectangular );
  14579. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  14580. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  14581. return cubeUVRenderTarget;
  14582. }
  14583. return this._fromTexture( equirectangular, renderTarget );
  14584. }
  14585. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  14586. if ( this._hasInitialized === false ) await this._renderer.init();
  14587. return this._fromTexture( equirectangular, renderTarget );
  14588. }
  14589. /**
  14590. * Generates a PMREM from an cubemap texture, which can be either LDR
  14591. * or HDR. The ideal input cube size is 256 x 256,
  14592. * as this matches best with the 256 x 256 cubemap output.
  14593. */
  14594. fromCubemap( cubemap, renderTarget = null ) {
  14595. if ( this._hasInitialized === false ) {
  14596. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  14597. this._setSizeFromTexture( cubemap );
  14598. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  14599. this.fromCubemapAsync( cubemap, renderTarget );
  14600. return cubeUVRenderTarget;
  14601. }
  14602. return this._fromTexture( cubemap, renderTarget );
  14603. }
  14604. async fromCubemapAsync( cubemap, renderTarget = null ) {
  14605. if ( this._hasInitialized === false ) await this._renderer.init();
  14606. return this._fromTexture( cubemap, renderTarget );
  14607. }
  14608. /**
  14609. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  14610. * your texture's network fetch for increased concurrency.
  14611. */
  14612. async compileCubemapShader() {
  14613. if ( this._cubemapMaterial === null ) {
  14614. this._cubemapMaterial = _getCubemapMaterial();
  14615. await this._compileMaterial( this._cubemapMaterial );
  14616. }
  14617. }
  14618. /**
  14619. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  14620. * your texture's network fetch for increased concurrency.
  14621. */
  14622. async compileEquirectangularShader() {
  14623. if ( this._equirectMaterial === null ) {
  14624. this._equirectMaterial = _getEquirectMaterial();
  14625. await this._compileMaterial( this._equirectMaterial );
  14626. }
  14627. }
  14628. /**
  14629. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  14630. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  14631. * one of them will cause any others to also become unusable.
  14632. */
  14633. dispose() {
  14634. this._dispose();
  14635. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  14636. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  14637. if ( this._backgroundBox !== null ) {
  14638. this._backgroundBox.geometry.dispose();
  14639. this._backgroundBox.material.dispose();
  14640. }
  14641. }
  14642. // private interface
  14643. _setSizeFromTexture( texture ) {
  14644. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  14645. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  14646. } else { // Equirectangular
  14647. this._setSize( texture.image.width / 4 );
  14648. }
  14649. }
  14650. _setSize( cubeSize ) {
  14651. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  14652. this._cubeSize = Math.pow( 2, this._lodMax );
  14653. }
  14654. _dispose() {
  14655. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  14656. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  14657. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  14658. this._lodPlanes[ i ].dispose();
  14659. }
  14660. }
  14661. _cleanup( outputTarget ) {
  14662. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  14663. outputTarget.scissorTest = false;
  14664. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  14665. }
  14666. _fromTexture( texture, renderTarget ) {
  14667. this._setSizeFromTexture( texture );
  14668. _oldTarget = this._renderer.getRenderTarget();
  14669. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  14670. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  14671. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  14672. this._textureToCubeUV( texture, cubeUVRenderTarget );
  14673. this._applyPMREM( cubeUVRenderTarget );
  14674. this._cleanup( cubeUVRenderTarget );
  14675. return cubeUVRenderTarget;
  14676. }
  14677. _allocateTargets() {
  14678. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  14679. const height = 4 * this._cubeSize;
  14680. const params = {
  14681. magFilter: LinearFilter,
  14682. minFilter: LinearFilter,
  14683. generateMipmaps: false,
  14684. type: HalfFloatType,
  14685. format: RGBAFormat,
  14686. colorSpace: LinearSRGBColorSpace,
  14687. //depthBuffer: false
  14688. };
  14689. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  14690. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  14691. if ( this._pingPongRenderTarget !== null ) {
  14692. this._dispose();
  14693. }
  14694. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  14695. const { _lodMax } = this;
  14696. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  14697. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  14698. }
  14699. return cubeUVRenderTarget;
  14700. }
  14701. async _compileMaterial( material ) {
  14702. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  14703. await this._renderer.compile( tmpMesh, _flatCamera );
  14704. }
  14705. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  14706. const cubeCamera = _cubeCamera;
  14707. cubeCamera.near = near;
  14708. cubeCamera.far = far;
  14709. // px, py, pz, nx, ny, nz
  14710. const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ];
  14711. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  14712. const renderer = this._renderer;
  14713. const originalAutoClear = renderer.autoClear;
  14714. renderer.getClearColor( _clearColor );
  14715. renderer.autoClear = false;
  14716. let backgroundBox = this._backgroundBox;
  14717. if ( backgroundBox === null ) {
  14718. const backgroundMaterial = new MeshBasicMaterial( {
  14719. name: 'PMREM.Background',
  14720. side: BackSide,
  14721. depthWrite: false,
  14722. depthTest: false
  14723. } );
  14724. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  14725. }
  14726. let useSolidColor = false;
  14727. const background = scene.background;
  14728. if ( background ) {
  14729. if ( background.isColor ) {
  14730. backgroundBox.material.color.copy( background );
  14731. scene.background = null;
  14732. useSolidColor = true;
  14733. }
  14734. } else {
  14735. backgroundBox.material.color.copy( _clearColor );
  14736. useSolidColor = true;
  14737. }
  14738. renderer.setRenderTarget( cubeUVRenderTarget );
  14739. renderer.clear();
  14740. if ( useSolidColor ) {
  14741. renderer.render( backgroundBox, cubeCamera );
  14742. }
  14743. for ( let i = 0; i < 6; i ++ ) {
  14744. const col = i % 3;
  14745. if ( col === 0 ) {
  14746. cubeCamera.up.set( 0, upSign[ i ], 0 );
  14747. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  14748. } else if ( col === 1 ) {
  14749. cubeCamera.up.set( 0, 0, upSign[ i ] );
  14750. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  14751. } else {
  14752. cubeCamera.up.set( 0, upSign[ i ], 0 );
  14753. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  14754. }
  14755. const size = this._cubeSize;
  14756. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  14757. renderer.render( scene, cubeCamera );
  14758. }
  14759. renderer.autoClear = originalAutoClear;
  14760. scene.background = background;
  14761. }
  14762. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  14763. const renderer = this._renderer;
  14764. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  14765. if ( isCubeTexture ) {
  14766. if ( this._cubemapMaterial === null ) {
  14767. this._cubemapMaterial = _getCubemapMaterial( texture );
  14768. }
  14769. } else {
  14770. if ( this._equirectMaterial === null ) {
  14771. this._equirectMaterial = _getEquirectMaterial( texture );
  14772. }
  14773. }
  14774. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  14775. material.fragmentNode.value = texture;
  14776. const mesh = this._lodMeshes[ 0 ];
  14777. mesh.material = material;
  14778. const size = this._cubeSize;
  14779. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  14780. renderer.setRenderTarget( cubeUVRenderTarget );
  14781. renderer.render( mesh, _flatCamera );
  14782. }
  14783. _applyPMREM( cubeUVRenderTarget ) {
  14784. const renderer = this._renderer;
  14785. const autoClear = renderer.autoClear;
  14786. renderer.autoClear = false;
  14787. const n = this._lodPlanes.length;
  14788. for ( let i = 1; i < n; i ++ ) {
  14789. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  14790. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  14791. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  14792. }
  14793. renderer.autoClear = autoClear;
  14794. }
  14795. /**
  14796. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  14797. * vertically and horizontally, but this breaks down on a cube. Here we apply
  14798. * the blur latitudinally (around the poles), and then longitudinally (towards
  14799. * the poles) to approximate the orthogonally-separable blur. It is least
  14800. * accurate at the poles, but still does a decent job.
  14801. */
  14802. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  14803. const pingPongRenderTarget = this._pingPongRenderTarget;
  14804. this._halfBlur(
  14805. cubeUVRenderTarget,
  14806. pingPongRenderTarget,
  14807. lodIn,
  14808. lodOut,
  14809. sigma,
  14810. 'latitudinal',
  14811. poleAxis );
  14812. this._halfBlur(
  14813. pingPongRenderTarget,
  14814. cubeUVRenderTarget,
  14815. lodOut,
  14816. lodOut,
  14817. sigma,
  14818. 'longitudinal',
  14819. poleAxis );
  14820. }
  14821. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  14822. const renderer = this._renderer;
  14823. const blurMaterial = this._blurMaterial;
  14824. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  14825. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  14826. }
  14827. // Number of standard deviations at which to cut off the discrete approximation.
  14828. const STANDARD_DEVIATIONS = 3;
  14829. const blurMesh = this._lodMeshes[ lodOut ];
  14830. blurMesh.material = blurMaterial;
  14831. const blurUniforms = blurMaterial.uniforms;
  14832. const pixels = this._sizeLods[ lodIn ] - 1;
  14833. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  14834. const sigmaPixels = sigmaRadians / radiansPerPixel;
  14835. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  14836. if ( samples > MAX_SAMPLES ) {
  14837. console.warn( `sigmaRadians, ${
  14838. sigmaRadians}, is too large and will clip, as it requested ${
  14839. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  14840. }
  14841. const weights = [];
  14842. let sum = 0;
  14843. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  14844. const x = i / sigmaPixels;
  14845. const weight = Math.exp( - x * x / 2 );
  14846. weights.push( weight );
  14847. if ( i === 0 ) {
  14848. sum += weight;
  14849. } else if ( i < samples ) {
  14850. sum += 2 * weight;
  14851. }
  14852. }
  14853. for ( let i = 0; i < weights.length; i ++ ) {
  14854. weights[ i ] = weights[ i ] / sum;
  14855. }
  14856. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  14857. blurUniforms.envMap.value = targetIn.texture;
  14858. blurUniforms.samples.value = samples;
  14859. blurUniforms.weights.array = weights;
  14860. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  14861. if ( poleAxis ) {
  14862. blurUniforms.poleAxis.value = poleAxis;
  14863. }
  14864. const { _lodMax } = this;
  14865. blurUniforms.dTheta.value = radiansPerPixel;
  14866. blurUniforms.mipInt.value = _lodMax - lodIn;
  14867. const outputSize = this._sizeLods[ lodOut ];
  14868. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  14869. const y = 4 * ( this._cubeSize - outputSize );
  14870. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  14871. renderer.setRenderTarget( targetOut );
  14872. renderer.render( blurMesh, _flatCamera );
  14873. }
  14874. }
  14875. function _createPlanes( lodMax ) {
  14876. const lodPlanes = [];
  14877. const sizeLods = [];
  14878. const sigmas = [];
  14879. const lodMeshes = [];
  14880. let lod = lodMax;
  14881. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  14882. for ( let i = 0; i < totalLods; i ++ ) {
  14883. const sizeLod = Math.pow( 2, lod );
  14884. sizeLods.push( sizeLod );
  14885. let sigma = 1.0 / sizeLod;
  14886. if ( i > lodMax - LOD_MIN ) {
  14887. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  14888. } else if ( i === 0 ) {
  14889. sigma = 0;
  14890. }
  14891. sigmas.push( sigma );
  14892. const texelSize = 1.0 / ( sizeLod - 2 );
  14893. const min = - texelSize;
  14894. const max = 1 + texelSize;
  14895. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  14896. const cubeFaces = 6;
  14897. const vertices = 6;
  14898. const positionSize = 3;
  14899. const uvSize = 2;
  14900. const faceIndexSize = 1;
  14901. const position = new Float32Array( positionSize * vertices * cubeFaces );
  14902. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  14903. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  14904. for ( let face = 0; face < cubeFaces; face ++ ) {
  14905. const x = ( face % 3 ) * 2 / 3 - 1;
  14906. const y = face > 2 ? 0 : - 1;
  14907. const coordinates = [
  14908. x, y, 0,
  14909. x + 2 / 3, y, 0,
  14910. x + 2 / 3, y + 1, 0,
  14911. x, y, 0,
  14912. x + 2 / 3, y + 1, 0,
  14913. x, y + 1, 0
  14914. ];
  14915. const faceIdx = _faceLib[ face ];
  14916. position.set( coordinates, positionSize * vertices * faceIdx );
  14917. uv.set( uv1, uvSize * vertices * faceIdx );
  14918. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  14919. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  14920. }
  14921. const planes = new BufferGeometry();
  14922. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  14923. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  14924. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  14925. lodPlanes.push( planes );
  14926. lodMeshes.push( new Mesh( planes, null ) );
  14927. if ( lod > LOD_MIN ) {
  14928. lod --;
  14929. }
  14930. }
  14931. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  14932. }
  14933. function _createRenderTarget( width, height, params ) {
  14934. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  14935. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  14936. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  14937. cubeUVRenderTarget.texture.isPMREMTexture = true;
  14938. cubeUVRenderTarget.scissorTest = true;
  14939. return cubeUVRenderTarget;
  14940. }
  14941. function _setViewport( target, x, y, width, height ) {
  14942. target.viewport.set( x, y, width, height );
  14943. target.scissor.set( x, y, width, height );
  14944. }
  14945. function _getMaterial( type ) {
  14946. const material = new NodeMaterial();
  14947. material.depthTest = false;
  14948. material.depthWrite = false;
  14949. material.blending = NoBlending;
  14950. material.name = `PMREM_${ type }`;
  14951. return material;
  14952. }
  14953. function _getBlurShader( lodMax, width, height ) {
  14954. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  14955. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  14956. const dTheta = uniform( 0 );
  14957. const n = float( MAX_SAMPLES );
  14958. const latitudinal = uniform( 0 ); // false, bool
  14959. const samples = uniform( 1 ); // int
  14960. const envMap = texture( null );
  14961. const mipInt = uniform( 0 ); // int
  14962. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  14963. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  14964. const CUBEUV_MAX_MIP = float( lodMax );
  14965. const materialUniforms = {
  14966. n,
  14967. latitudinal,
  14968. weights,
  14969. poleAxis,
  14970. outputDirection,
  14971. dTheta,
  14972. samples,
  14973. envMap,
  14974. mipInt,
  14975. CUBEUV_TEXEL_WIDTH,
  14976. CUBEUV_TEXEL_HEIGHT,
  14977. CUBEUV_MAX_MIP
  14978. };
  14979. const material = _getMaterial( 'blur' );
  14980. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  14981. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  14982. return material;
  14983. }
  14984. function _getCubemapMaterial( envTexture ) {
  14985. const material = _getMaterial( 'cubemap' );
  14986. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  14987. return material;
  14988. }
  14989. function _getEquirectMaterial( envTexture ) {
  14990. const material = _getMaterial( 'equirect' );
  14991. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  14992. return material;
  14993. }
  14994. const rendererCache = new WeakMap();
  14995. const typeFromArray = new Map( [
  14996. [ Int8Array, 'int' ],
  14997. [ Int16Array, 'int' ],
  14998. [ Int32Array, 'int' ],
  14999. [ Uint8Array, 'uint' ],
  15000. [ Uint16Array, 'uint' ],
  15001. [ Uint32Array, 'uint' ],
  15002. [ Float32Array, 'float' ]
  15003. ] );
  15004. const toFloat = ( value ) => {
  15005. if ( /e/g.test( value ) ) {
  15006. return String( value ).replace( /\+/g, '' );
  15007. } else {
  15008. value = Number( value );
  15009. return value + ( value % 1 ? '' : '.0' );
  15010. }
  15011. };
  15012. class NodeBuilder {
  15013. constructor( object, renderer, parser ) {
  15014. this.object = object;
  15015. this.material = ( object && object.material ) || null;
  15016. this.geometry = ( object && object.geometry ) || null;
  15017. this.renderer = renderer;
  15018. this.parser = parser;
  15019. this.scene = null;
  15020. this.camera = null;
  15021. this.nodes = [];
  15022. this.sequentialNodes = [];
  15023. this.updateNodes = [];
  15024. this.updateBeforeNodes = [];
  15025. this.updateAfterNodes = [];
  15026. this.hashNodes = {};
  15027. this.monitor = null;
  15028. this.lightsNode = null;
  15029. this.environmentNode = null;
  15030. this.fogNode = null;
  15031. this.clippingContext = null;
  15032. this.vertexShader = null;
  15033. this.fragmentShader = null;
  15034. this.computeShader = null;
  15035. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  15036. this.flowCode = { vertex: '', fragment: '', compute: '' };
  15037. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  15038. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  15039. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  15040. this.bindingsIndexes = {};
  15041. this.bindGroups = null;
  15042. this.attributes = [];
  15043. this.bufferAttributes = [];
  15044. this.varyings = [];
  15045. this.codes = {};
  15046. this.vars = {};
  15047. this.flow = { code: '' };
  15048. this.chaining = [];
  15049. this.stack = stack();
  15050. this.stacks = [];
  15051. this.tab = '\t';
  15052. this.currentFunctionNode = null;
  15053. this.context = {
  15054. material: this.material
  15055. };
  15056. this.cache = new NodeCache();
  15057. this.globalCache = this.cache;
  15058. this.flowsData = new WeakMap();
  15059. this.shaderStage = null;
  15060. this.buildStage = null;
  15061. this.useComparisonMethod = false;
  15062. }
  15063. getBindGroupsCache() {
  15064. let bindGroupsCache = rendererCache.get( this.renderer );
  15065. if ( bindGroupsCache === undefined ) {
  15066. bindGroupsCache = new ChainMap();
  15067. rendererCache.set( this.renderer, bindGroupsCache );
  15068. }
  15069. return bindGroupsCache;
  15070. }
  15071. createRenderTarget( width, height, options ) {
  15072. return new RenderTarget( width, height, options );
  15073. }
  15074. createCubeRenderTarget( size, options ) {
  15075. return new CubeRenderTarget( size, options );
  15076. }
  15077. createPMREMGenerator() {
  15078. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  15079. return new PMREMGenerator( this.renderer );
  15080. }
  15081. includes( node ) {
  15082. return this.nodes.includes( node );
  15083. }
  15084. _getBindGroup( groupName, bindings ) {
  15085. const bindGroupsCache = this.getBindGroupsCache();
  15086. //
  15087. const bindingsArray = [];
  15088. let sharedGroup = true;
  15089. for ( const binding of bindings ) {
  15090. bindingsArray.push( binding );
  15091. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  15092. }
  15093. //
  15094. let bindGroup;
  15095. if ( sharedGroup ) {
  15096. bindGroup = bindGroupsCache.get( bindingsArray );
  15097. if ( bindGroup === undefined ) {
  15098. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  15099. bindGroupsCache.set( bindingsArray, bindGroup );
  15100. }
  15101. } else {
  15102. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  15103. }
  15104. return bindGroup;
  15105. }
  15106. getBindGroupArray( groupName, shaderStage ) {
  15107. const bindings = this.bindings[ shaderStage ];
  15108. let bindGroup = bindings[ groupName ];
  15109. if ( bindGroup === undefined ) {
  15110. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  15111. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  15112. }
  15113. bindings[ groupName ] = bindGroup = [];
  15114. }
  15115. return bindGroup;
  15116. }
  15117. getBindings() {
  15118. let bindingsGroups = this.bindGroups;
  15119. if ( bindingsGroups === null ) {
  15120. const groups = {};
  15121. const bindings = this.bindings;
  15122. for ( const shaderStage of shaderStages ) {
  15123. for ( const groupName in bindings[ shaderStage ] ) {
  15124. const uniforms = bindings[ shaderStage ][ groupName ];
  15125. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  15126. groupUniforms.push( ...uniforms );
  15127. }
  15128. }
  15129. bindingsGroups = [];
  15130. for ( const groupName in groups ) {
  15131. const group = groups[ groupName ];
  15132. const bindingsGroup = this._getBindGroup( groupName, group );
  15133. bindingsGroups.push( bindingsGroup );
  15134. }
  15135. this.bindGroups = bindingsGroups;
  15136. }
  15137. return bindingsGroups;
  15138. }
  15139. sortBindingGroups() {
  15140. const bindingsGroups = this.getBindings();
  15141. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  15142. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  15143. const bindingGroup = bindingsGroups[ i ];
  15144. this.bindingsIndexes[ bindingGroup.name ].group = i;
  15145. bindingGroup.index = i;
  15146. }
  15147. }
  15148. setHashNode( node, hash ) {
  15149. this.hashNodes[ hash ] = node;
  15150. }
  15151. addNode( node ) {
  15152. if ( this.nodes.includes( node ) === false ) {
  15153. this.nodes.push( node );
  15154. this.setHashNode( node, node.getHash( this ) );
  15155. }
  15156. }
  15157. addSequentialNode( node ) {
  15158. if ( this.sequentialNodes.includes( node ) === false ) {
  15159. this.sequentialNodes.push( node );
  15160. }
  15161. }
  15162. buildUpdateNodes() {
  15163. for ( const node of this.nodes ) {
  15164. const updateType = node.getUpdateType();
  15165. if ( updateType !== NodeUpdateType.NONE ) {
  15166. this.updateNodes.push( node.getSelf() );
  15167. }
  15168. }
  15169. for ( const node of this.sequentialNodes ) {
  15170. const updateBeforeType = node.getUpdateBeforeType();
  15171. const updateAfterType = node.getUpdateAfterType();
  15172. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  15173. this.updateBeforeNodes.push( node.getSelf() );
  15174. }
  15175. if ( updateAfterType !== NodeUpdateType.NONE ) {
  15176. this.updateAfterNodes.push( node.getSelf() );
  15177. }
  15178. }
  15179. }
  15180. get currentNode() {
  15181. return this.chaining[ this.chaining.length - 1 ];
  15182. }
  15183. isFilteredTexture( texture ) {
  15184. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  15185. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  15186. }
  15187. addChain( node ) {
  15188. /*
  15189. if ( this.chaining.indexOf( node ) !== - 1 ) {
  15190. console.warn( 'Recursive node: ', node );
  15191. }
  15192. */
  15193. this.chaining.push( node );
  15194. }
  15195. removeChain( node ) {
  15196. const lastChain = this.chaining.pop();
  15197. if ( lastChain !== node ) {
  15198. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  15199. }
  15200. }
  15201. getMethod( method ) {
  15202. return method;
  15203. }
  15204. getNodeFromHash( hash ) {
  15205. return this.hashNodes[ hash ];
  15206. }
  15207. addFlow( shaderStage, node ) {
  15208. this.flowNodes[ shaderStage ].push( node );
  15209. return node;
  15210. }
  15211. setContext( context ) {
  15212. this.context = context;
  15213. }
  15214. getContext() {
  15215. return this.context;
  15216. }
  15217. getSharedContext() {
  15218. ({ ...this.context });
  15219. return this.context;
  15220. }
  15221. setCache( cache ) {
  15222. this.cache = cache;
  15223. }
  15224. getCache() {
  15225. return this.cache;
  15226. }
  15227. getCacheFromNode( node, parent = true ) {
  15228. const data = this.getDataFromNode( node );
  15229. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  15230. return data.cache;
  15231. }
  15232. isAvailable( /*name*/ ) {
  15233. return false;
  15234. }
  15235. getVertexIndex() {
  15236. console.warn( 'Abstract function.' );
  15237. }
  15238. getInstanceIndex() {
  15239. console.warn( 'Abstract function.' );
  15240. }
  15241. getDrawIndex() {
  15242. console.warn( 'Abstract function.' );
  15243. }
  15244. getFrontFacing() {
  15245. console.warn( 'Abstract function.' );
  15246. }
  15247. getFragCoord() {
  15248. console.warn( 'Abstract function.' );
  15249. }
  15250. isFlipY() {
  15251. return false;
  15252. }
  15253. increaseUsage( node ) {
  15254. const nodeData = this.getDataFromNode( node );
  15255. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  15256. return nodeData.usageCount;
  15257. }
  15258. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  15259. console.warn( 'Abstract function.' );
  15260. }
  15261. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  15262. console.warn( 'Abstract function.' );
  15263. }
  15264. generateConst( type, value = null ) {
  15265. if ( value === null ) {
  15266. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  15267. else if ( type === 'bool' ) value = false;
  15268. else if ( type === 'color' ) value = new Color();
  15269. else if ( type === 'vec2' ) value = new Vector2();
  15270. else if ( type === 'vec3' ) value = new Vector3();
  15271. else if ( type === 'vec4' ) value = new Vector4();
  15272. }
  15273. if ( type === 'float' ) return toFloat( value );
  15274. if ( type === 'int' ) return `${ Math.round( value ) }`;
  15275. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  15276. if ( type === 'bool' ) return value ? 'true' : 'false';
  15277. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  15278. const typeLength = this.getTypeLength( type );
  15279. const componentType = this.getComponentType( type );
  15280. const generateConst = value => this.generateConst( componentType, value );
  15281. if ( typeLength === 2 ) {
  15282. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  15283. } else if ( typeLength === 3 ) {
  15284. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  15285. } else if ( typeLength === 4 ) {
  15286. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  15287. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  15288. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  15289. } else if ( typeLength > 4 ) {
  15290. return `${ this.getType( type ) }()`;
  15291. }
  15292. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  15293. }
  15294. getType( type ) {
  15295. if ( type === 'color' ) return 'vec3';
  15296. return type;
  15297. }
  15298. hasGeometryAttribute( name ) {
  15299. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  15300. }
  15301. getAttribute( name, type ) {
  15302. const attributes = this.attributes;
  15303. // find attribute
  15304. for ( const attribute of attributes ) {
  15305. if ( attribute.name === name ) {
  15306. return attribute;
  15307. }
  15308. }
  15309. // create a new if no exist
  15310. const attribute = new NodeAttribute( name, type );
  15311. attributes.push( attribute );
  15312. return attribute;
  15313. }
  15314. getPropertyName( node/*, shaderStage*/ ) {
  15315. return node.name;
  15316. }
  15317. isVector( type ) {
  15318. return /vec\d/.test( type );
  15319. }
  15320. isMatrix( type ) {
  15321. return /mat\d/.test( type );
  15322. }
  15323. isReference( type ) {
  15324. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  15325. }
  15326. needsToWorkingColorSpace( /*texture*/ ) {
  15327. return false;
  15328. }
  15329. getComponentTypeFromTexture( texture ) {
  15330. const type = texture.type;
  15331. if ( texture.isDataTexture ) {
  15332. if ( type === IntType ) return 'int';
  15333. if ( type === UnsignedIntType ) return 'uint';
  15334. }
  15335. return 'float';
  15336. }
  15337. getElementType( type ) {
  15338. if ( type === 'mat2' ) return 'vec2';
  15339. if ( type === 'mat3' ) return 'vec3';
  15340. if ( type === 'mat4' ) return 'vec4';
  15341. return this.getComponentType( type );
  15342. }
  15343. getComponentType( type ) {
  15344. type = this.getVectorType( type );
  15345. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  15346. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  15347. if ( componentType === null ) return null;
  15348. if ( componentType[ 1 ] === 'b' ) return 'bool';
  15349. if ( componentType[ 1 ] === 'i' ) return 'int';
  15350. if ( componentType[ 1 ] === 'u' ) return 'uint';
  15351. return 'float';
  15352. }
  15353. getVectorType( type ) {
  15354. if ( type === 'color' ) return 'vec3';
  15355. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  15356. return type;
  15357. }
  15358. getTypeFromLength( length, componentType = 'float' ) {
  15359. if ( length === 1 ) return componentType;
  15360. const baseType = getTypeFromLength( length );
  15361. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  15362. return prefix + baseType;
  15363. }
  15364. getTypeFromArray( array ) {
  15365. return typeFromArray.get( array.constructor );
  15366. }
  15367. getTypeFromAttribute( attribute ) {
  15368. let dataAttribute = attribute;
  15369. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  15370. const array = dataAttribute.array;
  15371. const itemSize = attribute.itemSize;
  15372. const normalized = attribute.normalized;
  15373. let arrayType;
  15374. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  15375. arrayType = this.getTypeFromArray( array );
  15376. }
  15377. return this.getTypeFromLength( itemSize, arrayType );
  15378. }
  15379. getTypeLength( type ) {
  15380. const vecType = this.getVectorType( type );
  15381. const vecNum = /vec([2-4])/.exec( vecType );
  15382. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  15383. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  15384. if ( /mat2/.test( type ) === true ) return 4;
  15385. if ( /mat3/.test( type ) === true ) return 9;
  15386. if ( /mat4/.test( type ) === true ) return 16;
  15387. return 0;
  15388. }
  15389. getVectorFromMatrix( type ) {
  15390. return type.replace( 'mat', 'vec' );
  15391. }
  15392. changeComponentType( type, newComponentType ) {
  15393. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  15394. }
  15395. getIntegerType( type ) {
  15396. const componentType = this.getComponentType( type );
  15397. if ( componentType === 'int' || componentType === 'uint' ) return type;
  15398. return this.changeComponentType( type, 'int' );
  15399. }
  15400. addStack() {
  15401. this.stack = stack( this.stack );
  15402. this.stacks.push( getCurrentStack() || this.stack );
  15403. setCurrentStack( this.stack );
  15404. return this.stack;
  15405. }
  15406. removeStack() {
  15407. const lastStack = this.stack;
  15408. this.stack = lastStack.parent;
  15409. setCurrentStack( this.stacks.pop() );
  15410. return lastStack;
  15411. }
  15412. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  15413. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  15414. let nodeData = cache.getData( node );
  15415. if ( nodeData === undefined ) {
  15416. nodeData = {};
  15417. cache.setData( node, nodeData );
  15418. }
  15419. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  15420. return nodeData[ shaderStage ];
  15421. }
  15422. getNodeProperties( node, shaderStage = 'any' ) {
  15423. const nodeData = this.getDataFromNode( node, shaderStage );
  15424. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  15425. }
  15426. getBufferAttributeFromNode( node, type ) {
  15427. const nodeData = this.getDataFromNode( node );
  15428. let bufferAttribute = nodeData.bufferAttribute;
  15429. if ( bufferAttribute === undefined ) {
  15430. const index = this.uniforms.index ++;
  15431. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  15432. this.bufferAttributes.push( bufferAttribute );
  15433. nodeData.bufferAttribute = bufferAttribute;
  15434. }
  15435. return bufferAttribute;
  15436. }
  15437. getStructTypeFromNode( node, shaderStage = this.shaderStage ) {
  15438. const nodeData = this.getDataFromNode( node, shaderStage );
  15439. if ( nodeData.structType === undefined ) {
  15440. const index = this.structs.index ++;
  15441. node.name = `StructType${ index }`;
  15442. this.structs[ shaderStage ].push( node );
  15443. nodeData.structType = node;
  15444. }
  15445. return node;
  15446. }
  15447. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  15448. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  15449. let nodeUniform = nodeData.uniform;
  15450. if ( nodeUniform === undefined ) {
  15451. const index = this.uniforms.index ++;
  15452. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  15453. this.uniforms[ shaderStage ].push( nodeUniform );
  15454. nodeData.uniform = nodeUniform;
  15455. }
  15456. return nodeUniform;
  15457. }
  15458. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  15459. const nodeData = this.getDataFromNode( node, shaderStage );
  15460. let nodeVar = nodeData.variable;
  15461. if ( nodeVar === undefined ) {
  15462. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  15463. if ( name === null ) name = 'nodeVar' + vars.length;
  15464. nodeVar = new NodeVar( name, type );
  15465. vars.push( nodeVar );
  15466. nodeData.variable = nodeVar;
  15467. }
  15468. return nodeVar;
  15469. }
  15470. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  15471. const nodeData = this.getDataFromNode( node, 'any' );
  15472. let nodeVarying = nodeData.varying;
  15473. if ( nodeVarying === undefined ) {
  15474. const varyings = this.varyings;
  15475. const index = varyings.length;
  15476. if ( name === null ) name = 'nodeVarying' + index;
  15477. nodeVarying = new NodeVarying( name, type );
  15478. varyings.push( nodeVarying );
  15479. nodeData.varying = nodeVarying;
  15480. }
  15481. return nodeVarying;
  15482. }
  15483. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  15484. const nodeData = this.getDataFromNode( node );
  15485. let nodeCode = nodeData.code;
  15486. if ( nodeCode === undefined ) {
  15487. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  15488. const index = codes.length;
  15489. nodeCode = new NodeCode( 'nodeCode' + index, type );
  15490. codes.push( nodeCode );
  15491. nodeData.code = nodeCode;
  15492. }
  15493. return nodeCode;
  15494. }
  15495. addFlowCodeHierarchy( node, nodeBlock ) {
  15496. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  15497. let needsFlowCode = true;
  15498. let nodeBlockHierarchy = nodeBlock;
  15499. while ( nodeBlockHierarchy ) {
  15500. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  15501. needsFlowCode = false;
  15502. break;
  15503. }
  15504. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  15505. }
  15506. if ( needsFlowCode ) {
  15507. for ( const flowCode of flowCodes ) {
  15508. this.addLineFlowCode( flowCode );
  15509. }
  15510. }
  15511. }
  15512. addLineFlowCodeBlock( node, code, nodeBlock ) {
  15513. const nodeData = this.getDataFromNode( node );
  15514. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  15515. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  15516. flowCodes.push( code );
  15517. codeBlock.set( nodeBlock, true );
  15518. }
  15519. addLineFlowCode( code, node = null ) {
  15520. if ( code === '' ) return this;
  15521. if ( node !== null && this.context.nodeBlock ) {
  15522. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  15523. }
  15524. code = this.tab + code;
  15525. if ( ! /;\s*$/.test( code ) ) {
  15526. code = code + ';\n';
  15527. }
  15528. this.flow.code += code;
  15529. return this;
  15530. }
  15531. addFlowCode( code ) {
  15532. this.flow.code += code;
  15533. return this;
  15534. }
  15535. addFlowTab() {
  15536. this.tab += '\t';
  15537. return this;
  15538. }
  15539. removeFlowTab() {
  15540. this.tab = this.tab.slice( 0, - 1 );
  15541. return this;
  15542. }
  15543. getFlowData( node/*, shaderStage*/ ) {
  15544. return this.flowsData.get( node );
  15545. }
  15546. flowNode( node ) {
  15547. const output = node.getNodeType( this );
  15548. const flowData = this.flowChildNode( node, output );
  15549. this.flowsData.set( node, flowData );
  15550. return flowData;
  15551. }
  15552. buildFunctionNode( shaderNode ) {
  15553. const fn = new FunctionNode();
  15554. const previous = this.currentFunctionNode;
  15555. this.currentFunctionNode = fn;
  15556. fn.code = this.buildFunctionCode( shaderNode );
  15557. this.currentFunctionNode = previous;
  15558. return fn;
  15559. }
  15560. flowShaderNode( shaderNode ) {
  15561. const layout = shaderNode.layout;
  15562. const inputs = {
  15563. [ Symbol.iterator ]() {
  15564. let index = 0;
  15565. const values = Object.values( this );
  15566. return {
  15567. next: () => ( {
  15568. value: values[ index ],
  15569. done: index ++ >= values.length
  15570. } )
  15571. };
  15572. }
  15573. };
  15574. for ( const input of layout.inputs ) {
  15575. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  15576. }
  15577. //
  15578. shaderNode.layout = null;
  15579. const callNode = shaderNode.call( inputs );
  15580. const flowData = this.flowStagesNode( callNode, layout.type );
  15581. shaderNode.layout = layout;
  15582. return flowData;
  15583. }
  15584. flowStagesNode( node, output = null ) {
  15585. const previousFlow = this.flow;
  15586. const previousVars = this.vars;
  15587. const previousCache = this.cache;
  15588. const previousBuildStage = this.buildStage;
  15589. const previousStack = this.stack;
  15590. const flow = {
  15591. code: ''
  15592. };
  15593. this.flow = flow;
  15594. this.vars = {};
  15595. this.cache = new NodeCache();
  15596. this.stack = stack();
  15597. for ( const buildStage of defaultBuildStages ) {
  15598. this.setBuildStage( buildStage );
  15599. flow.result = node.build( this, output );
  15600. }
  15601. flow.vars = this.getVars( this.shaderStage );
  15602. this.flow = previousFlow;
  15603. this.vars = previousVars;
  15604. this.cache = previousCache;
  15605. this.stack = previousStack;
  15606. this.setBuildStage( previousBuildStage );
  15607. return flow;
  15608. }
  15609. getFunctionOperator() {
  15610. return null;
  15611. }
  15612. flowChildNode( node, output = null ) {
  15613. const previousFlow = this.flow;
  15614. const flow = {
  15615. code: ''
  15616. };
  15617. this.flow = flow;
  15618. flow.result = node.build( this, output );
  15619. this.flow = previousFlow;
  15620. return flow;
  15621. }
  15622. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  15623. const previousShaderStage = this.shaderStage;
  15624. this.setShaderStage( shaderStage );
  15625. const flowData = this.flowChildNode( node, output );
  15626. if ( propertyName !== null ) {
  15627. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  15628. }
  15629. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  15630. this.setShaderStage( previousShaderStage );
  15631. return flowData;
  15632. }
  15633. getAttributesArray() {
  15634. return this.attributes.concat( this.bufferAttributes );
  15635. }
  15636. getAttributes( /*shaderStage*/ ) {
  15637. console.warn( 'Abstract function.' );
  15638. }
  15639. getVaryings( /*shaderStage*/ ) {
  15640. console.warn( 'Abstract function.' );
  15641. }
  15642. getVar( type, name ) {
  15643. return `${ this.getType( type ) } ${ name }`;
  15644. }
  15645. getVars( shaderStage ) {
  15646. let snippet = '';
  15647. const vars = this.vars[ shaderStage ];
  15648. if ( vars !== undefined ) {
  15649. for ( const variable of vars ) {
  15650. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  15651. }
  15652. }
  15653. return snippet;
  15654. }
  15655. getUniforms( /*shaderStage*/ ) {
  15656. console.warn( 'Abstract function.' );
  15657. }
  15658. getCodes( shaderStage ) {
  15659. const codes = this.codes[ shaderStage ];
  15660. let code = '';
  15661. if ( codes !== undefined ) {
  15662. for ( const nodeCode of codes ) {
  15663. code += nodeCode.code + '\n';
  15664. }
  15665. }
  15666. return code;
  15667. }
  15668. getHash() {
  15669. return this.vertexShader + this.fragmentShader + this.computeShader;
  15670. }
  15671. setShaderStage( shaderStage ) {
  15672. this.shaderStage = shaderStage;
  15673. }
  15674. getShaderStage() {
  15675. return this.shaderStage;
  15676. }
  15677. setBuildStage( buildStage ) {
  15678. this.buildStage = buildStage;
  15679. }
  15680. getBuildStage() {
  15681. return this.buildStage;
  15682. }
  15683. buildCode() {
  15684. console.warn( 'Abstract function.' );
  15685. }
  15686. build() {
  15687. const { object, material, renderer } = this;
  15688. if ( material !== null ) {
  15689. let nodeMaterial = renderer.library.fromMaterial( material );
  15690. if ( nodeMaterial === null ) {
  15691. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  15692. nodeMaterial = new NodeMaterial();
  15693. }
  15694. nodeMaterial.build( this );
  15695. } else {
  15696. this.addFlow( 'compute', object );
  15697. }
  15698. // setup() -> stage 1: create possible new nodes and returns an output reference node
  15699. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  15700. // generate() -> stage 3: generate shader
  15701. for ( const buildStage of defaultBuildStages ) {
  15702. this.setBuildStage( buildStage );
  15703. if ( this.context.vertex && this.context.vertex.isNode ) {
  15704. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  15705. }
  15706. for ( const shaderStage of shaderStages ) {
  15707. this.setShaderStage( shaderStage );
  15708. const flowNodes = this.flowNodes[ shaderStage ];
  15709. for ( const node of flowNodes ) {
  15710. if ( buildStage === 'generate' ) {
  15711. this.flowNode( node );
  15712. } else {
  15713. node.build( this );
  15714. }
  15715. }
  15716. }
  15717. }
  15718. this.setBuildStage( null );
  15719. this.setShaderStage( null );
  15720. // stage 4: build code for a specific output
  15721. this.buildCode();
  15722. this.buildUpdateNodes();
  15723. return this;
  15724. }
  15725. getNodeUniform( uniformNode, type ) {
  15726. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  15727. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  15728. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  15729. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  15730. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  15731. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  15732. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  15733. throw new Error( `Uniform "${type}" not declared.` );
  15734. }
  15735. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  15736. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  15737. }
  15738. format( snippet, fromType, toType ) {
  15739. fromType = this.getVectorType( fromType );
  15740. toType = this.getVectorType( toType );
  15741. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  15742. return snippet;
  15743. }
  15744. const fromTypeLength = this.getTypeLength( fromType );
  15745. const toTypeLength = this.getTypeLength( toType );
  15746. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  15747. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  15748. }
  15749. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  15750. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  15751. }
  15752. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  15753. // @TODO: ignore for now
  15754. return snippet;
  15755. }
  15756. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  15757. // @TODO: ignore for now
  15758. return snippet;
  15759. }
  15760. if ( fromTypeLength === toTypeLength ) {
  15761. return `${ this.getType( toType ) }( ${ snippet } )`;
  15762. }
  15763. if ( fromTypeLength > toTypeLength ) {
  15764. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  15765. }
  15766. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  15767. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  15768. }
  15769. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  15770. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  15771. }
  15772. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  15773. // convert a number value to vector type, e.g:
  15774. // vec3( 1u ) -> vec3( float( 1u ) )
  15775. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  15776. }
  15777. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  15778. }
  15779. getSignature() {
  15780. return `// Three.js r${ REVISION } - Node System\n`;
  15781. }
  15782. }
  15783. class NodeFrame {
  15784. constructor() {
  15785. this.time = 0;
  15786. this.deltaTime = 0;
  15787. this.frameId = 0;
  15788. this.renderId = 0;
  15789. this.startTime = null;
  15790. this.updateMap = new WeakMap();
  15791. this.updateBeforeMap = new WeakMap();
  15792. this.updateAfterMap = new WeakMap();
  15793. this.renderer = null;
  15794. this.material = null;
  15795. this.camera = null;
  15796. this.object = null;
  15797. this.scene = null;
  15798. }
  15799. _getMaps( referenceMap, nodeRef ) {
  15800. let maps = referenceMap.get( nodeRef );
  15801. if ( maps === undefined ) {
  15802. maps = {
  15803. renderMap: new WeakMap(),
  15804. frameMap: new WeakMap()
  15805. };
  15806. referenceMap.set( nodeRef, maps );
  15807. }
  15808. return maps;
  15809. }
  15810. updateBeforeNode( node ) {
  15811. const updateType = node.getUpdateBeforeType();
  15812. const reference = node.updateReference( this );
  15813. if ( updateType === NodeUpdateType.FRAME ) {
  15814. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  15815. if ( frameMap.get( reference ) !== this.frameId ) {
  15816. if ( node.updateBefore( this ) !== false ) {
  15817. frameMap.set( reference, this.frameId );
  15818. }
  15819. }
  15820. } else if ( updateType === NodeUpdateType.RENDER ) {
  15821. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  15822. if ( renderMap.get( reference ) !== this.renderId ) {
  15823. if ( node.updateBefore( this ) !== false ) {
  15824. renderMap.set( reference, this.renderId );
  15825. }
  15826. }
  15827. } else if ( updateType === NodeUpdateType.OBJECT ) {
  15828. node.updateBefore( this );
  15829. }
  15830. }
  15831. updateAfterNode( node ) {
  15832. const updateType = node.getUpdateAfterType();
  15833. const reference = node.updateReference( this );
  15834. if ( updateType === NodeUpdateType.FRAME ) {
  15835. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  15836. if ( frameMap.get( reference ) !== this.frameId ) {
  15837. if ( node.updateAfter( this ) !== false ) {
  15838. frameMap.set( reference, this.frameId );
  15839. }
  15840. }
  15841. } else if ( updateType === NodeUpdateType.RENDER ) {
  15842. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  15843. if ( renderMap.get( reference ) !== this.renderId ) {
  15844. if ( node.updateAfter( this ) !== false ) {
  15845. renderMap.set( reference, this.renderId );
  15846. }
  15847. }
  15848. } else if ( updateType === NodeUpdateType.OBJECT ) {
  15849. node.updateAfter( this );
  15850. }
  15851. }
  15852. updateNode( node ) {
  15853. const updateType = node.getUpdateType();
  15854. const reference = node.updateReference( this );
  15855. if ( updateType === NodeUpdateType.FRAME ) {
  15856. const { frameMap } = this._getMaps( this.updateMap, reference );
  15857. if ( frameMap.get( reference ) !== this.frameId ) {
  15858. if ( node.update( this ) !== false ) {
  15859. frameMap.set( reference, this.frameId );
  15860. }
  15861. }
  15862. } else if ( updateType === NodeUpdateType.RENDER ) {
  15863. const { renderMap } = this._getMaps( this.updateMap, reference );
  15864. if ( renderMap.get( reference ) !== this.renderId ) {
  15865. if ( node.update( this ) !== false ) {
  15866. renderMap.set( reference, this.renderId );
  15867. }
  15868. }
  15869. } else if ( updateType === NodeUpdateType.OBJECT ) {
  15870. node.update( this );
  15871. }
  15872. }
  15873. update() {
  15874. this.frameId ++;
  15875. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  15876. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  15877. this.lastTime = performance.now();
  15878. this.time += this.deltaTime;
  15879. }
  15880. }
  15881. class NodeFunctionInput {
  15882. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  15883. this.type = type;
  15884. this.name = name;
  15885. this.count = count;
  15886. this.qualifier = qualifier;
  15887. this.isConst = isConst;
  15888. }
  15889. }
  15890. NodeFunctionInput.isNodeFunctionInput = true;
  15891. class DirectionalLightNode extends AnalyticLightNode {
  15892. static get type() {
  15893. return 'DirectionalLightNode';
  15894. }
  15895. constructor( light = null ) {
  15896. super( light );
  15897. }
  15898. setup( builder ) {
  15899. super.setup( builder );
  15900. const lightingModel = builder.context.lightingModel;
  15901. const lightColor = this.colorNode;
  15902. const lightDirection = lightTargetDirection( this.light );
  15903. const reflectedLight = builder.context.reflectedLight;
  15904. lightingModel.direct( {
  15905. lightDirection,
  15906. lightColor,
  15907. reflectedLight
  15908. }, builder.stack, builder );
  15909. }
  15910. }
  15911. const _matrix41 = /*@__PURE__*/ new Matrix4();
  15912. const _matrix42 = /*@__PURE__*/ new Matrix4();
  15913. let ltcLib = null;
  15914. class RectAreaLightNode extends AnalyticLightNode {
  15915. static get type() {
  15916. return 'RectAreaLightNode';
  15917. }
  15918. constructor( light = null ) {
  15919. super( light );
  15920. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  15921. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  15922. this.updateType = NodeUpdateType.RENDER;
  15923. }
  15924. update( frame ) {
  15925. super.update( frame );
  15926. const { light } = this;
  15927. const viewMatrix = frame.camera.matrixWorldInverse;
  15928. _matrix42.identity();
  15929. _matrix41.copy( light.matrixWorld );
  15930. _matrix41.premultiply( viewMatrix );
  15931. _matrix42.extractRotation( _matrix41 );
  15932. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  15933. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  15934. this.halfWidth.value.applyMatrix4( _matrix42 );
  15935. this.halfHeight.value.applyMatrix4( _matrix42 );
  15936. }
  15937. setup( builder ) {
  15938. super.setup( builder );
  15939. let ltc_1, ltc_2;
  15940. if ( builder.isAvailable( 'float32Filterable' ) ) {
  15941. ltc_1 = texture( ltcLib.LTC_FLOAT_1 );
  15942. ltc_2 = texture( ltcLib.LTC_FLOAT_2 );
  15943. } else {
  15944. ltc_1 = texture( ltcLib.LTC_HALF_1 );
  15945. ltc_2 = texture( ltcLib.LTC_HALF_2 );
  15946. }
  15947. const { colorNode, light } = this;
  15948. const lightingModel = builder.context.lightingModel;
  15949. const lightPosition = lightViewPosition( light );
  15950. const reflectedLight = builder.context.reflectedLight;
  15951. lightingModel.directRectArea( {
  15952. lightColor: colorNode,
  15953. lightPosition,
  15954. halfWidth: this.halfWidth,
  15955. halfHeight: this.halfHeight,
  15956. reflectedLight,
  15957. ltc_1,
  15958. ltc_2
  15959. }, builder.stack, builder );
  15960. }
  15961. static setLTC( ltc ) {
  15962. ltcLib = ltc;
  15963. }
  15964. }
  15965. class SpotLightNode extends AnalyticLightNode {
  15966. static get type() {
  15967. return 'SpotLightNode';
  15968. }
  15969. constructor( light = null ) {
  15970. super( light );
  15971. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  15972. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  15973. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  15974. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  15975. }
  15976. update( frame ) {
  15977. super.update( frame );
  15978. const { light } = this;
  15979. this.coneCosNode.value = Math.cos( light.angle );
  15980. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  15981. this.cutoffDistanceNode.value = light.distance;
  15982. this.decayExponentNode.value = light.decay;
  15983. }
  15984. getSpotAttenuation( angleCosine ) {
  15985. const { coneCosNode, penumbraCosNode } = this;
  15986. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  15987. }
  15988. setup( builder ) {
  15989. super.setup( builder );
  15990. const lightingModel = builder.context.lightingModel;
  15991. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  15992. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  15993. const lightDirection = lVector.normalize();
  15994. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  15995. const spotAttenuation = this.getSpotAttenuation( angleCos );
  15996. const lightDistance = lVector.length();
  15997. const lightAttenuation = getDistanceAttenuation( {
  15998. lightDistance,
  15999. cutoffDistance: cutoffDistanceNode,
  16000. decayExponent: decayExponentNode
  16001. } );
  16002. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  16003. if ( light.map ) {
  16004. const spotLightCoord = lightProjectionUV( light );
  16005. const projectedTexture = texture( light.map, spotLightCoord.xy ).onRenderUpdate( () => light.map );
  16006. const inSpotLightMap = spotLightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  16007. lightColor = inSpotLightMap.select( lightColor.mul( projectedTexture ), lightColor );
  16008. }
  16009. const reflectedLight = builder.context.reflectedLight;
  16010. lightingModel.direct( {
  16011. lightDirection,
  16012. lightColor,
  16013. reflectedLight
  16014. }, builder.stack, builder );
  16015. }
  16016. }
  16017. class IESSpotLightNode extends SpotLightNode {
  16018. static get type() {
  16019. return 'IESSpotLightNode';
  16020. }
  16021. getSpotAttenuation( angleCosine ) {
  16022. const iesMap = this.light.iesMap;
  16023. let spotAttenuation = null;
  16024. if ( iesMap && iesMap.isTexture === true ) {
  16025. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  16026. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  16027. } else {
  16028. spotAttenuation = super.getSpotAttenuation( angleCosine );
  16029. }
  16030. return spotAttenuation;
  16031. }
  16032. }
  16033. class AmbientLightNode extends AnalyticLightNode {
  16034. static get type() {
  16035. return 'AmbientLightNode';
  16036. }
  16037. constructor( light = null ) {
  16038. super( light );
  16039. }
  16040. setup( { context } ) {
  16041. context.irradiance.addAssign( this.colorNode );
  16042. }
  16043. }
  16044. class HemisphereLightNode extends AnalyticLightNode {
  16045. static get type() {
  16046. return 'HemisphereLightNode';
  16047. }
  16048. constructor( light = null ) {
  16049. super( light );
  16050. this.lightPositionNode = lightPosition( light );
  16051. this.lightDirectionNode = this.lightPositionNode.normalize();
  16052. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  16053. }
  16054. update( frame ) {
  16055. const { light } = this;
  16056. super.update( frame );
  16057. this.lightPositionNode.object3d = light;
  16058. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  16059. }
  16060. setup( builder ) {
  16061. const { colorNode, groundColorNode, lightDirectionNode } = this;
  16062. const dotNL = normalView.dot( lightDirectionNode );
  16063. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  16064. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  16065. builder.context.irradiance.addAssign( irradiance );
  16066. }
  16067. }
  16068. class LightProbeNode extends AnalyticLightNode {
  16069. static get type() {
  16070. return 'LightProbeNode';
  16071. }
  16072. constructor( light = null ) {
  16073. super( light );
  16074. const array = [];
  16075. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  16076. this.lightProbe = uniformArray( array );
  16077. }
  16078. update( frame ) {
  16079. const { light } = this;
  16080. super.update( frame );
  16081. //
  16082. for ( let i = 0; i < 9; i ++ ) {
  16083. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  16084. }
  16085. }
  16086. setup( builder ) {
  16087. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  16088. builder.context.irradiance.addAssign( irradiance );
  16089. }
  16090. }
  16091. class NodeParser {
  16092. parseFunction( /*source*/ ) {
  16093. console.warn( 'Abstract function.' );
  16094. }
  16095. }
  16096. class NodeFunction {
  16097. constructor( type, inputs, name = '', precision = '' ) {
  16098. this.type = type;
  16099. this.inputs = inputs;
  16100. this.name = name;
  16101. this.precision = precision;
  16102. }
  16103. getCode( /*name = this.name*/ ) {
  16104. console.warn( 'Abstract function.' );
  16105. }
  16106. }
  16107. NodeFunction.isNodeFunction = true;
  16108. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  16109. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  16110. const pragmaMain = '#pragma main';
  16111. const parse$1 = ( source ) => {
  16112. source = source.trim();
  16113. const pragmaMainIndex = source.indexOf( pragmaMain );
  16114. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  16115. const declaration = mainCode.match( declarationRegexp$1 );
  16116. if ( declaration !== null && declaration.length === 5 ) {
  16117. // tokenizer
  16118. const inputsCode = declaration[ 4 ];
  16119. const propsMatches = [];
  16120. let nameMatch = null;
  16121. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  16122. propsMatches.push( nameMatch );
  16123. }
  16124. // parser
  16125. const inputs = [];
  16126. let i = 0;
  16127. while ( i < propsMatches.length ) {
  16128. const isConst = propsMatches[ i ][ 0 ] === 'const';
  16129. if ( isConst === true ) {
  16130. i ++;
  16131. }
  16132. let qualifier = propsMatches[ i ][ 0 ];
  16133. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  16134. i ++;
  16135. } else {
  16136. qualifier = '';
  16137. }
  16138. const type = propsMatches[ i ++ ][ 0 ];
  16139. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  16140. if ( Number.isNaN( count ) === false ) i ++;
  16141. else count = null;
  16142. const name = propsMatches[ i ++ ][ 0 ];
  16143. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  16144. }
  16145. //
  16146. const blockCode = mainCode.substring( declaration[ 0 ].length );
  16147. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  16148. const type = declaration[ 2 ];
  16149. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  16150. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  16151. return {
  16152. type,
  16153. inputs,
  16154. name,
  16155. precision,
  16156. inputsCode,
  16157. blockCode,
  16158. headerCode
  16159. };
  16160. } else {
  16161. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  16162. }
  16163. };
  16164. class GLSLNodeFunction extends NodeFunction {
  16165. constructor( source ) {
  16166. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  16167. super( type, inputs, name, precision );
  16168. this.inputsCode = inputsCode;
  16169. this.blockCode = blockCode;
  16170. this.headerCode = headerCode;
  16171. }
  16172. getCode( name = this.name ) {
  16173. let code;
  16174. const blockCode = this.blockCode;
  16175. if ( blockCode !== '' ) {
  16176. const { type, inputsCode, headerCode, precision } = this;
  16177. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  16178. if ( precision !== '' ) {
  16179. declarationCode = `${ precision } ${ declarationCode }`;
  16180. }
  16181. code = headerCode + declarationCode + blockCode;
  16182. } else {
  16183. // interface function
  16184. code = '';
  16185. }
  16186. return code;
  16187. }
  16188. }
  16189. class GLSLNodeParser extends NodeParser {
  16190. parseFunction( source ) {
  16191. return new GLSLNodeFunction( source );
  16192. }
  16193. }
  16194. const outputNodeMap = new WeakMap();
  16195. class Nodes extends DataMap {
  16196. constructor( renderer, backend ) {
  16197. super();
  16198. this.renderer = renderer;
  16199. this.backend = backend;
  16200. this.nodeFrame = new NodeFrame();
  16201. this.nodeBuilderCache = new Map();
  16202. this.callHashCache = new ChainMap();
  16203. this.groupsData = new ChainMap();
  16204. }
  16205. updateGroup( nodeUniformsGroup ) {
  16206. const groupNode = nodeUniformsGroup.groupNode;
  16207. const name = groupNode.name;
  16208. // objectGroup is every updated
  16209. if ( name === objectGroup.name ) return true;
  16210. // renderGroup is updated once per render/compute call
  16211. if ( name === renderGroup.name ) {
  16212. const uniformsGroupData = this.get( nodeUniformsGroup );
  16213. const renderId = this.nodeFrame.renderId;
  16214. if ( uniformsGroupData.renderId !== renderId ) {
  16215. uniformsGroupData.renderId = renderId;
  16216. return true;
  16217. }
  16218. return false;
  16219. }
  16220. // frameGroup is updated once per frame
  16221. if ( name === frameGroup.name ) {
  16222. const uniformsGroupData = this.get( nodeUniformsGroup );
  16223. const frameId = this.nodeFrame.frameId;
  16224. if ( uniformsGroupData.frameId !== frameId ) {
  16225. uniformsGroupData.frameId = frameId;
  16226. return true;
  16227. }
  16228. return false;
  16229. }
  16230. // other groups are updated just when groupNode.needsUpdate is true
  16231. const groupChain = [ groupNode, nodeUniformsGroup ];
  16232. let groupData = this.groupsData.get( groupChain );
  16233. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  16234. if ( groupData.version !== groupNode.version ) {
  16235. groupData.version = groupNode.version;
  16236. return true;
  16237. }
  16238. return false;
  16239. }
  16240. getForRenderCacheKey( renderObject ) {
  16241. return renderObject.initialCacheKey;
  16242. }
  16243. getForRender( renderObject ) {
  16244. const renderObjectData = this.get( renderObject );
  16245. let nodeBuilderState = renderObjectData.nodeBuilderState;
  16246. if ( nodeBuilderState === undefined ) {
  16247. const { nodeBuilderCache } = this;
  16248. const cacheKey = this.getForRenderCacheKey( renderObject );
  16249. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  16250. if ( nodeBuilderState === undefined ) {
  16251. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  16252. nodeBuilder.scene = renderObject.scene;
  16253. nodeBuilder.material = renderObject.material;
  16254. nodeBuilder.camera = renderObject.camera;
  16255. nodeBuilder.context.material = renderObject.material;
  16256. nodeBuilder.lightsNode = renderObject.lightsNode;
  16257. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  16258. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  16259. nodeBuilder.clippingContext = renderObject.clippingContext;
  16260. nodeBuilder.build();
  16261. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  16262. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  16263. }
  16264. nodeBuilderState.usedTimes ++;
  16265. renderObjectData.nodeBuilderState = nodeBuilderState;
  16266. }
  16267. return nodeBuilderState;
  16268. }
  16269. delete( object ) {
  16270. if ( object.isRenderObject ) {
  16271. const nodeBuilderState = this.get( object ).nodeBuilderState;
  16272. nodeBuilderState.usedTimes --;
  16273. if ( nodeBuilderState.usedTimes === 0 ) {
  16274. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  16275. }
  16276. }
  16277. return super.delete( object );
  16278. }
  16279. getForCompute( computeNode ) {
  16280. const computeData = this.get( computeNode );
  16281. let nodeBuilderState = computeData.nodeBuilderState;
  16282. if ( nodeBuilderState === undefined ) {
  16283. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  16284. nodeBuilder.build();
  16285. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  16286. computeData.nodeBuilderState = nodeBuilderState;
  16287. }
  16288. return nodeBuilderState;
  16289. }
  16290. _createNodeBuilderState( nodeBuilder ) {
  16291. return new NodeBuilderState(
  16292. nodeBuilder.vertexShader,
  16293. nodeBuilder.fragmentShader,
  16294. nodeBuilder.computeShader,
  16295. nodeBuilder.getAttributesArray(),
  16296. nodeBuilder.getBindings(),
  16297. nodeBuilder.updateNodes,
  16298. nodeBuilder.updateBeforeNodes,
  16299. nodeBuilder.updateAfterNodes,
  16300. nodeBuilder.monitor,
  16301. nodeBuilder.transforms
  16302. );
  16303. }
  16304. getEnvironmentNode( scene ) {
  16305. return scene.environmentNode || this.get( scene ).environmentNode || null;
  16306. }
  16307. getBackgroundNode( scene ) {
  16308. return scene.backgroundNode || this.get( scene ).backgroundNode || null;
  16309. }
  16310. getFogNode( scene ) {
  16311. return scene.fogNode || this.get( scene ).fogNode || null;
  16312. }
  16313. getCacheKey( scene, lightsNode ) {
  16314. const chain = [ scene, lightsNode ];
  16315. const callId = this.renderer.info.calls;
  16316. let cacheKeyData = this.callHashCache.get( chain );
  16317. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  16318. const environmentNode = this.getEnvironmentNode( scene );
  16319. const fogNode = this.getFogNode( scene );
  16320. const values = [];
  16321. if ( lightsNode ) values.push( lightsNode.getCacheKey( true ) );
  16322. if ( environmentNode ) values.push( environmentNode.getCacheKey() );
  16323. if ( fogNode ) values.push( fogNode.getCacheKey() );
  16324. values.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  16325. cacheKeyData = {
  16326. callId,
  16327. cacheKey: hashArray( values )
  16328. };
  16329. this.callHashCache.set( chain, cacheKeyData );
  16330. }
  16331. return cacheKeyData.cacheKey;
  16332. }
  16333. updateScene( scene ) {
  16334. this.updateEnvironment( scene );
  16335. this.updateFog( scene );
  16336. this.updateBackground( scene );
  16337. }
  16338. get isToneMappingState() {
  16339. return this.renderer.getRenderTarget() ? false : true;
  16340. }
  16341. updateBackground( scene ) {
  16342. const sceneData = this.get( scene );
  16343. const background = scene.background;
  16344. if ( background ) {
  16345. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  16346. if ( sceneData.background !== background || forceUpdate ) {
  16347. let backgroundNode = null;
  16348. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  16349. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  16350. backgroundNode = pmremTexture( background );
  16351. } else {
  16352. let envMap;
  16353. if ( background.isCubeTexture === true ) {
  16354. envMap = cubeTexture( background );
  16355. } else {
  16356. envMap = texture( background );
  16357. }
  16358. backgroundNode = cubeMapNode( envMap );
  16359. }
  16360. } else if ( background.isTexture === true ) {
  16361. backgroundNode = texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  16362. } else if ( background.isColor !== true ) {
  16363. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  16364. }
  16365. sceneData.backgroundNode = backgroundNode;
  16366. sceneData.background = background;
  16367. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  16368. }
  16369. } else if ( sceneData.backgroundNode ) {
  16370. delete sceneData.backgroundNode;
  16371. delete sceneData.background;
  16372. }
  16373. }
  16374. updateFog( scene ) {
  16375. const sceneData = this.get( scene );
  16376. const fog = scene.fog;
  16377. if ( fog ) {
  16378. if ( sceneData.fog !== fog ) {
  16379. let fogNode = null;
  16380. if ( fog.isFogExp2 ) {
  16381. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  16382. const density = reference( 'density', 'float', fog ).setGroup( renderGroup );
  16383. fogNode = densityFog( color, density );
  16384. } else if ( fog.isFog ) {
  16385. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  16386. const near = reference( 'near', 'float', fog ).setGroup( renderGroup );
  16387. const far = reference( 'far', 'float', fog ).setGroup( renderGroup );
  16388. fogNode = rangeFog( color, near, far );
  16389. } else {
  16390. console.error( 'WebGPUNodes: Unsupported fog configuration.', fog );
  16391. }
  16392. sceneData.fogNode = fogNode;
  16393. sceneData.fog = fog;
  16394. }
  16395. } else {
  16396. delete sceneData.fogNode;
  16397. delete sceneData.fog;
  16398. }
  16399. }
  16400. updateEnvironment( scene ) {
  16401. const sceneData = this.get( scene );
  16402. const environment = scene.environment;
  16403. if ( environment ) {
  16404. if ( sceneData.environment !== environment ) {
  16405. let environmentNode = null;
  16406. if ( environment.isCubeTexture === true ) {
  16407. environmentNode = cubeTexture( environment );
  16408. } else if ( environment.isTexture === true ) {
  16409. environmentNode = texture( environment );
  16410. } else {
  16411. console.error( 'Nodes: Unsupported environment configuration.', environment );
  16412. }
  16413. sceneData.environmentNode = environmentNode;
  16414. sceneData.environment = environment;
  16415. }
  16416. } else if ( sceneData.environmentNode ) {
  16417. delete sceneData.environmentNode;
  16418. delete sceneData.environment;
  16419. }
  16420. }
  16421. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  16422. const nodeFrame = this.nodeFrame;
  16423. nodeFrame.renderer = renderer;
  16424. nodeFrame.scene = scene;
  16425. nodeFrame.object = object;
  16426. nodeFrame.camera = camera;
  16427. nodeFrame.material = material;
  16428. return nodeFrame;
  16429. }
  16430. getNodeFrameForRender( renderObject ) {
  16431. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  16432. }
  16433. getOutputCacheKey() {
  16434. const renderer = this.renderer;
  16435. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  16436. }
  16437. hasOutputChange( outputTarget ) {
  16438. const cacheKey = outputNodeMap.get( outputTarget );
  16439. return cacheKey !== this.getOutputCacheKey();
  16440. }
  16441. getOutputNode( outputTexture ) {
  16442. const renderer = this.renderer;
  16443. const cacheKey = this.getOutputCacheKey();
  16444. const output = texture( outputTexture, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  16445. outputNodeMap.set( outputTexture, cacheKey );
  16446. return output;
  16447. }
  16448. updateBefore( renderObject ) {
  16449. const nodeBuilder = renderObject.getNodeBuilderState();
  16450. for ( const node of nodeBuilder.updateBeforeNodes ) {
  16451. // update frame state for each node
  16452. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  16453. }
  16454. }
  16455. updateAfter( renderObject ) {
  16456. const nodeBuilder = renderObject.getNodeBuilderState();
  16457. for ( const node of nodeBuilder.updateAfterNodes ) {
  16458. // update frame state for each node
  16459. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  16460. }
  16461. }
  16462. updateForCompute( computeNode ) {
  16463. const nodeFrame = this.getNodeFrame();
  16464. const nodeBuilder = this.getForCompute( computeNode );
  16465. for ( const node of nodeBuilder.updateNodes ) {
  16466. nodeFrame.updateNode( node );
  16467. }
  16468. }
  16469. updateForRender( renderObject ) {
  16470. const nodeFrame = this.getNodeFrameForRender( renderObject );
  16471. const nodeBuilder = renderObject.getNodeBuilderState();
  16472. for ( const node of nodeBuilder.updateNodes ) {
  16473. nodeFrame.updateNode( node );
  16474. }
  16475. }
  16476. needsRefresh( renderObject ) {
  16477. const nodeFrame = this.getNodeFrameForRender( renderObject );
  16478. const monitor = renderObject.getMonitor();
  16479. return monitor.needsRefresh( renderObject, nodeFrame );
  16480. }
  16481. dispose() {
  16482. super.dispose();
  16483. this.nodeFrame = new NodeFrame();
  16484. this.nodeBuilderCache = new Map();
  16485. }
  16486. }
  16487. const _plane = /*@__PURE__*/ new Plane();
  16488. class ClippingContext {
  16489. constructor( parentContext = null ) {
  16490. this.version = 0;
  16491. this.clipIntersection = null;
  16492. this.cacheKey = '';
  16493. if ( parentContext === null ) {
  16494. this.intersectionPlanes = [];
  16495. this.unionPlanes = [];
  16496. this.viewNormalMatrix = new Matrix3();
  16497. this.clippingGroupContexts = new WeakMap();
  16498. this.shadowPass = false;
  16499. } else {
  16500. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  16501. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  16502. this.shadowPass = parentContext.shadowPass;
  16503. this.viewMatrix = parentContext.viewMatrix;
  16504. }
  16505. this.parentVersion = null;
  16506. }
  16507. projectPlanes( source, destination, offset ) {
  16508. const l = source.length;
  16509. for ( let i = 0; i < l; i ++ ) {
  16510. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  16511. const v = destination[ offset + i ];
  16512. const normal = _plane.normal;
  16513. v.x = - normal.x;
  16514. v.y = - normal.y;
  16515. v.z = - normal.z;
  16516. v.w = _plane.constant;
  16517. }
  16518. }
  16519. updateGlobal( scene, camera ) {
  16520. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowNodeMaterial );
  16521. this.viewMatrix = camera.matrixWorldInverse;
  16522. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  16523. }
  16524. update( parentContext, clippingGroup ) {
  16525. let update = false;
  16526. if ( parentContext.version !== this.parentVersion ) {
  16527. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  16528. this.unionPlanes = Array.from( parentContext.unionPlanes );
  16529. this.parentVersion = parentContext.version;
  16530. }
  16531. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  16532. this.clipIntersection = clippingGroup.clipIntersection;
  16533. if ( this.clipIntersection ) {
  16534. this.unionPlanes.length = parentContext.unionPlanes.length;
  16535. } else {
  16536. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  16537. }
  16538. }
  16539. const srcClippingPlanes = clippingGroup.clippingPlanes;
  16540. const l = srcClippingPlanes.length;
  16541. let dstClippingPlanes;
  16542. let offset;
  16543. if ( this.clipIntersection ) {
  16544. dstClippingPlanes = this.intersectionPlanes;
  16545. offset = parentContext.intersectionPlanes.length;
  16546. } else {
  16547. dstClippingPlanes = this.unionPlanes;
  16548. offset = parentContext.unionPlanes.length;
  16549. }
  16550. if ( dstClippingPlanes.length !== offset + l ) {
  16551. dstClippingPlanes.length = offset + l;
  16552. for ( let i = 0; i < l; i ++ ) {
  16553. dstClippingPlanes[ offset + i ] = new Vector4();
  16554. }
  16555. update = true;
  16556. }
  16557. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  16558. if ( update ) {
  16559. this.version ++;
  16560. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  16561. }
  16562. }
  16563. getGroupContext( clippingGroup ) {
  16564. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  16565. let context = this.clippingGroupContexts.get( clippingGroup );
  16566. if ( context === undefined ) {
  16567. context = new ClippingContext( this );
  16568. this.clippingGroupContexts.set( clippingGroup, context );
  16569. }
  16570. context.update( this, clippingGroup );
  16571. return context;
  16572. }
  16573. get unionClippingCount() {
  16574. return this.unionPlanes.length;
  16575. }
  16576. }
  16577. class RenderBundle {
  16578. constructor( scene, camera ) {
  16579. this.scene = scene;
  16580. this.camera = camera;
  16581. }
  16582. clone() {
  16583. return Object.assign( new this.constructor(), this );
  16584. }
  16585. }
  16586. class RenderBundles {
  16587. constructor() {
  16588. this.lists = new ChainMap();
  16589. }
  16590. get( scene, camera ) {
  16591. const lists = this.lists;
  16592. const keys = [ scene, camera ];
  16593. let list = lists.get( keys );
  16594. if ( list === undefined ) {
  16595. list = new RenderBundle( scene, camera );
  16596. lists.set( keys, list );
  16597. }
  16598. return list;
  16599. }
  16600. dispose() {
  16601. this.lists = new ChainMap();
  16602. }
  16603. }
  16604. class NodeLibrary {
  16605. constructor() {
  16606. this.lightNodes = new WeakMap();
  16607. this.materialNodes = new Map();
  16608. this.toneMappingNodes = new Map();
  16609. }
  16610. fromMaterial( material ) {
  16611. if ( material.isNodeMaterial ) return material;
  16612. let nodeMaterial = null;
  16613. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  16614. if ( nodeMaterialClass !== null ) {
  16615. nodeMaterial = new nodeMaterialClass();
  16616. for ( const key in material ) {
  16617. nodeMaterial[ key ] = material[ key ];
  16618. }
  16619. }
  16620. return nodeMaterial;
  16621. }
  16622. addToneMapping( toneMappingNode, toneMapping ) {
  16623. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  16624. }
  16625. getToneMappingFunction( toneMapping ) {
  16626. return this.toneMappingNodes.get( toneMapping ) || null;
  16627. }
  16628. getMaterialNodeClass( materialType ) {
  16629. return this.materialNodes.get( materialType ) || null;
  16630. }
  16631. addMaterial( materialNodeClass, materialClassType ) {
  16632. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  16633. }
  16634. getLightNodeClass( light ) {
  16635. return this.lightNodes.get( light ) || null;
  16636. }
  16637. addLight( lightNodeClass, lightClass ) {
  16638. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  16639. }
  16640. addType( nodeClass, type, library ) {
  16641. if ( library.has( type ) ) {
  16642. console.warn( `Redefinition of node ${ type }` );
  16643. return;
  16644. }
  16645. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  16646. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  16647. library.set( type, nodeClass );
  16648. }
  16649. addClass( nodeClass, baseClass, library ) {
  16650. if ( library.has( baseClass ) ) {
  16651. console.warn( `Redefinition of node ${ baseClass.name }` );
  16652. return;
  16653. }
  16654. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  16655. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  16656. library.set( baseClass, nodeClass );
  16657. }
  16658. }
  16659. const _defaultLights = /*@__PURE__*/ new LightsNode();
  16660. class Lighting extends ChainMap {
  16661. constructor() {
  16662. super();
  16663. }
  16664. createNode( lights = [] ) {
  16665. return new LightsNode().setLights( lights );
  16666. }
  16667. getNode( scene, camera ) {
  16668. // ignore post-processing
  16669. if ( scene.isQuadMesh ) return _defaultLights;
  16670. // tiled lighting
  16671. const keys = [ scene, camera ];
  16672. let node = this.get( keys );
  16673. if ( node === undefined ) {
  16674. node = this.createNode();
  16675. this.set( keys, node );
  16676. }
  16677. return node;
  16678. }
  16679. }
  16680. const _scene = /*@__PURE__*/ new Scene();
  16681. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  16682. const _screen = /*@__PURE__*/ new Vector4();
  16683. const _frustum = /*@__PURE__*/ new Frustum();
  16684. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  16685. const _vector4 = /*@__PURE__*/ new Vector4();
  16686. class Renderer {
  16687. constructor( backend, parameters = {} ) {
  16688. this.isRenderer = true;
  16689. //
  16690. const {
  16691. logarithmicDepthBuffer = false,
  16692. alpha = true,
  16693. depth = true,
  16694. stencil = false,
  16695. antialias = false,
  16696. samples = 0,
  16697. getFallback = null
  16698. } = parameters;
  16699. // public
  16700. this.domElement = backend.getDomElement();
  16701. this.backend = backend;
  16702. this.samples = samples || ( antialias === true ) ? 4 : 0;
  16703. this.autoClear = true;
  16704. this.autoClearColor = true;
  16705. this.autoClearDepth = true;
  16706. this.autoClearStencil = true;
  16707. this.alpha = alpha;
  16708. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  16709. this.outputColorSpace = SRGBColorSpace;
  16710. this.toneMapping = NoToneMapping;
  16711. this.toneMappingExposure = 1.0;
  16712. this.sortObjects = true;
  16713. this.depth = depth;
  16714. this.stencil = stencil;
  16715. this.info = new Info();
  16716. this.nodes = {
  16717. modelViewMatrix: null,
  16718. modelNormalViewMatrix: null
  16719. };
  16720. this.library = new NodeLibrary();
  16721. this.lighting = new Lighting();
  16722. // internals
  16723. this._getFallback = getFallback;
  16724. this._pixelRatio = 1;
  16725. this._width = this.domElement.width;
  16726. this._height = this.domElement.height;
  16727. this._viewport = new Vector4( 0, 0, this._width, this._height );
  16728. this._scissor = new Vector4( 0, 0, this._width, this._height );
  16729. this._scissorTest = false;
  16730. this._attributes = null;
  16731. this._geometries = null;
  16732. this._nodes = null;
  16733. this._animation = null;
  16734. this._bindings = null;
  16735. this._objects = null;
  16736. this._pipelines = null;
  16737. this._bundles = null;
  16738. this._renderLists = null;
  16739. this._renderContexts = null;
  16740. this._textures = null;
  16741. this._background = null;
  16742. this._quad = new QuadMesh( new NodeMaterial() );
  16743. this._quad.material.type = 'Renderer_output';
  16744. this._currentRenderContext = null;
  16745. this._opaqueSort = null;
  16746. this._transparentSort = null;
  16747. this._frameBufferTarget = null;
  16748. const alphaClear = this.alpha === true ? 0 : 1;
  16749. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  16750. this._clearDepth = 1;
  16751. this._clearStencil = 0;
  16752. this._renderTarget = null;
  16753. this._activeCubeFace = 0;
  16754. this._activeMipmapLevel = 0;
  16755. this._mrt = null;
  16756. this._renderObjectFunction = null;
  16757. this._currentRenderObjectFunction = null;
  16758. this._currentRenderBundle = null;
  16759. this._handleObjectFunction = this._renderObjectDirect;
  16760. this._isDeviceLost = false;
  16761. this.onDeviceLost = this._onDeviceLost;
  16762. this._initialized = false;
  16763. this._initPromise = null;
  16764. this._compilationPromises = null;
  16765. this.transparent = true;
  16766. this.opaque = true;
  16767. this.shadowMap = {
  16768. enabled: false,
  16769. type: PCFShadowMap
  16770. };
  16771. this.xr = {
  16772. enabled: false
  16773. };
  16774. this.debug = {
  16775. checkShaderErrors: true,
  16776. onShaderError: null,
  16777. getShaderAsync: async ( scene, camera, object ) => {
  16778. await this.compileAsync( scene, camera );
  16779. const renderList = this._renderLists.get( scene, camera );
  16780. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  16781. const material = scene.overrideMaterial || object.material;
  16782. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  16783. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  16784. return { fragmentShader, vertexShader };
  16785. }
  16786. };
  16787. }
  16788. async init() {
  16789. if ( this._initialized ) {
  16790. throw new Error( 'Renderer: Backend has already been initialized.' );
  16791. }
  16792. if ( this._initPromise !== null ) {
  16793. return this._initPromise;
  16794. }
  16795. this._initPromise = new Promise( async ( resolve, reject ) => {
  16796. let backend = this.backend;
  16797. try {
  16798. await backend.init( this );
  16799. } catch ( error ) {
  16800. if ( this._getFallback !== null ) {
  16801. // try the fallback
  16802. try {
  16803. this.backend = backend = this._getFallback( error );
  16804. await backend.init( this );
  16805. } catch ( error ) {
  16806. reject( error );
  16807. return;
  16808. }
  16809. } else {
  16810. reject( error );
  16811. return;
  16812. }
  16813. }
  16814. this._nodes = new Nodes( this, backend );
  16815. this._animation = new Animation( this._nodes, this.info );
  16816. this._attributes = new Attributes( backend );
  16817. this._background = new Background( this, this._nodes );
  16818. this._geometries = new Geometries( this._attributes, this.info );
  16819. this._textures = new Textures( this, backend, this.info );
  16820. this._pipelines = new Pipelines( backend, this._nodes );
  16821. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  16822. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  16823. this._renderLists = new RenderLists( this.lighting );
  16824. this._bundles = new RenderBundles();
  16825. this._renderContexts = new RenderContexts();
  16826. //
  16827. this._animation.start();
  16828. this._initialized = true;
  16829. resolve();
  16830. } );
  16831. return this._initPromise;
  16832. }
  16833. get coordinateSystem() {
  16834. return this.backend.coordinateSystem;
  16835. }
  16836. async compileAsync( scene, camera, targetScene = null ) {
  16837. if ( this._isDeviceLost === true ) return;
  16838. if ( this._initialized === false ) await this.init();
  16839. // preserve render tree
  16840. const nodeFrame = this._nodes.nodeFrame;
  16841. const previousRenderId = nodeFrame.renderId;
  16842. const previousRenderContext = this._currentRenderContext;
  16843. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  16844. const previousCompilationPromises = this._compilationPromises;
  16845. //
  16846. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  16847. if ( targetScene === null ) targetScene = scene;
  16848. const renderTarget = this._renderTarget;
  16849. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  16850. const activeMipmapLevel = this._activeMipmapLevel;
  16851. const compilationPromises = [];
  16852. this._currentRenderContext = renderContext;
  16853. this._currentRenderObjectFunction = this.renderObject;
  16854. this._handleObjectFunction = this._createObjectPipeline;
  16855. this._compilationPromises = compilationPromises;
  16856. nodeFrame.renderId ++;
  16857. //
  16858. nodeFrame.update();
  16859. //
  16860. renderContext.depth = this.depth;
  16861. renderContext.stencil = this.stencil;
  16862. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  16863. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  16864. //
  16865. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  16866. //
  16867. const renderList = this._renderLists.get( scene, camera );
  16868. renderList.begin();
  16869. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  16870. // include lights from target scene
  16871. if ( targetScene !== scene ) {
  16872. targetScene.traverseVisible( function ( object ) {
  16873. if ( object.isLight && object.layers.test( camera.layers ) ) {
  16874. renderList.pushLight( object );
  16875. }
  16876. } );
  16877. }
  16878. renderList.finish();
  16879. //
  16880. if ( renderTarget !== null ) {
  16881. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  16882. const renderTargetData = this._textures.get( renderTarget );
  16883. renderContext.textures = renderTargetData.textures;
  16884. renderContext.depthTexture = renderTargetData.depthTexture;
  16885. } else {
  16886. renderContext.textures = null;
  16887. renderContext.depthTexture = null;
  16888. }
  16889. //
  16890. this._nodes.updateScene( sceneRef );
  16891. //
  16892. this._background.update( sceneRef, renderList, renderContext );
  16893. // process render lists
  16894. const opaqueObjects = renderList.opaque;
  16895. const transparentObjects = renderList.transparent;
  16896. const transparentDoublePassObjects = renderList.transparentDoublePass;
  16897. const lightsNode = renderList.lightsNode;
  16898. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  16899. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  16900. // restore render tree
  16901. nodeFrame.renderId = previousRenderId;
  16902. this._currentRenderContext = previousRenderContext;
  16903. this._currentRenderObjectFunction = previousRenderObjectFunction;
  16904. this._compilationPromises = previousCompilationPromises;
  16905. this._handleObjectFunction = this._renderObjectDirect;
  16906. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  16907. await Promise.all( compilationPromises );
  16908. }
  16909. async renderAsync( scene, camera ) {
  16910. if ( this._initialized === false ) await this.init();
  16911. const renderContext = this._renderScene( scene, camera );
  16912. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  16913. }
  16914. async waitForGPU() {
  16915. await this.backend.waitForGPU();
  16916. }
  16917. setMRT( mrt ) {
  16918. this._mrt = mrt;
  16919. return this;
  16920. }
  16921. getMRT() {
  16922. return this._mrt;
  16923. }
  16924. _onDeviceLost( info ) {
  16925. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  16926. if ( info.reason ) {
  16927. errorMessage += `\nReason: ${info.reason}`;
  16928. }
  16929. console.error( errorMessage );
  16930. this._isDeviceLost = true;
  16931. }
  16932. _renderBundle( bundle, sceneRef, lightsNode ) {
  16933. const { bundleGroup, camera, renderList } = bundle;
  16934. const renderContext = this._currentRenderContext;
  16935. //
  16936. const renderBundle = this._bundles.get( bundleGroup, camera );
  16937. const renderBundleData = this.backend.get( renderBundle );
  16938. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  16939. //
  16940. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  16941. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  16942. renderBundleData.renderContexts.add( renderContext );
  16943. if ( renderBundleNeedsUpdate ) {
  16944. this.backend.beginBundle( renderContext );
  16945. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  16946. renderBundleData.renderObjects = [];
  16947. }
  16948. this._currentRenderBundle = renderBundle;
  16949. const opaqueObjects = renderList.opaque;
  16950. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  16951. this._currentRenderBundle = null;
  16952. //
  16953. this.backend.finishBundle( renderContext, renderBundle );
  16954. renderBundleData.version = bundleGroup.version;
  16955. } else {
  16956. const { renderObjects } = renderBundleData;
  16957. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  16958. const renderObject = renderObjects[ i ];
  16959. if ( this._nodes.needsRefresh( renderObject ) ) {
  16960. this._nodes.updateBefore( renderObject );
  16961. this._nodes.updateForRender( renderObject );
  16962. this._bindings.updateForRender( renderObject );
  16963. this._nodes.updateAfter( renderObject );
  16964. }
  16965. }
  16966. }
  16967. this.backend.addBundle( renderContext, renderBundle );
  16968. }
  16969. render( scene, camera ) {
  16970. if ( this._initialized === false ) {
  16971. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  16972. return this.renderAsync( scene, camera );
  16973. }
  16974. this._renderScene( scene, camera );
  16975. }
  16976. _getFrameBufferTarget() {
  16977. const { currentToneMapping, currentColorSpace } = this;
  16978. const useToneMapping = currentToneMapping !== NoToneMapping;
  16979. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  16980. if ( useToneMapping === false && useColorSpace === false ) return null;
  16981. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  16982. const { depth, stencil } = this;
  16983. let frameBufferTarget = this._frameBufferTarget;
  16984. if ( frameBufferTarget === null ) {
  16985. frameBufferTarget = new RenderTarget( width, height, {
  16986. depthBuffer: depth,
  16987. stencilBuffer: stencil,
  16988. type: HalfFloatType, // FloatType
  16989. format: RGBAFormat,
  16990. colorSpace: LinearSRGBColorSpace,
  16991. generateMipmaps: false,
  16992. minFilter: LinearFilter,
  16993. magFilter: LinearFilter,
  16994. samples: this.samples
  16995. } );
  16996. frameBufferTarget.isPostProcessingRenderTarget = true;
  16997. this._frameBufferTarget = frameBufferTarget;
  16998. }
  16999. frameBufferTarget.depthBuffer = depth;
  17000. frameBufferTarget.stencilBuffer = stencil;
  17001. frameBufferTarget.setSize( width, height );
  17002. frameBufferTarget.viewport.copy( this._viewport );
  17003. frameBufferTarget.scissor.copy( this._scissor );
  17004. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  17005. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  17006. frameBufferTarget.scissorTest = this._scissorTest;
  17007. return frameBufferTarget;
  17008. }
  17009. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  17010. if ( this._isDeviceLost === true ) return;
  17011. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  17012. // preserve render tree
  17013. const nodeFrame = this._nodes.nodeFrame;
  17014. const previousRenderId = nodeFrame.renderId;
  17015. const previousRenderContext = this._currentRenderContext;
  17016. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  17017. //
  17018. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  17019. const outputRenderTarget = this._renderTarget;
  17020. const activeCubeFace = this._activeCubeFace;
  17021. const activeMipmapLevel = this._activeMipmapLevel;
  17022. //
  17023. let renderTarget;
  17024. if ( frameBufferTarget !== null ) {
  17025. renderTarget = frameBufferTarget;
  17026. this.setRenderTarget( renderTarget );
  17027. } else {
  17028. renderTarget = outputRenderTarget;
  17029. }
  17030. //
  17031. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  17032. this._currentRenderContext = renderContext;
  17033. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  17034. //
  17035. this.info.calls ++;
  17036. this.info.render.calls ++;
  17037. this.info.render.frameCalls ++;
  17038. nodeFrame.renderId = this.info.calls;
  17039. //
  17040. const coordinateSystem = this.coordinateSystem;
  17041. if ( camera.coordinateSystem !== coordinateSystem ) {
  17042. camera.coordinateSystem = coordinateSystem;
  17043. camera.updateProjectionMatrix();
  17044. }
  17045. //
  17046. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  17047. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  17048. //
  17049. let viewport = this._viewport;
  17050. let scissor = this._scissor;
  17051. let pixelRatio = this._pixelRatio;
  17052. if ( renderTarget !== null ) {
  17053. viewport = renderTarget.viewport;
  17054. scissor = renderTarget.scissor;
  17055. pixelRatio = 1;
  17056. }
  17057. this.getDrawingBufferSize( _drawingBufferSize );
  17058. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  17059. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  17060. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  17061. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  17062. renderContext.viewportValue.width >>= activeMipmapLevel;
  17063. renderContext.viewportValue.height >>= activeMipmapLevel;
  17064. renderContext.viewportValue.minDepth = minDepth;
  17065. renderContext.viewportValue.maxDepth = maxDepth;
  17066. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  17067. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  17068. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  17069. renderContext.scissorValue.width >>= activeMipmapLevel;
  17070. renderContext.scissorValue.height >>= activeMipmapLevel;
  17071. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  17072. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  17073. //
  17074. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  17075. //
  17076. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  17077. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  17078. const renderList = this._renderLists.get( scene, camera );
  17079. renderList.begin();
  17080. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  17081. renderList.finish();
  17082. if ( this.sortObjects === true ) {
  17083. renderList.sort( this._opaqueSort, this._transparentSort );
  17084. }
  17085. //
  17086. if ( renderTarget !== null ) {
  17087. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  17088. const renderTargetData = this._textures.get( renderTarget );
  17089. renderContext.textures = renderTargetData.textures;
  17090. renderContext.depthTexture = renderTargetData.depthTexture;
  17091. renderContext.width = renderTargetData.width;
  17092. renderContext.height = renderTargetData.height;
  17093. renderContext.renderTarget = renderTarget;
  17094. renderContext.depth = renderTarget.depthBuffer;
  17095. renderContext.stencil = renderTarget.stencilBuffer;
  17096. } else {
  17097. renderContext.textures = null;
  17098. renderContext.depthTexture = null;
  17099. renderContext.width = this.domElement.width;
  17100. renderContext.height = this.domElement.height;
  17101. renderContext.depth = this.depth;
  17102. renderContext.stencil = this.stencil;
  17103. }
  17104. renderContext.width >>= activeMipmapLevel;
  17105. renderContext.height >>= activeMipmapLevel;
  17106. renderContext.activeCubeFace = activeCubeFace;
  17107. renderContext.activeMipmapLevel = activeMipmapLevel;
  17108. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  17109. //
  17110. this._nodes.updateScene( sceneRef );
  17111. //
  17112. this._background.update( sceneRef, renderList, renderContext );
  17113. //
  17114. this.backend.beginRender( renderContext );
  17115. // process render lists
  17116. const {
  17117. bundles,
  17118. lightsNode,
  17119. transparentDoublePass: transparentDoublePassObjects,
  17120. transparent: transparentObjects,
  17121. opaque: opaqueObjects
  17122. } = renderList;
  17123. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  17124. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  17125. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  17126. // finish render pass
  17127. this.backend.finishRender( renderContext );
  17128. // restore render tree
  17129. nodeFrame.renderId = previousRenderId;
  17130. this._currentRenderContext = previousRenderContext;
  17131. this._currentRenderObjectFunction = previousRenderObjectFunction;
  17132. //
  17133. if ( frameBufferTarget !== null ) {
  17134. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  17135. const quad = this._quad;
  17136. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  17137. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  17138. quad.material.needsUpdate = true;
  17139. }
  17140. this._renderScene( quad, quad.camera, false );
  17141. }
  17142. //
  17143. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  17144. //
  17145. return renderContext;
  17146. }
  17147. getMaxAnisotropy() {
  17148. return this.backend.getMaxAnisotropy();
  17149. }
  17150. getActiveCubeFace() {
  17151. return this._activeCubeFace;
  17152. }
  17153. getActiveMipmapLevel() {
  17154. return this._activeMipmapLevel;
  17155. }
  17156. async setAnimationLoop( callback ) {
  17157. if ( this._initialized === false ) await this.init();
  17158. this._animation.setAnimationLoop( callback );
  17159. }
  17160. async getArrayBufferAsync( attribute ) {
  17161. return await this.backend.getArrayBufferAsync( attribute );
  17162. }
  17163. getContext() {
  17164. return this.backend.getContext();
  17165. }
  17166. getPixelRatio() {
  17167. return this._pixelRatio;
  17168. }
  17169. getDrawingBufferSize( target ) {
  17170. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  17171. }
  17172. getSize( target ) {
  17173. return target.set( this._width, this._height );
  17174. }
  17175. setPixelRatio( value = 1 ) {
  17176. if ( this._pixelRatio === value ) return;
  17177. this._pixelRatio = value;
  17178. this.setSize( this._width, this._height, false );
  17179. }
  17180. setDrawingBufferSize( width, height, pixelRatio ) {
  17181. this._width = width;
  17182. this._height = height;
  17183. this._pixelRatio = pixelRatio;
  17184. this.domElement.width = Math.floor( width * pixelRatio );
  17185. this.domElement.height = Math.floor( height * pixelRatio );
  17186. this.setViewport( 0, 0, width, height );
  17187. if ( this._initialized ) this.backend.updateSize();
  17188. }
  17189. setSize( width, height, updateStyle = true ) {
  17190. this._width = width;
  17191. this._height = height;
  17192. this.domElement.width = Math.floor( width * this._pixelRatio );
  17193. this.domElement.height = Math.floor( height * this._pixelRatio );
  17194. if ( updateStyle === true ) {
  17195. this.domElement.style.width = width + 'px';
  17196. this.domElement.style.height = height + 'px';
  17197. }
  17198. this.setViewport( 0, 0, width, height );
  17199. if ( this._initialized ) this.backend.updateSize();
  17200. }
  17201. setOpaqueSort( method ) {
  17202. this._opaqueSort = method;
  17203. }
  17204. setTransparentSort( method ) {
  17205. this._transparentSort = method;
  17206. }
  17207. getScissor( target ) {
  17208. const scissor = this._scissor;
  17209. target.x = scissor.x;
  17210. target.y = scissor.y;
  17211. target.width = scissor.width;
  17212. target.height = scissor.height;
  17213. return target;
  17214. }
  17215. setScissor( x, y, width, height ) {
  17216. const scissor = this._scissor;
  17217. if ( x.isVector4 ) {
  17218. scissor.copy( x );
  17219. } else {
  17220. scissor.set( x, y, width, height );
  17221. }
  17222. }
  17223. getScissorTest() {
  17224. return this._scissorTest;
  17225. }
  17226. setScissorTest( boolean ) {
  17227. this._scissorTest = boolean;
  17228. this.backend.setScissorTest( boolean );
  17229. }
  17230. getViewport( target ) {
  17231. return target.copy( this._viewport );
  17232. }
  17233. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  17234. const viewport = this._viewport;
  17235. if ( x.isVector4 ) {
  17236. viewport.copy( x );
  17237. } else {
  17238. viewport.set( x, y, width, height );
  17239. }
  17240. viewport.minDepth = minDepth;
  17241. viewport.maxDepth = maxDepth;
  17242. }
  17243. getClearColor( target ) {
  17244. return target.copy( this._clearColor );
  17245. }
  17246. setClearColor( color, alpha = 1 ) {
  17247. this._clearColor.set( color );
  17248. this._clearColor.a = alpha;
  17249. }
  17250. getClearAlpha() {
  17251. return this._clearColor.a;
  17252. }
  17253. setClearAlpha( alpha ) {
  17254. this._clearColor.a = alpha;
  17255. }
  17256. getClearDepth() {
  17257. return this._clearDepth;
  17258. }
  17259. setClearDepth( depth ) {
  17260. this._clearDepth = depth;
  17261. }
  17262. getClearStencil() {
  17263. return this._clearStencil;
  17264. }
  17265. setClearStencil( stencil ) {
  17266. this._clearStencil = stencil;
  17267. }
  17268. isOccluded( object ) {
  17269. const renderContext = this._currentRenderContext;
  17270. return renderContext && this.backend.isOccluded( renderContext, object );
  17271. }
  17272. clear( color = true, depth = true, stencil = true ) {
  17273. if ( this._initialized === false ) {
  17274. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  17275. return this.clearAsync( color, depth, stencil );
  17276. }
  17277. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  17278. let renderTargetData = null;
  17279. if ( renderTarget !== null ) {
  17280. this._textures.updateRenderTarget( renderTarget );
  17281. renderTargetData = this._textures.get( renderTarget );
  17282. }
  17283. this.backend.clear( color, depth, stencil, renderTargetData );
  17284. if ( renderTarget !== null && this._renderTarget === null ) {
  17285. // If a color space transform or tone mapping is required,
  17286. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  17287. const quad = this._quad;
  17288. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  17289. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  17290. quad.material.needsUpdate = true;
  17291. }
  17292. this._renderScene( quad, quad.camera, false );
  17293. }
  17294. }
  17295. clearColor() {
  17296. return this.clear( true, false, false );
  17297. }
  17298. clearDepth() {
  17299. return this.clear( false, true, false );
  17300. }
  17301. clearStencil() {
  17302. return this.clear( false, false, true );
  17303. }
  17304. async clearAsync( color = true, depth = true, stencil = true ) {
  17305. if ( this._initialized === false ) await this.init();
  17306. this.clear( color, depth, stencil );
  17307. }
  17308. clearColorAsync() {
  17309. return this.clearAsync( true, false, false );
  17310. }
  17311. clearDepthAsync() {
  17312. return this.clearAsync( false, true, false );
  17313. }
  17314. clearStencilAsync() {
  17315. return this.clearAsync( false, false, true );
  17316. }
  17317. get currentToneMapping() {
  17318. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  17319. }
  17320. get currentColorSpace() {
  17321. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  17322. }
  17323. dispose() {
  17324. this.info.dispose();
  17325. this.backend.dispose();
  17326. this._animation.dispose();
  17327. this._objects.dispose();
  17328. this._pipelines.dispose();
  17329. this._nodes.dispose();
  17330. this._bindings.dispose();
  17331. this._renderLists.dispose();
  17332. this._renderContexts.dispose();
  17333. this._textures.dispose();
  17334. this.setRenderTarget( null );
  17335. this.setAnimationLoop( null );
  17336. }
  17337. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  17338. this._renderTarget = renderTarget;
  17339. this._activeCubeFace = activeCubeFace;
  17340. this._activeMipmapLevel = activeMipmapLevel;
  17341. }
  17342. getRenderTarget() {
  17343. return this._renderTarget;
  17344. }
  17345. setRenderObjectFunction( renderObjectFunction ) {
  17346. this._renderObjectFunction = renderObjectFunction;
  17347. }
  17348. getRenderObjectFunction() {
  17349. return this._renderObjectFunction;
  17350. }
  17351. compute( computeNodes ) {
  17352. if ( this.isDeviceLost === true ) return;
  17353. if ( this._initialized === false ) {
  17354. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  17355. return this.computeAsync( computeNodes );
  17356. }
  17357. //
  17358. const nodeFrame = this._nodes.nodeFrame;
  17359. const previousRenderId = nodeFrame.renderId;
  17360. //
  17361. this.info.calls ++;
  17362. this.info.compute.calls ++;
  17363. this.info.compute.frameCalls ++;
  17364. nodeFrame.renderId = this.info.calls;
  17365. //
  17366. const backend = this.backend;
  17367. const pipelines = this._pipelines;
  17368. const bindings = this._bindings;
  17369. const nodes = this._nodes;
  17370. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  17371. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  17372. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  17373. }
  17374. backend.beginCompute( computeNodes );
  17375. for ( const computeNode of computeList ) {
  17376. // onInit
  17377. if ( pipelines.has( computeNode ) === false ) {
  17378. const dispose = () => {
  17379. computeNode.removeEventListener( 'dispose', dispose );
  17380. pipelines.delete( computeNode );
  17381. bindings.delete( computeNode );
  17382. nodes.delete( computeNode );
  17383. };
  17384. computeNode.addEventListener( 'dispose', dispose );
  17385. //
  17386. const onInitFn = computeNode.onInitFunction;
  17387. if ( onInitFn !== null ) {
  17388. onInitFn.call( computeNode, { renderer: this } );
  17389. }
  17390. }
  17391. nodes.updateForCompute( computeNode );
  17392. bindings.updateForCompute( computeNode );
  17393. const computeBindings = bindings.getForCompute( computeNode );
  17394. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  17395. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  17396. }
  17397. backend.finishCompute( computeNodes );
  17398. //
  17399. nodeFrame.renderId = previousRenderId;
  17400. }
  17401. async computeAsync( computeNodes ) {
  17402. if ( this._initialized === false ) await this.init();
  17403. this.compute( computeNodes );
  17404. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  17405. }
  17406. async hasFeatureAsync( name ) {
  17407. if ( this._initialized === false ) await this.init();
  17408. return this.backend.hasFeature( name );
  17409. }
  17410. hasFeature( name ) {
  17411. if ( this._initialized === false ) {
  17412. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  17413. return false;
  17414. }
  17415. return this.backend.hasFeature( name );
  17416. }
  17417. hasInitialized() {
  17418. return this._initialized;
  17419. }
  17420. async initTextureAsync( texture ) {
  17421. if ( this._initialized === false ) await this.init();
  17422. this._textures.updateTexture( texture );
  17423. }
  17424. initTexture( texture ) {
  17425. if ( this._initialized === false ) {
  17426. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  17427. return false;
  17428. }
  17429. this._textures.updateTexture( texture );
  17430. }
  17431. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  17432. if ( rectangle !== null ) {
  17433. if ( rectangle.isVector2 ) {
  17434. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  17435. } else if ( rectangle.isVector4 ) {
  17436. rectangle = _vector4.copy( rectangle ).floor();
  17437. } else {
  17438. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  17439. return;
  17440. }
  17441. } else {
  17442. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  17443. }
  17444. //
  17445. let renderContext = this._currentRenderContext;
  17446. let renderTarget;
  17447. if ( renderContext !== null ) {
  17448. renderTarget = renderContext.renderTarget;
  17449. } else {
  17450. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  17451. if ( renderTarget !== null ) {
  17452. this._textures.updateRenderTarget( renderTarget );
  17453. renderContext = this._textures.get( renderTarget );
  17454. }
  17455. }
  17456. //
  17457. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  17458. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  17459. }
  17460. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  17461. this._textures.updateTexture( srcTexture );
  17462. this._textures.updateTexture( dstTexture );
  17463. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  17464. }
  17465. readRenderTargetPixelsAsync( renderTarget, x, y, width, height, index = 0, faceIndex = 0 ) {
  17466. return this.backend.copyTextureToBuffer( renderTarget.textures[ index ], x, y, width, height, faceIndex );
  17467. }
  17468. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  17469. if ( object.visible === false ) return;
  17470. const visible = object.layers.test( camera.layers );
  17471. if ( visible ) {
  17472. if ( object.isGroup ) {
  17473. groupOrder = object.renderOrder;
  17474. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  17475. } else if ( object.isLOD ) {
  17476. if ( object.autoUpdate === true ) object.update( camera );
  17477. } else if ( object.isLight ) {
  17478. renderList.pushLight( object );
  17479. } else if ( object.isSprite ) {
  17480. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  17481. if ( this.sortObjects === true ) {
  17482. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  17483. }
  17484. const { geometry, material } = object;
  17485. if ( material.visible ) {
  17486. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  17487. }
  17488. }
  17489. } else if ( object.isLineLoop ) {
  17490. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  17491. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  17492. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  17493. const { geometry, material } = object;
  17494. if ( this.sortObjects === true ) {
  17495. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17496. _vector4
  17497. .copy( geometry.boundingSphere.center )
  17498. .applyMatrix4( object.matrixWorld )
  17499. .applyMatrix4( _projScreenMatrix );
  17500. }
  17501. if ( Array.isArray( material ) ) {
  17502. const groups = geometry.groups;
  17503. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17504. const group = groups[ i ];
  17505. const groupMaterial = material[ group.materialIndex ];
  17506. if ( groupMaterial && groupMaterial.visible ) {
  17507. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  17508. }
  17509. }
  17510. } else if ( material.visible ) {
  17511. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  17512. }
  17513. }
  17514. }
  17515. }
  17516. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  17517. const baseRenderList = renderList;
  17518. // replace render list
  17519. renderList = this._renderLists.get( object, camera );
  17520. renderList.begin();
  17521. baseRenderList.pushBundle( {
  17522. bundleGroup: object,
  17523. camera,
  17524. renderList,
  17525. } );
  17526. renderList.finish();
  17527. }
  17528. const children = object.children;
  17529. for ( let i = 0, l = children.length; i < l; i ++ ) {
  17530. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  17531. }
  17532. }
  17533. _renderBundles( bundles, sceneRef, lightsNode ) {
  17534. for ( const bundle of bundles ) {
  17535. this._renderBundle( bundle, sceneRef, lightsNode );
  17536. }
  17537. }
  17538. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  17539. if ( doublePassList.length > 0 ) {
  17540. // render back side
  17541. for ( const { material } of doublePassList ) {
  17542. material.side = BackSide;
  17543. }
  17544. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  17545. // render front side
  17546. for ( const { material } of doublePassList ) {
  17547. material.side = FrontSide;
  17548. }
  17549. this._renderObjects( renderList, camera, scene, lightsNode );
  17550. // restore
  17551. for ( const { material } of doublePassList ) {
  17552. material.side = DoubleSide;
  17553. }
  17554. } else {
  17555. this._renderObjects( renderList, camera, scene, lightsNode );
  17556. }
  17557. }
  17558. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  17559. // process renderable objects
  17560. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  17561. const renderItem = renderList[ i ];
  17562. // @TODO: Add support for multiple materials per object. This will require to extract
  17563. // the material from the renderItem object and pass it with its group data to renderObject().
  17564. const { object, geometry, material, group, clippingContext } = renderItem;
  17565. if ( camera.isArrayCamera ) {
  17566. const cameras = camera.cameras;
  17567. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  17568. const camera2 = cameras[ j ];
  17569. if ( object.layers.test( camera2.layers ) ) {
  17570. const vp = camera2.viewport;
  17571. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  17572. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  17573. const viewportValue = this._currentRenderContext.viewportValue;
  17574. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  17575. viewportValue.minDepth = minDepth;
  17576. viewportValue.maxDepth = maxDepth;
  17577. this.backend.updateViewport( this._currentRenderContext );
  17578. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode, clippingContext, passId );
  17579. }
  17580. }
  17581. } else {
  17582. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  17583. }
  17584. }
  17585. }
  17586. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  17587. let overridePositionNode;
  17588. let overrideColorNode;
  17589. let overrideDepthNode;
  17590. //
  17591. object.onBeforeRender( this, scene, camera, geometry, material, group );
  17592. //
  17593. if ( scene.overrideMaterial !== null ) {
  17594. const overrideMaterial = scene.overrideMaterial;
  17595. if ( material.positionNode && material.positionNode.isNode ) {
  17596. overridePositionNode = overrideMaterial.positionNode;
  17597. overrideMaterial.positionNode = material.positionNode;
  17598. }
  17599. overrideMaterial.alphaTest = material.alphaTest;
  17600. overrideMaterial.alphaMap = material.alphaMap;
  17601. if ( overrideMaterial.isShadowNodeMaterial ) {
  17602. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  17603. if ( material.depthNode && material.depthNode.isNode ) {
  17604. overrideDepthNode = overrideMaterial.depthNode;
  17605. overrideMaterial.depthNode = material.depthNode;
  17606. }
  17607. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  17608. overrideColorNode = overrideMaterial.colorNode;
  17609. overrideMaterial.colorNode = material.castShadowNode;
  17610. }
  17611. }
  17612. material = overrideMaterial;
  17613. }
  17614. //
  17615. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  17616. material.side = BackSide;
  17617. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  17618. material.side = FrontSide;
  17619. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  17620. material.side = DoubleSide;
  17621. } else {
  17622. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  17623. }
  17624. //
  17625. if ( overridePositionNode !== undefined ) {
  17626. scene.overrideMaterial.positionNode = overridePositionNode;
  17627. }
  17628. if ( overrideDepthNode !== undefined ) {
  17629. scene.overrideMaterial.depthNode = overrideDepthNode;
  17630. }
  17631. if ( overrideColorNode !== undefined ) {
  17632. scene.overrideMaterial.colorNode = overrideColorNode;
  17633. }
  17634. //
  17635. object.onAfterRender( this, scene, camera, geometry, material, group );
  17636. }
  17637. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  17638. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  17639. renderObject.drawRange = object.geometry.drawRange;
  17640. renderObject.group = group;
  17641. //
  17642. const needsRefresh = this._nodes.needsRefresh( renderObject );
  17643. if ( needsRefresh ) {
  17644. this._nodes.updateBefore( renderObject );
  17645. this._geometries.updateForRender( renderObject );
  17646. this._nodes.updateForRender( renderObject );
  17647. this._bindings.updateForRender( renderObject );
  17648. }
  17649. this._pipelines.updateForRender( renderObject );
  17650. //
  17651. if ( this._currentRenderBundle !== null ) {
  17652. const renderBundleData = this.backend.get( this._currentRenderBundle );
  17653. renderBundleData.renderObjects.push( renderObject );
  17654. renderObject.bundle = this._currentRenderBundle.scene;
  17655. }
  17656. this.backend.draw( renderObject, this.info );
  17657. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  17658. }
  17659. _createObjectPipeline( object, material, scene, camera, lightsNode, clippingContext, passId ) {
  17660. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  17661. //
  17662. this._nodes.updateBefore( renderObject );
  17663. this._geometries.updateForRender( renderObject );
  17664. this._nodes.updateForRender( renderObject );
  17665. this._bindings.updateForRender( renderObject );
  17666. this._pipelines.getForRender( renderObject, this._compilationPromises );
  17667. this._nodes.updateAfter( renderObject );
  17668. }
  17669. get compile() {
  17670. return this.compileAsync;
  17671. }
  17672. }
  17673. class Binding {
  17674. constructor( name = '' ) {
  17675. this.name = name;
  17676. this.visibility = 0;
  17677. }
  17678. setVisibility( visibility ) {
  17679. this.visibility |= visibility;
  17680. }
  17681. clone() {
  17682. return Object.assign( new this.constructor(), this );
  17683. }
  17684. }
  17685. function getFloatLength( floatLength ) {
  17686. // ensure chunk size alignment (STD140 layout)
  17687. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  17688. }
  17689. class Buffer extends Binding {
  17690. constructor( name, buffer = null ) {
  17691. super( name );
  17692. this.isBuffer = true;
  17693. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  17694. this._buffer = buffer;
  17695. }
  17696. get byteLength() {
  17697. return getFloatLength( this._buffer.byteLength );
  17698. }
  17699. get buffer() {
  17700. return this._buffer;
  17701. }
  17702. update() {
  17703. return true;
  17704. }
  17705. }
  17706. class UniformBuffer extends Buffer {
  17707. constructor( name, buffer = null ) {
  17708. super( name, buffer );
  17709. this.isUniformBuffer = true;
  17710. }
  17711. }
  17712. let _id$4 = 0;
  17713. class NodeUniformBuffer extends UniformBuffer {
  17714. constructor( nodeUniform, groupNode ) {
  17715. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  17716. this.nodeUniform = nodeUniform;
  17717. this.groupNode = groupNode;
  17718. }
  17719. get buffer() {
  17720. return this.nodeUniform.value;
  17721. }
  17722. }
  17723. class UniformsGroup extends UniformBuffer {
  17724. constructor( name ) {
  17725. super( name );
  17726. this.isUniformsGroup = true;
  17727. this._values = null;
  17728. // the order of uniforms in this array must match the order of uniforms in the shader
  17729. this.uniforms = [];
  17730. }
  17731. addUniform( uniform ) {
  17732. this.uniforms.push( uniform );
  17733. return this;
  17734. }
  17735. removeUniform( uniform ) {
  17736. const index = this.uniforms.indexOf( uniform );
  17737. if ( index !== - 1 ) {
  17738. this.uniforms.splice( index, 1 );
  17739. }
  17740. return this;
  17741. }
  17742. get values() {
  17743. if ( this._values === null ) {
  17744. this._values = Array.from( this.buffer );
  17745. }
  17746. return this._values;
  17747. }
  17748. get buffer() {
  17749. let buffer = this._buffer;
  17750. if ( buffer === null ) {
  17751. const byteLength = this.byteLength;
  17752. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  17753. this._buffer = buffer;
  17754. }
  17755. return buffer;
  17756. }
  17757. get byteLength() {
  17758. let offset = 0; // global buffer offset in bytes
  17759. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  17760. const uniform = this.uniforms[ i ];
  17761. const { boundary, itemSize } = uniform;
  17762. // offset within a single chunk in bytes
  17763. const chunkOffset = offset % GPU_CHUNK_BYTES;
  17764. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  17765. // conformance tests
  17766. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  17767. // check for chunk overflow
  17768. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  17769. } else if ( chunkOffset % boundary !== 0 ) {
  17770. // check for correct alignment
  17771. offset += ( chunkOffset % boundary );
  17772. }
  17773. uniform.offset = ( offset / this.bytesPerElement );
  17774. offset += ( itemSize * this.bytesPerElement );
  17775. }
  17776. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  17777. }
  17778. update() {
  17779. let updated = false;
  17780. for ( const uniform of this.uniforms ) {
  17781. if ( this.updateByType( uniform ) === true ) {
  17782. updated = true;
  17783. }
  17784. }
  17785. return updated;
  17786. }
  17787. updateByType( uniform ) {
  17788. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  17789. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  17790. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  17791. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  17792. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  17793. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  17794. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  17795. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  17796. }
  17797. updateNumber( uniform ) {
  17798. let updated = false;
  17799. const a = this.values;
  17800. const v = uniform.getValue();
  17801. const offset = uniform.offset;
  17802. const type = uniform.getType();
  17803. if ( a[ offset ] !== v ) {
  17804. const b = this._getBufferForType( type );
  17805. b[ offset ] = a[ offset ] = v;
  17806. updated = true;
  17807. }
  17808. return updated;
  17809. }
  17810. updateVector2( uniform ) {
  17811. let updated = false;
  17812. const a = this.values;
  17813. const v = uniform.getValue();
  17814. const offset = uniform.offset;
  17815. const type = uniform.getType();
  17816. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  17817. const b = this._getBufferForType( type );
  17818. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  17819. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  17820. updated = true;
  17821. }
  17822. return updated;
  17823. }
  17824. updateVector3( uniform ) {
  17825. let updated = false;
  17826. const a = this.values;
  17827. const v = uniform.getValue();
  17828. const offset = uniform.offset;
  17829. const type = uniform.getType();
  17830. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  17831. const b = this._getBufferForType( type );
  17832. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  17833. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  17834. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  17835. updated = true;
  17836. }
  17837. return updated;
  17838. }
  17839. updateVector4( uniform ) {
  17840. let updated = false;
  17841. const a = this.values;
  17842. const v = uniform.getValue();
  17843. const offset = uniform.offset;
  17844. const type = uniform.getType();
  17845. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  17846. const b = this._getBufferForType( type );
  17847. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  17848. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  17849. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  17850. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  17851. updated = true;
  17852. }
  17853. return updated;
  17854. }
  17855. updateColor( uniform ) {
  17856. let updated = false;
  17857. const a = this.values;
  17858. const c = uniform.getValue();
  17859. const offset = uniform.offset;
  17860. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  17861. const b = this.buffer;
  17862. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  17863. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  17864. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  17865. updated = true;
  17866. }
  17867. return updated;
  17868. }
  17869. updateMatrix3( uniform ) {
  17870. let updated = false;
  17871. const a = this.values;
  17872. const e = uniform.getValue().elements;
  17873. const offset = uniform.offset;
  17874. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  17875. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  17876. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  17877. const b = this.buffer;
  17878. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  17879. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  17880. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  17881. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  17882. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  17883. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  17884. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  17885. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  17886. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  17887. updated = true;
  17888. }
  17889. return updated;
  17890. }
  17891. updateMatrix4( uniform ) {
  17892. let updated = false;
  17893. const a = this.values;
  17894. const e = uniform.getValue().elements;
  17895. const offset = uniform.offset;
  17896. if ( arraysEqual( a, e, offset ) === false ) {
  17897. const b = this.buffer;
  17898. b.set( e, offset );
  17899. setArray( a, e, offset );
  17900. updated = true;
  17901. }
  17902. return updated;
  17903. }
  17904. _getBufferForType( type ) {
  17905. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  17906. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  17907. return this.buffer;
  17908. }
  17909. }
  17910. function setArray( a, b, offset ) {
  17911. for ( let i = 0, l = b.length; i < l; i ++ ) {
  17912. a[ offset + i ] = b[ i ];
  17913. }
  17914. }
  17915. function arraysEqual( a, b, offset ) {
  17916. for ( let i = 0, l = b.length; i < l; i ++ ) {
  17917. if ( a[ offset + i ] !== b[ i ] ) return false;
  17918. }
  17919. return true;
  17920. }
  17921. let _id$3 = 0;
  17922. class NodeUniformsGroup extends UniformsGroup {
  17923. constructor( name, groupNode ) {
  17924. super( name );
  17925. this.id = _id$3 ++;
  17926. this.groupNode = groupNode;
  17927. this.isNodeUniformsGroup = true;
  17928. }
  17929. getNodes() {
  17930. const nodes = [];
  17931. for ( const uniform of this.uniforms ) {
  17932. const node = uniform.nodeUniform.node;
  17933. if ( ! node ) throw new Error( 'NodeUniformsGroup: Uniform has no node.' );
  17934. nodes.push( node );
  17935. }
  17936. return nodes;
  17937. }
  17938. }
  17939. let _id$2 = 0;
  17940. class SampledTexture extends Binding {
  17941. constructor( name, texture ) {
  17942. super( name );
  17943. this.id = _id$2 ++;
  17944. this.texture = texture;
  17945. this.version = texture ? texture.version : 0;
  17946. this.store = false;
  17947. this.generation = null;
  17948. this.isSampledTexture = true;
  17949. }
  17950. needsBindingsUpdate( generation ) {
  17951. const { texture } = this;
  17952. if ( generation !== this.generation ) {
  17953. this.generation = generation;
  17954. return true;
  17955. }
  17956. return texture.isVideoTexture;
  17957. }
  17958. update() {
  17959. const { texture, version } = this;
  17960. if ( version !== texture.version ) {
  17961. this.version = texture.version;
  17962. return true;
  17963. }
  17964. return false;
  17965. }
  17966. }
  17967. class NodeSampledTexture extends SampledTexture {
  17968. constructor( name, textureNode, groupNode, access = null ) {
  17969. super( name, textureNode ? textureNode.value : null );
  17970. this.textureNode = textureNode;
  17971. this.groupNode = groupNode;
  17972. this.access = access;
  17973. }
  17974. needsBindingsUpdate( generation ) {
  17975. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  17976. }
  17977. update() {
  17978. const { textureNode } = this;
  17979. if ( this.texture !== textureNode.value ) {
  17980. this.texture = textureNode.value;
  17981. return true;
  17982. }
  17983. return super.update();
  17984. }
  17985. }
  17986. class NodeSampledCubeTexture extends NodeSampledTexture {
  17987. constructor( name, textureNode, groupNode, access ) {
  17988. super( name, textureNode, groupNode, access );
  17989. this.isSampledCubeTexture = true;
  17990. }
  17991. }
  17992. class NodeSampledTexture3D extends NodeSampledTexture {
  17993. constructor( name, textureNode, groupNode, access ) {
  17994. super( name, textureNode, groupNode, access );
  17995. this.isSampledTexture3D = true;
  17996. }
  17997. }
  17998. const glslMethods = {
  17999. atan2: 'atan',
  18000. textureDimensions: 'textureSize',
  18001. equals: 'equal'
  18002. };
  18003. const precisionLib = {
  18004. low: 'lowp',
  18005. medium: 'mediump',
  18006. high: 'highp'
  18007. };
  18008. const supports$1 = {
  18009. swizzleAssign: true,
  18010. storageBuffer: false
  18011. };
  18012. const defaultPrecisions = `
  18013. precision highp float;
  18014. precision highp int;
  18015. precision highp sampler2D;
  18016. precision highp sampler3D;
  18017. precision highp samplerCube;
  18018. precision highp sampler2DArray;
  18019. precision highp usampler2D;
  18020. precision highp usampler3D;
  18021. precision highp usamplerCube;
  18022. precision highp usampler2DArray;
  18023. precision highp isampler2D;
  18024. precision highp isampler3D;
  18025. precision highp isamplerCube;
  18026. precision highp isampler2DArray;
  18027. precision lowp sampler2DShadow;
  18028. `;
  18029. class GLSLNodeBuilder extends NodeBuilder {
  18030. constructor( object, renderer ) {
  18031. super( object, renderer, new GLSLNodeParser() );
  18032. this.uniformGroups = {};
  18033. this.transforms = [];
  18034. this.extensions = {};
  18035. this.builtins = { vertex: [], fragment: [], compute: [] };
  18036. this.useComparisonMethod = true;
  18037. }
  18038. needsToWorkingColorSpace( texture ) {
  18039. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  18040. }
  18041. getMethod( method ) {
  18042. return glslMethods[ method ] || method;
  18043. }
  18044. getOutputStructName() {
  18045. return '';
  18046. }
  18047. buildFunctionCode( shaderNode ) {
  18048. const layout = shaderNode.layout;
  18049. const flowData = this.flowShaderNode( shaderNode );
  18050. const parameters = [];
  18051. for ( const input of layout.inputs ) {
  18052. parameters.push( this.getType( input.type ) + ' ' + input.name );
  18053. }
  18054. //
  18055. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  18056. ${ flowData.vars }
  18057. ${ flowData.code }
  18058. return ${ flowData.result };
  18059. }`;
  18060. //
  18061. return code;
  18062. }
  18063. setupPBO( storageBufferNode ) {
  18064. const attribute = storageBufferNode.value;
  18065. if ( attribute.pbo === undefined ) {
  18066. const originalArray = attribute.array;
  18067. const numElements = attribute.count * attribute.itemSize;
  18068. const { itemSize } = attribute;
  18069. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  18070. let format = isInteger ? RedIntegerFormat : RedFormat;
  18071. if ( itemSize === 2 ) {
  18072. format = isInteger ? RGIntegerFormat : RGFormat;
  18073. } else if ( itemSize === 3 ) {
  18074. format = isInteger ? RGBIntegerFormat : RGBFormat;
  18075. } else if ( itemSize === 4 ) {
  18076. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  18077. }
  18078. const typeMap = {
  18079. Float32Array: FloatType,
  18080. Uint8Array: UnsignedByteType,
  18081. Uint16Array: UnsignedShortType,
  18082. Uint32Array: UnsignedIntType,
  18083. Int8Array: ByteType,
  18084. Int16Array: ShortType,
  18085. Int32Array: IntType,
  18086. Uint8ClampedArray: UnsignedByteType,
  18087. };
  18088. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  18089. let height = Math.ceil( ( numElements / itemSize ) / width );
  18090. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  18091. const newSize = width * height * itemSize;
  18092. const newArray = new originalArray.constructor( newSize );
  18093. newArray.set( originalArray, 0 );
  18094. attribute.array = newArray;
  18095. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  18096. pboTexture.needsUpdate = true;
  18097. pboTexture.isPBOTexture = true;
  18098. const pbo = new TextureNode( pboTexture, null, null );
  18099. pbo.setPrecision( 'high' );
  18100. attribute.pboNode = pbo;
  18101. attribute.pbo = pbo.value;
  18102. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  18103. }
  18104. }
  18105. getPropertyName( node, shaderStage = this.shaderStage ) {
  18106. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  18107. return shaderStage.charAt( 0 ) + '_' + node.name;
  18108. }
  18109. return super.getPropertyName( node, shaderStage );
  18110. }
  18111. generatePBO( storageArrayElementNode ) {
  18112. const { node, indexNode } = storageArrayElementNode;
  18113. const attribute = node.value;
  18114. if ( this.renderer.backend.has( attribute ) ) {
  18115. const attributeData = this.renderer.backend.get( attribute );
  18116. attributeData.pbo = attribute.pbo;
  18117. }
  18118. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  18119. const textureName = this.getPropertyName( nodeUniform );
  18120. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  18121. const indexSnippet = indexNode.build( this, 'uint' );
  18122. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  18123. let propertyName = elementNodeData.propertyName;
  18124. if ( propertyName === undefined ) {
  18125. // property element
  18126. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  18127. propertyName = this.getPropertyName( nodeVar );
  18128. // property size
  18129. const bufferNodeData = this.getDataFromNode( node );
  18130. let propertySizeName = bufferNodeData.propertySizeName;
  18131. if ( propertySizeName === undefined ) {
  18132. propertySizeName = propertyName + 'Size';
  18133. this.getVarFromNode( node, propertySizeName, 'uint' );
  18134. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  18135. bufferNodeData.propertySizeName = propertySizeName;
  18136. }
  18137. //
  18138. const { itemSize } = attribute;
  18139. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  18140. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  18141. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  18142. //
  18143. let prefix = 'vec4';
  18144. if ( attribute.pbo.type === UnsignedIntType ) {
  18145. prefix = 'uvec4';
  18146. } else if ( attribute.pbo.type === IntType ) {
  18147. prefix = 'ivec4';
  18148. }
  18149. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  18150. elementNodeData.propertyName = propertyName;
  18151. }
  18152. return propertyName;
  18153. }
  18154. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  18155. if ( depthSnippet ) {
  18156. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  18157. } else {
  18158. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  18159. }
  18160. }
  18161. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  18162. if ( texture.isDepthTexture ) {
  18163. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  18164. } else {
  18165. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  18166. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  18167. }
  18168. }
  18169. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  18170. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  18171. }
  18172. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  18173. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  18174. }
  18175. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  18176. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  18177. }
  18178. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  18179. if ( shaderStage === 'fragment' ) {
  18180. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  18181. } else {
  18182. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  18183. }
  18184. }
  18185. getVars( shaderStage ) {
  18186. const snippets = [];
  18187. const vars = this.vars[ shaderStage ];
  18188. if ( vars !== undefined ) {
  18189. for ( const variable of vars ) {
  18190. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  18191. }
  18192. }
  18193. return snippets.join( '\n\t' );
  18194. }
  18195. getUniforms( shaderStage ) {
  18196. const uniforms = this.uniforms[ shaderStage ];
  18197. const bindingSnippets = [];
  18198. const uniformGroups = {};
  18199. for ( const uniform of uniforms ) {
  18200. let snippet = null;
  18201. let group = false;
  18202. if ( uniform.type === 'texture' ) {
  18203. const texture = uniform.node.value;
  18204. let typePrefix = '';
  18205. if ( texture.isDataTexture === true ) {
  18206. if ( texture.type === UnsignedIntType ) {
  18207. typePrefix = 'u';
  18208. } else if ( texture.type === IntType ) {
  18209. typePrefix = 'i';
  18210. }
  18211. }
  18212. if ( texture.compareFunction ) {
  18213. snippet = `sampler2DShadow ${ uniform.name };`;
  18214. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  18215. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  18216. } else {
  18217. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  18218. }
  18219. } else if ( uniform.type === 'cubeTexture' ) {
  18220. snippet = `samplerCube ${ uniform.name };`;
  18221. } else if ( uniform.type === 'texture3D' ) {
  18222. snippet = `sampler3D ${ uniform.name };`;
  18223. } else if ( uniform.type === 'buffer' ) {
  18224. const bufferNode = uniform.node;
  18225. const bufferType = this.getType( bufferNode.bufferType );
  18226. const bufferCount = bufferNode.bufferCount;
  18227. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  18228. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  18229. } else {
  18230. const vectorType = this.getVectorType( uniform.type );
  18231. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  18232. group = true;
  18233. }
  18234. const precision = uniform.node.precision;
  18235. if ( precision !== null ) {
  18236. snippet = precisionLib[ precision ] + ' ' + snippet;
  18237. }
  18238. if ( group ) {
  18239. snippet = '\t' + snippet;
  18240. const groupName = uniform.groupNode.name;
  18241. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  18242. groupSnippets.push( snippet );
  18243. } else {
  18244. snippet = 'uniform ' + snippet;
  18245. bindingSnippets.push( snippet );
  18246. }
  18247. }
  18248. let output = '';
  18249. for ( const name in uniformGroups ) {
  18250. const groupSnippets = uniformGroups[ name ];
  18251. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  18252. }
  18253. output += bindingSnippets.join( '\n' );
  18254. return output;
  18255. }
  18256. getTypeFromAttribute( attribute ) {
  18257. let nodeType = super.getTypeFromAttribute( attribute );
  18258. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  18259. let dataAttribute = attribute;
  18260. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  18261. const array = dataAttribute.array;
  18262. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  18263. nodeType = nodeType.slice( 1 );
  18264. }
  18265. }
  18266. return nodeType;
  18267. }
  18268. getAttributes( shaderStage ) {
  18269. let snippet = '';
  18270. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  18271. const attributes = this.getAttributesArray();
  18272. let location = 0;
  18273. for ( const attribute of attributes ) {
  18274. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  18275. }
  18276. }
  18277. return snippet;
  18278. }
  18279. getStructMembers( struct ) {
  18280. const snippets = [];
  18281. const members = struct.getMemberTypes();
  18282. for ( let i = 0; i < members.length; i ++ ) {
  18283. const member = members[ i ];
  18284. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  18285. }
  18286. return snippets.join( '\n' );
  18287. }
  18288. getStructs( shaderStage ) {
  18289. const snippets = [];
  18290. const structs = this.structs[ shaderStage ];
  18291. if ( structs.length === 0 ) {
  18292. return 'layout( location = 0 ) out vec4 fragColor;\n';
  18293. }
  18294. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  18295. const struct = structs[ index ];
  18296. let snippet = '\n';
  18297. snippet += this.getStructMembers( struct );
  18298. snippet += '\n';
  18299. snippets.push( snippet );
  18300. }
  18301. return snippets.join( '\n\n' );
  18302. }
  18303. getVaryings( shaderStage ) {
  18304. let snippet = '';
  18305. const varyings = this.varyings;
  18306. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  18307. for ( const varying of varyings ) {
  18308. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  18309. const type = this.getType( varying.type );
  18310. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  18311. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  18312. }
  18313. } else if ( shaderStage === 'fragment' ) {
  18314. for ( const varying of varyings ) {
  18315. if ( varying.needsInterpolation ) {
  18316. const type = this.getType( varying.type );
  18317. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  18318. snippet += `${flat}in ${type} ${varying.name};\n`;
  18319. }
  18320. }
  18321. }
  18322. for ( const builtin of this.builtins[ shaderStage ] ) {
  18323. snippet += `${builtin};\n`;
  18324. }
  18325. return snippet;
  18326. }
  18327. getVertexIndex() {
  18328. return 'uint( gl_VertexID )';
  18329. }
  18330. getInstanceIndex() {
  18331. return 'uint( gl_InstanceID )';
  18332. }
  18333. getInvocationLocalIndex() {
  18334. const workgroupSize = this.object.workgroupSize;
  18335. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  18336. return `uint( gl_InstanceID ) % ${size}u`;
  18337. }
  18338. getDrawIndex() {
  18339. const extensions = this.renderer.backend.extensions;
  18340. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  18341. return 'uint( gl_DrawID )';
  18342. }
  18343. return null;
  18344. }
  18345. getFrontFacing() {
  18346. return 'gl_FrontFacing';
  18347. }
  18348. getFragCoord() {
  18349. return 'gl_FragCoord.xy';
  18350. }
  18351. getFragDepth() {
  18352. return 'gl_FragDepth';
  18353. }
  18354. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  18355. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  18356. if ( map.has( name ) === false ) {
  18357. map.set( name, {
  18358. name,
  18359. behavior
  18360. } );
  18361. }
  18362. }
  18363. getExtensions( shaderStage ) {
  18364. const snippets = [];
  18365. if ( shaderStage === 'vertex' ) {
  18366. const ext = this.renderer.backend.extensions;
  18367. const isBatchedMesh = this.object.isBatchedMesh;
  18368. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  18369. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  18370. }
  18371. }
  18372. const extensions = this.extensions[ shaderStage ];
  18373. if ( extensions !== undefined ) {
  18374. for ( const { name, behavior } of extensions.values() ) {
  18375. snippets.push( `#extension ${name} : ${behavior}` );
  18376. }
  18377. }
  18378. return snippets.join( '\n' );
  18379. }
  18380. getClipDistance() {
  18381. return 'gl_ClipDistance';
  18382. }
  18383. isAvailable( name ) {
  18384. let result = supports$1[ name ];
  18385. if ( result === undefined ) {
  18386. let extensionName;
  18387. result = false;
  18388. switch ( name ) {
  18389. case 'float32Filterable':
  18390. extensionName = 'OES_texture_float_linear';
  18391. break;
  18392. case 'clipDistance':
  18393. extensionName = 'WEBGL_clip_cull_distance';
  18394. break;
  18395. }
  18396. if ( extensionName !== undefined ) {
  18397. const extensions = this.renderer.backend.extensions;
  18398. if ( extensions.has( extensionName ) ) {
  18399. extensions.get( extensionName );
  18400. result = true;
  18401. }
  18402. }
  18403. supports$1[ name ] = result;
  18404. }
  18405. return result;
  18406. }
  18407. isFlipY() {
  18408. return true;
  18409. }
  18410. enableHardwareClipping( planeCount ) {
  18411. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  18412. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  18413. }
  18414. registerTransform( varyingName, attributeNode ) {
  18415. this.transforms.push( { varyingName, attributeNode } );
  18416. }
  18417. getTransforms( /* shaderStage */ ) {
  18418. const transforms = this.transforms;
  18419. let snippet = '';
  18420. for ( let i = 0; i < transforms.length; i ++ ) {
  18421. const transform = transforms[ i ];
  18422. const attributeName = this.getPropertyName( transform.attributeNode );
  18423. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  18424. }
  18425. return snippet;
  18426. }
  18427. _getGLSLUniformStruct( name, vars ) {
  18428. return `
  18429. layout( std140 ) uniform ${name} {
  18430. ${vars}
  18431. };`;
  18432. }
  18433. _getGLSLVertexCode( shaderData ) {
  18434. return `#version 300 es
  18435. ${ this.getSignature() }
  18436. // extensions
  18437. ${shaderData.extensions}
  18438. // precision
  18439. ${ defaultPrecisions }
  18440. // uniforms
  18441. ${shaderData.uniforms}
  18442. // varyings
  18443. ${shaderData.varyings}
  18444. // attributes
  18445. ${shaderData.attributes}
  18446. // codes
  18447. ${shaderData.codes}
  18448. void main() {
  18449. // vars
  18450. ${shaderData.vars}
  18451. // transforms
  18452. ${shaderData.transforms}
  18453. // flow
  18454. ${shaderData.flow}
  18455. gl_PointSize = 1.0;
  18456. }
  18457. `;
  18458. }
  18459. _getGLSLFragmentCode( shaderData ) {
  18460. return `#version 300 es
  18461. ${ this.getSignature() }
  18462. // precision
  18463. ${ defaultPrecisions }
  18464. // uniforms
  18465. ${shaderData.uniforms}
  18466. // varyings
  18467. ${shaderData.varyings}
  18468. // codes
  18469. ${shaderData.codes}
  18470. ${shaderData.structs}
  18471. void main() {
  18472. // vars
  18473. ${shaderData.vars}
  18474. // flow
  18475. ${shaderData.flow}
  18476. }
  18477. `;
  18478. }
  18479. buildCode() {
  18480. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  18481. this.sortBindingGroups();
  18482. for ( const shaderStage in shadersData ) {
  18483. let flow = '// code\n\n';
  18484. flow += this.flowCode[ shaderStage ];
  18485. const flowNodes = this.flowNodes[ shaderStage ];
  18486. const mainNode = flowNodes[ flowNodes.length - 1 ];
  18487. for ( const node of flowNodes ) {
  18488. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  18489. const slotName = node.name;
  18490. if ( slotName ) {
  18491. if ( flow.length > 0 ) flow += '\n';
  18492. flow += `\t// flow -> ${ slotName }\n\t`;
  18493. }
  18494. flow += `${ flowSlotData.code }\n\t`;
  18495. if ( node === mainNode && shaderStage !== 'compute' ) {
  18496. flow += '// result\n\t';
  18497. if ( shaderStage === 'vertex' ) {
  18498. flow += 'gl_Position = ';
  18499. flow += `${ flowSlotData.result };`;
  18500. } else if ( shaderStage === 'fragment' ) {
  18501. if ( ! node.outputNode.isOutputStructNode ) {
  18502. flow += 'fragColor = ';
  18503. flow += `${ flowSlotData.result };`;
  18504. }
  18505. }
  18506. }
  18507. }
  18508. const stageData = shadersData[ shaderStage ];
  18509. stageData.extensions = this.getExtensions( shaderStage );
  18510. stageData.uniforms = this.getUniforms( shaderStage );
  18511. stageData.attributes = this.getAttributes( shaderStage );
  18512. stageData.varyings = this.getVaryings( shaderStage );
  18513. stageData.vars = this.getVars( shaderStage );
  18514. stageData.structs = this.getStructs( shaderStage );
  18515. stageData.codes = this.getCodes( shaderStage );
  18516. stageData.transforms = this.getTransforms( shaderStage );
  18517. stageData.flow = flow;
  18518. }
  18519. if ( this.material !== null ) {
  18520. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  18521. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  18522. } else {
  18523. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  18524. }
  18525. }
  18526. getUniformFromNode( node, type, shaderStage, name = null ) {
  18527. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  18528. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  18529. let uniformGPU = nodeData.uniformGPU;
  18530. if ( uniformGPU === undefined ) {
  18531. const group = node.groupNode;
  18532. const groupName = group.name;
  18533. const bindings = this.getBindGroupArray( groupName, shaderStage );
  18534. if ( type === 'texture' ) {
  18535. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  18536. bindings.push( uniformGPU );
  18537. } else if ( type === 'cubeTexture' ) {
  18538. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  18539. bindings.push( uniformGPU );
  18540. } else if ( type === 'texture3D' ) {
  18541. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  18542. bindings.push( uniformGPU );
  18543. } else if ( type === 'buffer' ) {
  18544. node.name = `NodeBuffer_${ node.id }`;
  18545. uniformNode.name = `buffer${ node.id }`;
  18546. const buffer = new NodeUniformBuffer( node, group );
  18547. buffer.name = node.name;
  18548. bindings.push( buffer );
  18549. uniformGPU = buffer;
  18550. } else {
  18551. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  18552. let uniformsGroup = uniformsStage[ groupName ];
  18553. if ( uniformsGroup === undefined ) {
  18554. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  18555. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  18556. uniformsStage[ groupName ] = uniformsGroup;
  18557. bindings.push( uniformsGroup );
  18558. }
  18559. uniformGPU = this.getNodeUniform( uniformNode, type );
  18560. uniformsGroup.addUniform( uniformGPU );
  18561. }
  18562. nodeData.uniformGPU = uniformGPU;
  18563. }
  18564. return uniformNode;
  18565. }
  18566. }
  18567. let vector2 = null;
  18568. let vector4 = null;
  18569. let color4 = null;
  18570. class Backend {
  18571. constructor( parameters = {} ) {
  18572. this.parameters = Object.assign( {}, parameters );
  18573. this.data = new WeakMap();
  18574. this.renderer = null;
  18575. this.domElement = null;
  18576. }
  18577. async init( renderer ) {
  18578. this.renderer = renderer;
  18579. }
  18580. // render context
  18581. begin( /*renderContext*/ ) { }
  18582. finish( /*renderContext*/ ) { }
  18583. // render object
  18584. draw( /*renderObject, info*/ ) { }
  18585. // program
  18586. createProgram( /*program*/ ) { }
  18587. destroyProgram( /*program*/ ) { }
  18588. // bindings
  18589. createBindings( /*bingGroup, bindings*/ ) { }
  18590. updateBindings( /*bingGroup, bindings*/ ) { }
  18591. // pipeline
  18592. createRenderPipeline( /*renderObject*/ ) { }
  18593. createComputePipeline( /*computeNode, pipeline*/ ) { }
  18594. destroyPipeline( /*pipeline*/ ) { }
  18595. // cache key
  18596. needsRenderUpdate( /*renderObject*/ ) { } // return Boolean ( fast test )
  18597. getRenderCacheKey( /*renderObject*/ ) { } // return String
  18598. // node builder
  18599. createNodeBuilder( /*renderObject*/ ) { } // return NodeBuilder (ADD IT)
  18600. // textures
  18601. createSampler( /*texture*/ ) { }
  18602. createDefaultTexture( /*texture*/ ) { }
  18603. createTexture( /*texture*/ ) { }
  18604. copyTextureToBuffer( /*texture, x, y, width, height*/ ) {}
  18605. // attributes
  18606. createAttribute( /*attribute*/ ) { }
  18607. createIndexAttribute( /*attribute*/ ) { }
  18608. updateAttribute( /*attribute*/ ) { }
  18609. destroyAttribute( /*attribute*/ ) { }
  18610. // canvas
  18611. getContext() { }
  18612. updateSize() { }
  18613. // utils
  18614. resolveTimestampAsync( /*renderContext, type*/ ) { }
  18615. hasFeatureAsync( /*name*/ ) { } // return Boolean
  18616. hasFeature( /*name*/ ) { } // return Boolean
  18617. getInstanceCount( renderObject ) {
  18618. const { object, geometry } = renderObject;
  18619. return geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  18620. }
  18621. getDrawingBufferSize() {
  18622. vector2 = vector2 || new Vector2();
  18623. return this.renderer.getDrawingBufferSize( vector2 );
  18624. }
  18625. getScissor() {
  18626. vector4 = vector4 || new Vector4();
  18627. return this.renderer.getScissor( vector4 );
  18628. }
  18629. setScissorTest( /*boolean*/ ) { }
  18630. getClearColor() {
  18631. const renderer = this.renderer;
  18632. color4 = color4 || new Color4();
  18633. renderer.getClearColor( color4 );
  18634. color4.getRGB( color4, this.renderer.currentColorSpace );
  18635. return color4;
  18636. }
  18637. getDomElement() {
  18638. let domElement = this.domElement;
  18639. if ( domElement === null ) {
  18640. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  18641. // OffscreenCanvas does not have setAttribute, see #22811
  18642. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  18643. this.domElement = domElement;
  18644. }
  18645. return domElement;
  18646. }
  18647. // resource properties
  18648. set( object, value ) {
  18649. this.data.set( object, value );
  18650. }
  18651. get( object ) {
  18652. let map = this.data.get( object );
  18653. if ( map === undefined ) {
  18654. map = {};
  18655. this.data.set( object, map );
  18656. }
  18657. return map;
  18658. }
  18659. has( object ) {
  18660. return this.data.has( object );
  18661. }
  18662. delete( object ) {
  18663. this.data.delete( object );
  18664. }
  18665. dispose() { }
  18666. }
  18667. let _id$1 = 0;
  18668. class DualAttributeData {
  18669. constructor( attributeData, dualBuffer ) {
  18670. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  18671. this.type = attributeData.type;
  18672. this.bufferType = attributeData.bufferType;
  18673. this.pbo = attributeData.pbo;
  18674. this.byteLength = attributeData.byteLength;
  18675. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  18676. this.version = attributeData.version;
  18677. this.isInteger = attributeData.isInteger;
  18678. this.activeBufferIndex = 0;
  18679. this.baseId = attributeData.id;
  18680. }
  18681. get id() {
  18682. return `${ this.baseId }|${ this.activeBufferIndex }`;
  18683. }
  18684. get bufferGPU() {
  18685. return this.buffers[ this.activeBufferIndex ];
  18686. }
  18687. get transformBuffer() {
  18688. return this.buffers[ this.activeBufferIndex ^ 1 ];
  18689. }
  18690. switchBuffers() {
  18691. this.activeBufferIndex ^= 1;
  18692. }
  18693. }
  18694. class WebGLAttributeUtils {
  18695. constructor( backend ) {
  18696. this.backend = backend;
  18697. }
  18698. createAttribute( attribute, bufferType ) {
  18699. const backend = this.backend;
  18700. const { gl } = backend;
  18701. const array = attribute.array;
  18702. const usage = attribute.usage || gl.STATIC_DRAW;
  18703. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  18704. const bufferData = backend.get( bufferAttribute );
  18705. let bufferGPU = bufferData.bufferGPU;
  18706. if ( bufferGPU === undefined ) {
  18707. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  18708. bufferData.bufferGPU = bufferGPU;
  18709. bufferData.bufferType = bufferType;
  18710. bufferData.version = bufferAttribute.version;
  18711. }
  18712. //attribute.onUploadCallback();
  18713. let type;
  18714. if ( array instanceof Float32Array ) {
  18715. type = gl.FLOAT;
  18716. } else if ( array instanceof Uint16Array ) {
  18717. if ( attribute.isFloat16BufferAttribute ) {
  18718. type = gl.HALF_FLOAT;
  18719. } else {
  18720. type = gl.UNSIGNED_SHORT;
  18721. }
  18722. } else if ( array instanceof Int16Array ) {
  18723. type = gl.SHORT;
  18724. } else if ( array instanceof Uint32Array ) {
  18725. type = gl.UNSIGNED_INT;
  18726. } else if ( array instanceof Int32Array ) {
  18727. type = gl.INT;
  18728. } else if ( array instanceof Int8Array ) {
  18729. type = gl.BYTE;
  18730. } else if ( array instanceof Uint8Array ) {
  18731. type = gl.UNSIGNED_BYTE;
  18732. } else if ( array instanceof Uint8ClampedArray ) {
  18733. type = gl.UNSIGNED_BYTE;
  18734. } else {
  18735. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  18736. }
  18737. let attributeData = {
  18738. bufferGPU,
  18739. bufferType,
  18740. type,
  18741. byteLength: array.byteLength,
  18742. bytesPerElement: array.BYTES_PER_ELEMENT,
  18743. version: attribute.version,
  18744. pbo: attribute.pbo,
  18745. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  18746. id: _id$1 ++
  18747. };
  18748. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  18749. // create buffer for tranform feedback use
  18750. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  18751. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  18752. }
  18753. backend.set( attribute, attributeData );
  18754. }
  18755. updateAttribute( attribute ) {
  18756. const backend = this.backend;
  18757. const { gl } = backend;
  18758. const array = attribute.array;
  18759. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  18760. const bufferData = backend.get( bufferAttribute );
  18761. const bufferType = bufferData.bufferType;
  18762. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  18763. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  18764. if ( updateRanges.length === 0 ) {
  18765. // Not using update ranges
  18766. gl.bufferSubData( bufferType, 0, array );
  18767. } else {
  18768. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  18769. const range = updateRanges[ i ];
  18770. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  18771. array, range.start, range.count );
  18772. }
  18773. bufferAttribute.clearUpdateRanges();
  18774. }
  18775. gl.bindBuffer( bufferType, null );
  18776. bufferData.version = bufferAttribute.version;
  18777. }
  18778. destroyAttribute( attribute ) {
  18779. const backend = this.backend;
  18780. const { gl } = backend;
  18781. if ( attribute.isInterleavedBufferAttribute ) {
  18782. backend.delete( attribute.data );
  18783. }
  18784. const attributeData = backend.get( attribute );
  18785. gl.deleteBuffer( attributeData.bufferGPU );
  18786. backend.delete( attribute );
  18787. }
  18788. async getArrayBufferAsync( attribute ) {
  18789. const backend = this.backend;
  18790. const { gl } = backend;
  18791. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  18792. const { bufferGPU } = backend.get( bufferAttribute );
  18793. const array = attribute.array;
  18794. const byteLength = array.byteLength;
  18795. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  18796. const writeBuffer = gl.createBuffer();
  18797. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  18798. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  18799. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  18800. await backend.utils._clientWaitAsync();
  18801. const dstBuffer = new attribute.array.constructor( array.length );
  18802. // Ensure the buffer is bound before reading
  18803. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  18804. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  18805. gl.deleteBuffer( writeBuffer );
  18806. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  18807. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  18808. return dstBuffer.buffer;
  18809. }
  18810. _createBuffer( gl, bufferType, array, usage ) {
  18811. const bufferGPU = gl.createBuffer();
  18812. gl.bindBuffer( bufferType, bufferGPU );
  18813. gl.bufferData( bufferType, array, usage );
  18814. gl.bindBuffer( bufferType, null );
  18815. return bufferGPU;
  18816. }
  18817. }
  18818. let initialized$1 = false, equationToGL, factorToGL;
  18819. class WebGLState {
  18820. constructor( backend ) {
  18821. this.backend = backend;
  18822. this.gl = this.backend.gl;
  18823. this.enabled = {};
  18824. this.currentFlipSided = null;
  18825. this.currentCullFace = null;
  18826. this.currentProgram = null;
  18827. this.currentBlendingEnabled = false;
  18828. this.currentBlending = null;
  18829. this.currentBlendSrc = null;
  18830. this.currentBlendDst = null;
  18831. this.currentBlendSrcAlpha = null;
  18832. this.currentBlendDstAlpha = null;
  18833. this.currentPremultipledAlpha = null;
  18834. this.currentPolygonOffsetFactor = null;
  18835. this.currentPolygonOffsetUnits = null;
  18836. this.currentColorMask = null;
  18837. this.currentDepthFunc = null;
  18838. this.currentDepthMask = null;
  18839. this.currentStencilFunc = null;
  18840. this.currentStencilRef = null;
  18841. this.currentStencilFuncMask = null;
  18842. this.currentStencilFail = null;
  18843. this.currentStencilZFail = null;
  18844. this.currentStencilZPass = null;
  18845. this.currentStencilMask = null;
  18846. this.currentLineWidth = null;
  18847. this.currentClippingPlanes = 0;
  18848. this.currentBoundFramebuffers = {};
  18849. this.currentDrawbuffers = new WeakMap();
  18850. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  18851. this.currentTextureSlot = null;
  18852. this.currentBoundTextures = {};
  18853. this.currentBoundBufferBases = {};
  18854. if ( initialized$1 === false ) {
  18855. this._init( this.gl );
  18856. initialized$1 = true;
  18857. }
  18858. }
  18859. _init( gl ) {
  18860. // Store only WebGL constants here.
  18861. equationToGL = {
  18862. [ AddEquation ]: gl.FUNC_ADD,
  18863. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  18864. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  18865. };
  18866. factorToGL = {
  18867. [ ZeroFactor ]: gl.ZERO,
  18868. [ OneFactor ]: gl.ONE,
  18869. [ SrcColorFactor ]: gl.SRC_COLOR,
  18870. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  18871. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  18872. [ DstColorFactor ]: gl.DST_COLOR,
  18873. [ DstAlphaFactor ]: gl.DST_ALPHA,
  18874. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  18875. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  18876. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  18877. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  18878. };
  18879. }
  18880. enable( id ) {
  18881. const { enabled } = this;
  18882. if ( enabled[ id ] !== true ) {
  18883. this.gl.enable( id );
  18884. enabled[ id ] = true;
  18885. }
  18886. }
  18887. disable( id ) {
  18888. const { enabled } = this;
  18889. if ( enabled[ id ] !== false ) {
  18890. this.gl.disable( id );
  18891. enabled[ id ] = false;
  18892. }
  18893. }
  18894. setFlipSided( flipSided ) {
  18895. if ( this.currentFlipSided !== flipSided ) {
  18896. const { gl } = this;
  18897. if ( flipSided ) {
  18898. gl.frontFace( gl.CW );
  18899. } else {
  18900. gl.frontFace( gl.CCW );
  18901. }
  18902. this.currentFlipSided = flipSided;
  18903. }
  18904. }
  18905. setCullFace( cullFace ) {
  18906. const { gl } = this;
  18907. if ( cullFace !== CullFaceNone ) {
  18908. this.enable( gl.CULL_FACE );
  18909. if ( cullFace !== this.currentCullFace ) {
  18910. if ( cullFace === CullFaceBack ) {
  18911. gl.cullFace( gl.BACK );
  18912. } else if ( cullFace === CullFaceFront ) {
  18913. gl.cullFace( gl.FRONT );
  18914. } else {
  18915. gl.cullFace( gl.FRONT_AND_BACK );
  18916. }
  18917. }
  18918. } else {
  18919. this.disable( gl.CULL_FACE );
  18920. }
  18921. this.currentCullFace = cullFace;
  18922. }
  18923. setLineWidth( width ) {
  18924. const { currentLineWidth, gl } = this;
  18925. if ( width !== currentLineWidth ) {
  18926. gl.lineWidth( width );
  18927. this.currentLineWidth = width;
  18928. }
  18929. }
  18930. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  18931. const { gl } = this;
  18932. if ( blending === NoBlending ) {
  18933. if ( this.currentBlendingEnabled === true ) {
  18934. this.disable( gl.BLEND );
  18935. this.currentBlendingEnabled = false;
  18936. }
  18937. return;
  18938. }
  18939. if ( this.currentBlendingEnabled === false ) {
  18940. this.enable( gl.BLEND );
  18941. this.currentBlendingEnabled = true;
  18942. }
  18943. if ( blending !== CustomBlending ) {
  18944. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  18945. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  18946. gl.blendEquation( gl.FUNC_ADD );
  18947. this.currentBlendEquation = AddEquation;
  18948. this.currentBlendEquationAlpha = AddEquation;
  18949. }
  18950. if ( premultipliedAlpha ) {
  18951. switch ( blending ) {
  18952. case NormalBlending:
  18953. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  18954. break;
  18955. case AdditiveBlending:
  18956. gl.blendFunc( gl.ONE, gl.ONE );
  18957. break;
  18958. case SubtractiveBlending:
  18959. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  18960. break;
  18961. case MultiplyBlending:
  18962. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  18963. break;
  18964. default:
  18965. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  18966. break;
  18967. }
  18968. } else {
  18969. switch ( blending ) {
  18970. case NormalBlending:
  18971. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  18972. break;
  18973. case AdditiveBlending:
  18974. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  18975. break;
  18976. case SubtractiveBlending:
  18977. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  18978. break;
  18979. case MultiplyBlending:
  18980. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  18981. break;
  18982. default:
  18983. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  18984. break;
  18985. }
  18986. }
  18987. this.currentBlendSrc = null;
  18988. this.currentBlendDst = null;
  18989. this.currentBlendSrcAlpha = null;
  18990. this.currentBlendDstAlpha = null;
  18991. this.currentBlending = blending;
  18992. this.currentPremultipledAlpha = premultipliedAlpha;
  18993. }
  18994. return;
  18995. }
  18996. // custom blending
  18997. blendEquationAlpha = blendEquationAlpha || blendEquation;
  18998. blendSrcAlpha = blendSrcAlpha || blendSrc;
  18999. blendDstAlpha = blendDstAlpha || blendDst;
  19000. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  19001. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  19002. this.currentBlendEquation = blendEquation;
  19003. this.currentBlendEquationAlpha = blendEquationAlpha;
  19004. }
  19005. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  19006. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  19007. this.currentBlendSrc = blendSrc;
  19008. this.currentBlendDst = blendDst;
  19009. this.currentBlendSrcAlpha = blendSrcAlpha;
  19010. this.currentBlendDstAlpha = blendDstAlpha;
  19011. }
  19012. this.currentBlending = blending;
  19013. this.currentPremultipledAlpha = false;
  19014. }
  19015. setColorMask( colorMask ) {
  19016. if ( this.currentColorMask !== colorMask ) {
  19017. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  19018. this.currentColorMask = colorMask;
  19019. }
  19020. }
  19021. setDepthTest( depthTest ) {
  19022. const { gl } = this;
  19023. if ( depthTest ) {
  19024. this.enable( gl.DEPTH_TEST );
  19025. } else {
  19026. this.disable( gl.DEPTH_TEST );
  19027. }
  19028. }
  19029. setDepthMask( depthMask ) {
  19030. if ( this.currentDepthMask !== depthMask ) {
  19031. this.gl.depthMask( depthMask );
  19032. this.currentDepthMask = depthMask;
  19033. }
  19034. }
  19035. setDepthFunc( depthFunc ) {
  19036. if ( this.currentDepthFunc !== depthFunc ) {
  19037. const { gl } = this;
  19038. switch ( depthFunc ) {
  19039. case NeverDepth:
  19040. gl.depthFunc( gl.NEVER );
  19041. break;
  19042. case AlwaysDepth:
  19043. gl.depthFunc( gl.ALWAYS );
  19044. break;
  19045. case LessDepth:
  19046. gl.depthFunc( gl.LESS );
  19047. break;
  19048. case LessEqualDepth:
  19049. gl.depthFunc( gl.LEQUAL );
  19050. break;
  19051. case EqualDepth:
  19052. gl.depthFunc( gl.EQUAL );
  19053. break;
  19054. case GreaterEqualDepth:
  19055. gl.depthFunc( gl.GEQUAL );
  19056. break;
  19057. case GreaterDepth:
  19058. gl.depthFunc( gl.GREATER );
  19059. break;
  19060. case NotEqualDepth:
  19061. gl.depthFunc( gl.NOTEQUAL );
  19062. break;
  19063. default:
  19064. gl.depthFunc( gl.LEQUAL );
  19065. }
  19066. this.currentDepthFunc = depthFunc;
  19067. }
  19068. }
  19069. setStencilTest( stencilTest ) {
  19070. const { gl } = this;
  19071. if ( stencilTest ) {
  19072. this.enable( gl.STENCIL_TEST );
  19073. } else {
  19074. this.disable( gl.STENCIL_TEST );
  19075. }
  19076. }
  19077. setStencilMask( stencilMask ) {
  19078. if ( this.currentStencilMask !== stencilMask ) {
  19079. this.gl.stencilMask( stencilMask );
  19080. this.currentStencilMask = stencilMask;
  19081. }
  19082. }
  19083. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  19084. if ( this.currentStencilFunc !== stencilFunc ||
  19085. this.currentStencilRef !== stencilRef ||
  19086. this.currentStencilFuncMask !== stencilMask ) {
  19087. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  19088. this.currentStencilFunc = stencilFunc;
  19089. this.currentStencilRef = stencilRef;
  19090. this.currentStencilFuncMask = stencilMask;
  19091. }
  19092. }
  19093. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  19094. if ( this.currentStencilFail !== stencilFail ||
  19095. this.currentStencilZFail !== stencilZFail ||
  19096. this.currentStencilZPass !== stencilZPass ) {
  19097. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  19098. this.currentStencilFail = stencilFail;
  19099. this.currentStencilZFail = stencilZFail;
  19100. this.currentStencilZPass = stencilZPass;
  19101. }
  19102. }
  19103. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  19104. const { gl } = this;
  19105. material.side === DoubleSide
  19106. ? this.disable( gl.CULL_FACE )
  19107. : this.enable( gl.CULL_FACE );
  19108. let flipSided = ( material.side === BackSide );
  19109. if ( frontFaceCW ) flipSided = ! flipSided;
  19110. this.setFlipSided( flipSided );
  19111. ( material.blending === NormalBlending && material.transparent === false )
  19112. ? this.setBlending( NoBlending )
  19113. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  19114. this.setDepthFunc( material.depthFunc );
  19115. this.setDepthTest( material.depthTest );
  19116. this.setDepthMask( material.depthWrite );
  19117. this.setColorMask( material.colorWrite );
  19118. const stencilWrite = material.stencilWrite;
  19119. this.setStencilTest( stencilWrite );
  19120. if ( stencilWrite ) {
  19121. this.setStencilMask( material.stencilWriteMask );
  19122. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  19123. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  19124. }
  19125. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  19126. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  19127. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  19128. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  19129. if ( hardwareClippingPlanes > 0 ) {
  19130. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  19131. const CLIP_DISTANCE0_WEBGL = 0x3000;
  19132. for ( let i = 0; i < 8; i ++ ) {
  19133. if ( i < hardwareClippingPlanes ) {
  19134. this.enable( CLIP_DISTANCE0_WEBGL + i );
  19135. } else {
  19136. this.disable( CLIP_DISTANCE0_WEBGL + i );
  19137. }
  19138. }
  19139. }
  19140. }
  19141. }
  19142. setPolygonOffset( polygonOffset, factor, units ) {
  19143. const { gl } = this;
  19144. if ( polygonOffset ) {
  19145. this.enable( gl.POLYGON_OFFSET_FILL );
  19146. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  19147. gl.polygonOffset( factor, units );
  19148. this.currentPolygonOffsetFactor = factor;
  19149. this.currentPolygonOffsetUnits = units;
  19150. }
  19151. } else {
  19152. this.disable( gl.POLYGON_OFFSET_FILL );
  19153. }
  19154. }
  19155. useProgram( program ) {
  19156. if ( this.currentProgram !== program ) {
  19157. this.gl.useProgram( program );
  19158. this.currentProgram = program;
  19159. return true;
  19160. }
  19161. return false;
  19162. }
  19163. // framebuffer
  19164. bindFramebuffer( target, framebuffer ) {
  19165. const { gl, currentBoundFramebuffers } = this;
  19166. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  19167. gl.bindFramebuffer( target, framebuffer );
  19168. currentBoundFramebuffers[ target ] = framebuffer;
  19169. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  19170. if ( target === gl.DRAW_FRAMEBUFFER ) {
  19171. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  19172. }
  19173. if ( target === gl.FRAMEBUFFER ) {
  19174. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  19175. }
  19176. return true;
  19177. }
  19178. return false;
  19179. }
  19180. drawBuffers( renderContext, framebuffer ) {
  19181. const { gl } = this;
  19182. let drawBuffers = [];
  19183. let needsUpdate = false;
  19184. if ( renderContext.textures !== null ) {
  19185. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  19186. if ( drawBuffers === undefined ) {
  19187. drawBuffers = [];
  19188. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  19189. }
  19190. const textures = renderContext.textures;
  19191. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  19192. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  19193. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  19194. }
  19195. drawBuffers.length = textures.length;
  19196. needsUpdate = true;
  19197. }
  19198. } else {
  19199. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  19200. drawBuffers[ 0 ] = gl.BACK;
  19201. needsUpdate = true;
  19202. }
  19203. }
  19204. if ( needsUpdate ) {
  19205. gl.drawBuffers( drawBuffers );
  19206. }
  19207. }
  19208. // texture
  19209. activeTexture( webglSlot ) {
  19210. const { gl, currentTextureSlot, maxTextures } = this;
  19211. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  19212. if ( currentTextureSlot !== webglSlot ) {
  19213. gl.activeTexture( webglSlot );
  19214. this.currentTextureSlot = webglSlot;
  19215. }
  19216. }
  19217. bindTexture( webglType, webglTexture, webglSlot ) {
  19218. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  19219. if ( webglSlot === undefined ) {
  19220. if ( currentTextureSlot === null ) {
  19221. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  19222. } else {
  19223. webglSlot = currentTextureSlot;
  19224. }
  19225. }
  19226. let boundTexture = currentBoundTextures[ webglSlot ];
  19227. if ( boundTexture === undefined ) {
  19228. boundTexture = { type: undefined, texture: undefined };
  19229. currentBoundTextures[ webglSlot ] = boundTexture;
  19230. }
  19231. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  19232. if ( currentTextureSlot !== webglSlot ) {
  19233. gl.activeTexture( webglSlot );
  19234. this.currentTextureSlot = webglSlot;
  19235. }
  19236. gl.bindTexture( webglType, webglTexture );
  19237. boundTexture.type = webglType;
  19238. boundTexture.texture = webglTexture;
  19239. }
  19240. }
  19241. bindBufferBase( target, index, buffer ) {
  19242. const { gl } = this;
  19243. const key = `${target}-${index}`;
  19244. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  19245. gl.bindBufferBase( target, index, buffer );
  19246. this.currentBoundBufferBases[ key ] = buffer;
  19247. return true;
  19248. }
  19249. return false;
  19250. }
  19251. unbindTexture() {
  19252. const { gl, currentTextureSlot, currentBoundTextures } = this;
  19253. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  19254. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  19255. gl.bindTexture( boundTexture.type, null );
  19256. boundTexture.type = undefined;
  19257. boundTexture.texture = undefined;
  19258. }
  19259. }
  19260. }
  19261. class WebGLUtils {
  19262. constructor( backend ) {
  19263. this.backend = backend;
  19264. this.gl = this.backend.gl;
  19265. this.extensions = backend.extensions;
  19266. }
  19267. convert( p, colorSpace = NoColorSpace ) {
  19268. const { gl, extensions } = this;
  19269. let extension;
  19270. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  19271. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  19272. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  19273. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  19274. if ( p === ByteType ) return gl.BYTE;
  19275. if ( p === ShortType ) return gl.SHORT;
  19276. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  19277. if ( p === IntType ) return gl.INT;
  19278. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  19279. if ( p === FloatType ) return gl.FLOAT;
  19280. if ( p === HalfFloatType ) {
  19281. return gl.HALF_FLOAT;
  19282. }
  19283. if ( p === AlphaFormat ) return gl.ALPHA;
  19284. if ( p === RGBFormat ) return gl.RGB;
  19285. if ( p === RGBAFormat ) return gl.RGBA;
  19286. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  19287. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  19288. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  19289. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  19290. // WebGL2 formats.
  19291. if ( p === RedFormat ) return gl.RED;
  19292. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  19293. if ( p === RGFormat ) return gl.RG;
  19294. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  19295. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  19296. // S3TC
  19297. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  19298. if ( colorSpace === SRGBColorSpace ) {
  19299. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  19300. if ( extension !== null ) {
  19301. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  19302. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  19303. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  19304. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  19305. } else {
  19306. return null;
  19307. }
  19308. } else {
  19309. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  19310. if ( extension !== null ) {
  19311. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  19312. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  19313. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  19314. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  19315. } else {
  19316. return null;
  19317. }
  19318. }
  19319. }
  19320. // PVRTC
  19321. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  19322. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  19323. if ( extension !== null ) {
  19324. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  19325. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  19326. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  19327. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  19328. } else {
  19329. return null;
  19330. }
  19331. }
  19332. // ETC
  19333. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  19334. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  19335. if ( extension !== null ) {
  19336. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  19337. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  19338. } else {
  19339. return null;
  19340. }
  19341. }
  19342. // ASTC
  19343. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  19344. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  19345. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  19346. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  19347. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  19348. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  19349. if ( extension !== null ) {
  19350. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  19351. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  19352. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  19353. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  19354. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  19355. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  19356. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  19357. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  19358. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  19359. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  19360. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  19361. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  19362. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  19363. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  19364. } else {
  19365. return null;
  19366. }
  19367. }
  19368. // BPTC
  19369. if ( p === RGBA_BPTC_Format ) {
  19370. extension = extensions.get( 'EXT_texture_compression_bptc' );
  19371. if ( extension !== null ) {
  19372. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  19373. } else {
  19374. return null;
  19375. }
  19376. }
  19377. // RGTC
  19378. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  19379. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  19380. if ( extension !== null ) {
  19381. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  19382. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  19383. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  19384. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  19385. } else {
  19386. return null;
  19387. }
  19388. }
  19389. //
  19390. if ( p === UnsignedInt248Type ) {
  19391. return gl.UNSIGNED_INT_24_8;
  19392. }
  19393. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  19394. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  19395. }
  19396. _clientWaitAsync() {
  19397. const { gl } = this;
  19398. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  19399. gl.flush();
  19400. return new Promise( ( resolve, reject ) => {
  19401. function test() {
  19402. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  19403. if ( res === gl.WAIT_FAILED ) {
  19404. gl.deleteSync( sync );
  19405. reject();
  19406. return;
  19407. }
  19408. if ( res === gl.TIMEOUT_EXPIRED ) {
  19409. requestAnimationFrame( test );
  19410. return;
  19411. }
  19412. gl.deleteSync( sync );
  19413. resolve();
  19414. }
  19415. test();
  19416. } );
  19417. }
  19418. }
  19419. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  19420. class WebGLTextureUtils {
  19421. constructor( backend ) {
  19422. this.backend = backend;
  19423. this.gl = backend.gl;
  19424. this.extensions = backend.extensions;
  19425. this.defaultTextures = {};
  19426. if ( initialized === false ) {
  19427. this._init( this.gl );
  19428. initialized = true;
  19429. }
  19430. }
  19431. _init( gl ) {
  19432. // Store only WebGL constants here.
  19433. wrappingToGL = {
  19434. [ RepeatWrapping ]: gl.REPEAT,
  19435. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  19436. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  19437. };
  19438. filterToGL = {
  19439. [ NearestFilter ]: gl.NEAREST,
  19440. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  19441. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  19442. [ LinearFilter ]: gl.LINEAR,
  19443. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  19444. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  19445. };
  19446. compareToGL = {
  19447. [ NeverCompare ]: gl.NEVER,
  19448. [ AlwaysCompare ]: gl.ALWAYS,
  19449. [ LessCompare ]: gl.LESS,
  19450. [ LessEqualCompare ]: gl.LEQUAL,
  19451. [ EqualCompare ]: gl.EQUAL,
  19452. [ GreaterEqualCompare ]: gl.GEQUAL,
  19453. [ GreaterCompare ]: gl.GREATER,
  19454. [ NotEqualCompare ]: gl.NOTEQUAL
  19455. };
  19456. }
  19457. filterFallback( f ) {
  19458. const { gl } = this;
  19459. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  19460. return gl.NEAREST;
  19461. }
  19462. return gl.LINEAR;
  19463. }
  19464. getGLTextureType( texture ) {
  19465. const { gl } = this;
  19466. let glTextureType;
  19467. if ( texture.isCubeTexture === true ) {
  19468. glTextureType = gl.TEXTURE_CUBE_MAP;
  19469. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  19470. glTextureType = gl.TEXTURE_2D_ARRAY;
  19471. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  19472. glTextureType = gl.TEXTURE_3D;
  19473. } else {
  19474. glTextureType = gl.TEXTURE_2D;
  19475. }
  19476. return glTextureType;
  19477. }
  19478. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  19479. const { gl, extensions } = this;
  19480. if ( internalFormatName !== null ) {
  19481. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  19482. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  19483. }
  19484. let internalFormat = glFormat;
  19485. if ( glFormat === gl.RED ) {
  19486. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  19487. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  19488. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  19489. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  19490. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  19491. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  19492. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  19493. if ( glType === gl.INT ) internalFormat = gl.R32I;
  19494. }
  19495. if ( glFormat === gl.RED_INTEGER ) {
  19496. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  19497. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  19498. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  19499. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  19500. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  19501. if ( glType === gl.INT ) internalFormat = gl.R32I;
  19502. }
  19503. if ( glFormat === gl.RG ) {
  19504. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  19505. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  19506. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  19507. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  19508. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  19509. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  19510. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  19511. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  19512. }
  19513. if ( glFormat === gl.RG_INTEGER ) {
  19514. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  19515. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  19516. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  19517. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  19518. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  19519. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  19520. }
  19521. if ( glFormat === gl.RGB ) {
  19522. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  19523. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  19524. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  19525. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  19526. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  19527. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  19528. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  19529. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  19530. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  19531. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  19532. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  19533. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  19534. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  19535. }
  19536. if ( glFormat === gl.RGB_INTEGER ) {
  19537. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  19538. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  19539. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  19540. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  19541. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  19542. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  19543. }
  19544. if ( glFormat === gl.RGBA ) {
  19545. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  19546. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  19547. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  19548. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  19549. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  19550. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  19551. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  19552. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  19553. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  19554. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  19555. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  19556. }
  19557. if ( glFormat === gl.RGBA_INTEGER ) {
  19558. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  19559. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  19560. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  19561. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  19562. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  19563. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  19564. }
  19565. if ( glFormat === gl.DEPTH_COMPONENT ) {
  19566. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  19567. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  19568. }
  19569. if ( glFormat === gl.DEPTH_STENCIL ) {
  19570. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  19571. }
  19572. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  19573. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  19574. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  19575. extensions.get( 'EXT_color_buffer_float' );
  19576. }
  19577. return internalFormat;
  19578. }
  19579. setTextureParameters( textureType, texture ) {
  19580. const { gl, extensions, backend } = this;
  19581. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  19582. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  19583. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  19584. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  19585. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  19586. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  19587. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  19588. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  19589. }
  19590. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  19591. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  19592. // follow WebGPU backend mapping for texture filtering
  19593. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  19594. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  19595. if ( texture.compareFunction ) {
  19596. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  19597. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  19598. }
  19599. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  19600. if ( texture.magFilter === NearestFilter ) return;
  19601. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  19602. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  19603. if ( texture.anisotropy > 1 ) {
  19604. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  19605. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  19606. }
  19607. }
  19608. }
  19609. createDefaultTexture( texture ) {
  19610. const { gl, backend, defaultTextures } = this;
  19611. const glTextureType = this.getGLTextureType( texture );
  19612. let textureGPU = defaultTextures[ glTextureType ];
  19613. if ( textureGPU === undefined ) {
  19614. textureGPU = gl.createTexture();
  19615. backend.state.bindTexture( glTextureType, textureGPU );
  19616. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  19617. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  19618. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  19619. defaultTextures[ glTextureType ] = textureGPU;
  19620. }
  19621. backend.set( texture, {
  19622. textureGPU,
  19623. glTextureType,
  19624. isDefault: true
  19625. } );
  19626. }
  19627. createTexture( texture, options ) {
  19628. const { gl, backend } = this;
  19629. const { levels, width, height, depth } = options;
  19630. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  19631. const glType = backend.utils.convert( texture.type );
  19632. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  19633. const textureGPU = gl.createTexture();
  19634. const glTextureType = this.getGLTextureType( texture );
  19635. backend.state.bindTexture( glTextureType, textureGPU );
  19636. this.setTextureParameters( glTextureType, texture );
  19637. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  19638. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  19639. } else if ( texture.isData3DTexture ) {
  19640. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  19641. } else if ( ! texture.isVideoTexture ) {
  19642. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  19643. }
  19644. backend.set( texture, {
  19645. textureGPU,
  19646. glTextureType,
  19647. glFormat,
  19648. glType,
  19649. glInternalFormat
  19650. } );
  19651. }
  19652. copyBufferToTexture( buffer, texture ) {
  19653. const { gl, backend } = this;
  19654. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  19655. const { width, height } = texture.source.data;
  19656. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  19657. backend.state.bindTexture( glTextureType, textureGPU );
  19658. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  19659. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  19660. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  19661. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  19662. backend.state.unbindTexture();
  19663. // debug
  19664. // const framebuffer = gl.createFramebuffer();
  19665. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  19666. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  19667. // const readout = new Float32Array( width * height * 4 );
  19668. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  19669. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  19670. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  19671. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  19672. // console.log( readout );
  19673. }
  19674. updateTexture( texture, options ) {
  19675. const { gl } = this;
  19676. const { width, height } = options;
  19677. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  19678. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  19679. return;
  19680. const getImage = ( source ) => {
  19681. if ( source.isDataTexture ) {
  19682. return source.image.data;
  19683. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  19684. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  19685. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  19686. source instanceof OffscreenCanvas ) {
  19687. return source;
  19688. }
  19689. return source.data;
  19690. };
  19691. this.backend.state.bindTexture( glTextureType, textureGPU );
  19692. this.setTextureParameters( glTextureType, texture );
  19693. if ( texture.isCompressedTexture ) {
  19694. const mipmaps = texture.mipmaps;
  19695. const image = options.image;
  19696. for ( let i = 0; i < mipmaps.length; i ++ ) {
  19697. const mipmap = mipmaps[ i ];
  19698. if ( texture.isCompressedArrayTexture ) {
  19699. if ( texture.format !== gl.RGBA ) {
  19700. if ( glFormat !== null ) {
  19701. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  19702. } else {
  19703. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  19704. }
  19705. } else {
  19706. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  19707. }
  19708. } else {
  19709. if ( glFormat !== null ) {
  19710. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  19711. } else {
  19712. console.warn( 'Unsupported compressed texture format' );
  19713. }
  19714. }
  19715. }
  19716. } else if ( texture.isCubeTexture ) {
  19717. const images = options.images;
  19718. for ( let i = 0; i < 6; i ++ ) {
  19719. const image = getImage( images[ i ] );
  19720. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  19721. }
  19722. } else if ( texture.isDataArrayTexture ) {
  19723. const image = options.image;
  19724. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  19725. } else if ( texture.isData3DTexture ) {
  19726. const image = options.image;
  19727. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  19728. } else if ( texture.isVideoTexture ) {
  19729. texture.update();
  19730. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  19731. } else {
  19732. const image = getImage( options.image );
  19733. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  19734. }
  19735. }
  19736. generateMipmaps( texture ) {
  19737. const { gl, backend } = this;
  19738. const { textureGPU, glTextureType } = backend.get( texture );
  19739. backend.state.bindTexture( glTextureType, textureGPU );
  19740. gl.generateMipmap( glTextureType );
  19741. }
  19742. deallocateRenderBuffers( renderTarget ) {
  19743. const { gl, backend } = this;
  19744. // remove framebuffer reference
  19745. if ( renderTarget ) {
  19746. const renderContextData = backend.get( renderTarget );
  19747. renderContextData.renderBufferStorageSetup = undefined;
  19748. if ( renderContextData.framebuffers ) {
  19749. for ( const cacheKey in renderContextData.framebuffers ) {
  19750. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  19751. }
  19752. delete renderContextData.framebuffers;
  19753. }
  19754. if ( renderContextData.depthRenderbuffer ) {
  19755. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  19756. delete renderContextData.depthRenderbuffer;
  19757. }
  19758. if ( renderContextData.stencilRenderbuffer ) {
  19759. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  19760. delete renderContextData.stencilRenderbuffer;
  19761. }
  19762. if ( renderContextData.msaaFrameBuffer ) {
  19763. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  19764. delete renderContextData.msaaFrameBuffer;
  19765. }
  19766. if ( renderContextData.msaaRenderbuffers ) {
  19767. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  19768. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  19769. }
  19770. delete renderContextData.msaaRenderbuffers;
  19771. }
  19772. }
  19773. }
  19774. destroyTexture( texture ) {
  19775. const { gl, backend } = this;
  19776. const { textureGPU, renderTarget } = backend.get( texture );
  19777. this.deallocateRenderBuffers( renderTarget );
  19778. gl.deleteTexture( textureGPU );
  19779. backend.delete( texture );
  19780. }
  19781. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  19782. const { gl, backend } = this;
  19783. const { state } = this.backend;
  19784. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  19785. let width, height, minX, minY;
  19786. let dstX, dstY;
  19787. if ( srcRegion !== null ) {
  19788. width = srcRegion.max.x - srcRegion.min.x;
  19789. height = srcRegion.max.y - srcRegion.min.y;
  19790. minX = srcRegion.min.x;
  19791. minY = srcRegion.min.y;
  19792. } else {
  19793. width = srcTexture.image.width;
  19794. height = srcTexture.image.height;
  19795. minX = 0;
  19796. minY = 0;
  19797. }
  19798. if ( dstPosition !== null ) {
  19799. dstX = dstPosition.x;
  19800. dstY = dstPosition.y;
  19801. } else {
  19802. dstX = 0;
  19803. dstY = 0;
  19804. }
  19805. state.bindTexture( glTextureType, dstTextureGPU );
  19806. // As another texture upload may have changed pixelStorei
  19807. // parameters, make sure they are correct for the dstTexture
  19808. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  19809. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  19810. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  19811. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  19812. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  19813. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  19814. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  19815. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  19816. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  19817. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  19818. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  19819. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  19820. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  19821. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  19822. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  19823. const srcTextureData = backend.get( srcTexture );
  19824. const dstTextureData = backend.get( dstTexture );
  19825. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  19826. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  19827. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  19828. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  19829. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  19830. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  19831. let mask = gl.COLOR_BUFFER_BIT;
  19832. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  19833. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  19834. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  19835. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  19836. } else {
  19837. if ( srcTexture.isDataTexture ) {
  19838. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  19839. } else {
  19840. if ( srcTexture.isCompressedTexture ) {
  19841. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  19842. } else {
  19843. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  19844. }
  19845. }
  19846. }
  19847. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  19848. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  19849. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  19850. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  19851. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  19852. // Generate mipmaps only when copying level 0
  19853. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  19854. state.unbindTexture();
  19855. }
  19856. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  19857. const { gl } = this;
  19858. const { state } = this.backend;
  19859. const { textureGPU } = this.backend.get( texture );
  19860. const { x, y, z: width, w: height } = rectangle;
  19861. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  19862. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.gerDrawingBufferSize().y;
  19863. if ( requireDrawFrameBuffer ) {
  19864. const partial = ( x !== 0 || y !== 0 );
  19865. let mask;
  19866. let attachment;
  19867. if ( texture.isDepthTexture === true ) {
  19868. mask = gl.DEPTH_BUFFER_BIT;
  19869. attachment = gl.DEPTH_ATTACHMENT;
  19870. if ( renderContext.stencil ) {
  19871. mask |= gl.STENCIL_BUFFER_BIT;
  19872. }
  19873. } else {
  19874. mask = gl.COLOR_BUFFER_BIT;
  19875. attachment = gl.COLOR_ATTACHMENT0;
  19876. }
  19877. if ( partial ) {
  19878. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  19879. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  19880. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  19881. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  19882. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  19883. const flippedY = srcHeight - y - height;
  19884. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  19885. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  19886. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  19887. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  19888. state.unbindTexture();
  19889. } else {
  19890. const fb = gl.createFramebuffer();
  19891. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  19892. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  19893. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  19894. gl.deleteFramebuffer( fb );
  19895. }
  19896. } else {
  19897. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  19898. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  19899. state.unbindTexture();
  19900. }
  19901. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  19902. this.backend._setFramebuffer( renderContext );
  19903. }
  19904. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  19905. setupRenderBufferStorage( renderbuffer, renderContext ) {
  19906. const { gl } = this;
  19907. const renderTarget = renderContext.renderTarget;
  19908. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  19909. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  19910. if ( depthBuffer && ! stencilBuffer ) {
  19911. let glInternalFormat = gl.DEPTH_COMPONENT24;
  19912. if ( samples > 0 ) {
  19913. if ( depthTexture && depthTexture.isDepthTexture ) {
  19914. if ( depthTexture.type === gl.FLOAT ) {
  19915. glInternalFormat = gl.DEPTH_COMPONENT32F;
  19916. }
  19917. }
  19918. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  19919. } else {
  19920. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  19921. }
  19922. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  19923. } else if ( depthBuffer && stencilBuffer ) {
  19924. if ( samples > 0 ) {
  19925. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  19926. } else {
  19927. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  19928. }
  19929. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  19930. }
  19931. }
  19932. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  19933. const { backend, gl } = this;
  19934. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  19935. const fb = gl.createFramebuffer();
  19936. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  19937. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  19938. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  19939. const typedArrayType = this._getTypedArrayType( glType );
  19940. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  19941. const elementCount = width * height;
  19942. const byteLength = elementCount * bytesPerTexel;
  19943. const buffer = gl.createBuffer();
  19944. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  19945. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  19946. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  19947. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  19948. await backend.utils._clientWaitAsync();
  19949. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  19950. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  19951. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  19952. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  19953. gl.deleteFramebuffer( fb );
  19954. return dstBuffer;
  19955. }
  19956. _getTypedArrayType( glType ) {
  19957. const { gl } = this;
  19958. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  19959. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  19960. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  19961. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  19962. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  19963. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  19964. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  19965. if ( glType === gl.FLOAT ) return Float32Array;
  19966. throw new Error( `Unsupported WebGL type: ${glType}` );
  19967. }
  19968. _getBytesPerTexel( glType, glFormat ) {
  19969. const { gl } = this;
  19970. let bytesPerComponent = 0;
  19971. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  19972. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  19973. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  19974. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  19975. glType === gl.UNSIGNED_SHORT ||
  19976. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  19977. if ( glType === gl.UNSIGNED_INT ||
  19978. glType === gl.FLOAT ) bytesPerComponent = 4;
  19979. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  19980. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  19981. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  19982. }
  19983. }
  19984. class WebGLExtensions {
  19985. constructor( backend ) {
  19986. this.backend = backend;
  19987. this.gl = this.backend.gl;
  19988. this.availableExtensions = this.gl.getSupportedExtensions();
  19989. this.extensions = {};
  19990. }
  19991. get( name ) {
  19992. let extension = this.extensions[ name ];
  19993. if ( extension === undefined ) {
  19994. extension = this.gl.getExtension( name );
  19995. this.extensions[ name ] = extension;
  19996. }
  19997. return extension;
  19998. }
  19999. has( name ) {
  20000. return this.availableExtensions.includes( name );
  20001. }
  20002. }
  20003. class WebGLCapabilities {
  20004. constructor( backend ) {
  20005. this.backend = backend;
  20006. this.maxAnisotropy = null;
  20007. }
  20008. getMaxAnisotropy() {
  20009. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  20010. const gl = this.backend.gl;
  20011. const extensions = this.backend.extensions;
  20012. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  20013. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  20014. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  20015. } else {
  20016. this.maxAnisotropy = 0;
  20017. }
  20018. return this.maxAnisotropy;
  20019. }
  20020. }
  20021. const GLFeatureName = {
  20022. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  20023. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  20024. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  20025. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  20026. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  20027. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  20028. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  20029. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  20030. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  20031. };
  20032. class WebGLBufferRenderer {
  20033. constructor( backend ) {
  20034. this.gl = backend.gl;
  20035. this.extensions = backend.extensions;
  20036. this.info = backend.renderer.info;
  20037. this.mode = null;
  20038. this.index = 0;
  20039. this.type = null;
  20040. this.object = null;
  20041. }
  20042. render( start, count ) {
  20043. const { gl, mode, object, type, info, index } = this;
  20044. if ( index !== 0 ) {
  20045. gl.drawElements( mode, count, type, start );
  20046. } else {
  20047. gl.drawArrays( mode, start, count );
  20048. }
  20049. info.update( object, count, mode, 1 );
  20050. }
  20051. renderInstances( start, count, primcount ) {
  20052. const { gl, mode, type, index, object, info } = this;
  20053. if ( primcount === 0 ) return;
  20054. if ( index !== 0 ) {
  20055. gl.drawElementsInstanced( mode, count, type, start, primcount );
  20056. } else {
  20057. gl.drawArraysInstanced( mode, start, count, primcount );
  20058. }
  20059. info.update( object, count, mode, primcount );
  20060. }
  20061. renderMultiDraw( starts, counts, drawCount ) {
  20062. const { extensions, mode, object, info } = this;
  20063. if ( drawCount === 0 ) return;
  20064. const extension = extensions.get( 'WEBGL_multi_draw' );
  20065. if ( extension === null ) {
  20066. for ( let i = 0; i < drawCount; i ++ ) {
  20067. this.render( starts[ i ], counts[ i ] );
  20068. }
  20069. } else {
  20070. if ( this.index !== 0 ) {
  20071. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  20072. } else {
  20073. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  20074. }
  20075. let elementCount = 0;
  20076. for ( let i = 0; i < drawCount; i ++ ) {
  20077. elementCount += counts[ i ];
  20078. }
  20079. info.update( object, elementCount, mode, 1 );
  20080. }
  20081. }
  20082. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  20083. const { extensions, mode, object, info } = this;
  20084. if ( drawCount === 0 ) return;
  20085. const extension = extensions.get( 'WEBGL_multi_draw' );
  20086. if ( extension === null ) {
  20087. for ( let i = 0; i < drawCount; i ++ ) {
  20088. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  20089. }
  20090. } else {
  20091. if ( this.index !== 0 ) {
  20092. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  20093. } else {
  20094. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  20095. }
  20096. let elementCount = 0;
  20097. for ( let i = 0; i < drawCount; i ++ ) {
  20098. elementCount += counts[ i ] * primcount[ i ];
  20099. }
  20100. info.update( object, elementCount, mode, 1 );
  20101. }
  20102. }
  20103. //
  20104. }
  20105. //
  20106. class WebGLBackend extends Backend {
  20107. constructor( parameters = {} ) {
  20108. super( parameters );
  20109. this.isWebGLBackend = true;
  20110. }
  20111. init( renderer ) {
  20112. super.init( renderer );
  20113. //
  20114. const parameters = this.parameters;
  20115. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  20116. function onContextLost( event ) {
  20117. event.preventDefault();
  20118. const contextLossInfo = {
  20119. api: 'WebGL',
  20120. message: event.statusMessage || 'Unknown reason',
  20121. reason: null,
  20122. originalEvent: event
  20123. };
  20124. renderer.onDeviceLost( contextLossInfo );
  20125. }
  20126. this._onContextLost = onContextLost;
  20127. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  20128. this.gl = glContext;
  20129. this.extensions = new WebGLExtensions( this );
  20130. this.capabilities = new WebGLCapabilities( this );
  20131. this.attributeUtils = new WebGLAttributeUtils( this );
  20132. this.textureUtils = new WebGLTextureUtils( this );
  20133. this.bufferRenderer = new WebGLBufferRenderer( this );
  20134. this.state = new WebGLState( this );
  20135. this.utils = new WebGLUtils( this );
  20136. this.vaoCache = {};
  20137. this.transformFeedbackCache = {};
  20138. this.discard = false;
  20139. this.trackTimestamp = ( parameters.trackTimestamp === true );
  20140. this.extensions.get( 'EXT_color_buffer_float' );
  20141. this.extensions.get( 'WEBGL_clip_cull_distance' );
  20142. this.extensions.get( 'OES_texture_float_linear' );
  20143. this.extensions.get( 'EXT_color_buffer_half_float' );
  20144. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  20145. this.extensions.get( 'WEBGL_render_shared_exponent' );
  20146. this.extensions.get( 'WEBGL_multi_draw' );
  20147. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  20148. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  20149. this._knownBindings = new WeakSet();
  20150. this._currentContext = null;
  20151. }
  20152. get coordinateSystem() {
  20153. return WebGLCoordinateSystem;
  20154. }
  20155. async getArrayBufferAsync( attribute ) {
  20156. return await this.attributeUtils.getArrayBufferAsync( attribute );
  20157. }
  20158. async waitForGPU() {
  20159. await this.utils._clientWaitAsync();
  20160. }
  20161. initTimestampQuery( renderContext ) {
  20162. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  20163. const renderContextData = this.get( renderContext );
  20164. if ( this.queryRunning ) {
  20165. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  20166. renderContextData.queryQueue.push( renderContext );
  20167. return;
  20168. }
  20169. if ( renderContextData.activeQuery ) {
  20170. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  20171. renderContextData.activeQuery = null;
  20172. }
  20173. renderContextData.activeQuery = this.gl.createQuery();
  20174. if ( renderContextData.activeQuery !== null ) {
  20175. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  20176. this.queryRunning = true;
  20177. }
  20178. }
  20179. // timestamp utils
  20180. prepareTimestampBuffer( renderContext ) {
  20181. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  20182. const renderContextData = this.get( renderContext );
  20183. if ( renderContextData.activeQuery ) {
  20184. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  20185. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  20186. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  20187. renderContextData.activeQuery = null;
  20188. this.queryRunning = false;
  20189. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  20190. const nextRenderContext = renderContextData.queryQueue.shift();
  20191. this.initTimestampQuery( nextRenderContext );
  20192. }
  20193. }
  20194. }
  20195. async resolveTimestampAsync( renderContext, type = 'render' ) {
  20196. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  20197. const renderContextData = this.get( renderContext );
  20198. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  20199. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  20200. const queryInfo = renderContextData.gpuQueries[ i ];
  20201. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  20202. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  20203. if ( available && ! disjoint ) {
  20204. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  20205. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  20206. this.gl.deleteQuery( queryInfo.query );
  20207. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  20208. i --;
  20209. this.renderer.info.updateTimestamp( type, duration );
  20210. }
  20211. }
  20212. }
  20213. getContext() {
  20214. return this.gl;
  20215. }
  20216. beginRender( renderContext ) {
  20217. const { gl } = this;
  20218. const renderContextData = this.get( renderContext );
  20219. //
  20220. //
  20221. this.initTimestampQuery( renderContext );
  20222. renderContextData.previousContext = this._currentContext;
  20223. this._currentContext = renderContext;
  20224. this._setFramebuffer( renderContext );
  20225. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  20226. //
  20227. if ( renderContext.viewport ) {
  20228. this.updateViewport( renderContext );
  20229. } else {
  20230. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  20231. }
  20232. if ( renderContext.scissor ) {
  20233. const { x, y, width, height } = renderContext.scissorValue;
  20234. gl.scissor( x, renderContext.height - height - y, width, height );
  20235. }
  20236. const occlusionQueryCount = renderContext.occlusionQueryCount;
  20237. if ( occlusionQueryCount > 0 ) {
  20238. // Get a reference to the array of objects with queries. The renderContextData property
  20239. // can be changed by another render pass before the async reading of all previous queries complete
  20240. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  20241. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  20242. renderContextData.lastOcclusionObject = null;
  20243. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  20244. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  20245. renderContextData.occlusionQueryIndex = 0;
  20246. }
  20247. }
  20248. finishRender( renderContext ) {
  20249. const { gl, state } = this;
  20250. const renderContextData = this.get( renderContext );
  20251. const previousContext = renderContextData.previousContext;
  20252. const occlusionQueryCount = renderContext.occlusionQueryCount;
  20253. if ( occlusionQueryCount > 0 ) {
  20254. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  20255. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  20256. }
  20257. this.resolveOccludedAsync( renderContext );
  20258. }
  20259. const textures = renderContext.textures;
  20260. if ( textures !== null ) {
  20261. for ( let i = 0; i < textures.length; i ++ ) {
  20262. const texture = textures[ i ];
  20263. if ( texture.generateMipmaps ) {
  20264. this.generateMipmaps( texture );
  20265. }
  20266. }
  20267. }
  20268. this._currentContext = previousContext;
  20269. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  20270. const renderTargetContextData = this.get( renderContext.renderTarget );
  20271. const { samples } = renderContext.renderTarget;
  20272. if ( samples > 0 ) {
  20273. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  20274. const mask = gl.COLOR_BUFFER_BIT;
  20275. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  20276. const textures = renderContext.textures;
  20277. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  20278. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  20279. for ( let i = 0; i < textures.length; i ++ ) {
  20280. // TODO Add support for MRT
  20281. if ( renderContext.scissor ) {
  20282. const { x, y, width, height } = renderContext.scissorValue;
  20283. const viewY = renderContext.height - height - y;
  20284. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  20285. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  20286. } else {
  20287. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  20288. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  20289. }
  20290. }
  20291. }
  20292. }
  20293. if ( previousContext !== null ) {
  20294. this._setFramebuffer( previousContext );
  20295. if ( previousContext.viewport ) {
  20296. this.updateViewport( previousContext );
  20297. } else {
  20298. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  20299. }
  20300. }
  20301. this.prepareTimestampBuffer( renderContext );
  20302. }
  20303. resolveOccludedAsync( renderContext ) {
  20304. const renderContextData = this.get( renderContext );
  20305. // handle occlusion query results
  20306. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  20307. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  20308. const occluded = new WeakSet();
  20309. const { gl } = this;
  20310. renderContextData.currentOcclusionQueryObjects = null;
  20311. renderContextData.currentOcclusionQueries = null;
  20312. const check = () => {
  20313. let completed = 0;
  20314. // check all queries and requeue as appropriate
  20315. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  20316. const query = currentOcclusionQueries[ i ];
  20317. if ( query === null ) continue;
  20318. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  20319. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  20320. currentOcclusionQueries[ i ] = null;
  20321. gl.deleteQuery( query );
  20322. completed ++;
  20323. }
  20324. }
  20325. if ( completed < currentOcclusionQueries.length ) {
  20326. requestAnimationFrame( check );
  20327. } else {
  20328. renderContextData.occluded = occluded;
  20329. }
  20330. };
  20331. check();
  20332. }
  20333. }
  20334. isOccluded( renderContext, object ) {
  20335. const renderContextData = this.get( renderContext );
  20336. return renderContextData.occluded && renderContextData.occluded.has( object );
  20337. }
  20338. updateViewport( renderContext ) {
  20339. const gl = this.gl;
  20340. const { x, y, width, height } = renderContext.viewportValue;
  20341. gl.viewport( x, renderContext.height - height - y, width, height );
  20342. }
  20343. setScissorTest( boolean ) {
  20344. const gl = this.gl;
  20345. if ( boolean ) {
  20346. gl.enable( gl.SCISSOR_TEST );
  20347. } else {
  20348. gl.disable( gl.SCISSOR_TEST );
  20349. }
  20350. }
  20351. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  20352. const { gl } = this;
  20353. if ( descriptor === null ) {
  20354. const clearColor = this.getClearColor();
  20355. // premultiply alpha
  20356. clearColor.r *= clearColor.a;
  20357. clearColor.g *= clearColor.a;
  20358. clearColor.b *= clearColor.a;
  20359. descriptor = {
  20360. textures: null,
  20361. clearColorValue: clearColor
  20362. };
  20363. }
  20364. //
  20365. let clear = 0;
  20366. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  20367. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  20368. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  20369. if ( clear !== 0 ) {
  20370. let clearColor;
  20371. if ( descriptor.clearColorValue ) {
  20372. clearColor = descriptor.clearColorValue;
  20373. } else {
  20374. clearColor = this.getClearColor();
  20375. // premultiply alpha
  20376. clearColor.r *= clearColor.a;
  20377. clearColor.g *= clearColor.a;
  20378. clearColor.b *= clearColor.a;
  20379. }
  20380. if ( depth ) this.state.setDepthMask( true );
  20381. if ( descriptor.textures === null ) {
  20382. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  20383. gl.clear( clear );
  20384. } else {
  20385. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  20386. if ( color ) {
  20387. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  20388. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  20389. }
  20390. }
  20391. if ( depth && stencil ) {
  20392. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  20393. } else if ( depth ) {
  20394. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  20395. } else if ( stencil ) {
  20396. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  20397. }
  20398. }
  20399. }
  20400. }
  20401. beginCompute( computeGroup ) {
  20402. const { state, gl } = this;
  20403. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  20404. this.initTimestampQuery( computeGroup );
  20405. }
  20406. compute( computeGroup, computeNode, bindings, pipeline ) {
  20407. const { state, gl } = this;
  20408. if ( ! this.discard ) {
  20409. // required here to handle async behaviour of render.compute()
  20410. gl.enable( gl.RASTERIZER_DISCARD );
  20411. this.discard = true;
  20412. }
  20413. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  20414. const vaoKey = this._getVaoKey( null, attributes );
  20415. const vaoGPU = this.vaoCache[ vaoKey ];
  20416. if ( vaoGPU === undefined ) {
  20417. this._createVao( null, attributes );
  20418. } else {
  20419. gl.bindVertexArray( vaoGPU );
  20420. }
  20421. state.useProgram( programGPU );
  20422. this._bindUniforms( bindings );
  20423. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  20424. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  20425. gl.beginTransformFeedback( gl.POINTS );
  20426. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  20427. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  20428. } else {
  20429. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  20430. }
  20431. gl.endTransformFeedback();
  20432. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  20433. // switch active buffers
  20434. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  20435. const dualAttributeData = transformBuffers[ i ];
  20436. if ( dualAttributeData.pbo ) {
  20437. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  20438. }
  20439. dualAttributeData.switchBuffers();
  20440. }
  20441. }
  20442. finishCompute( computeGroup ) {
  20443. const gl = this.gl;
  20444. this.discard = false;
  20445. gl.disable( gl.RASTERIZER_DISCARD );
  20446. this.prepareTimestampBuffer( computeGroup );
  20447. if ( this._currentContext ) {
  20448. this._setFramebuffer( this._currentContext );
  20449. }
  20450. }
  20451. draw( renderObject/*, info*/ ) {
  20452. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  20453. const { programGPU } = this.get( pipeline );
  20454. const { gl, state } = this;
  20455. const contextData = this.get( context );
  20456. const drawParams = renderObject.getDrawParameters();
  20457. if ( drawParams === null ) return;
  20458. //
  20459. this._bindUniforms( renderObject.getBindings() );
  20460. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  20461. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  20462. state.useProgram( programGPU );
  20463. //
  20464. const renderObjectData = this.get( renderObject );
  20465. let vaoGPU = renderObjectData.staticVao;
  20466. if ( vaoGPU === undefined || renderObjectData.geometryId !== renderObject.geometry.id ) {
  20467. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  20468. vaoGPU = this.vaoCache[ vaoKey ];
  20469. if ( vaoGPU === undefined ) {
  20470. let staticVao;
  20471. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  20472. if ( staticVao ) {
  20473. renderObjectData.staticVao = vaoGPU;
  20474. renderObjectData.geometryId = renderObject.geometry.id;
  20475. }
  20476. }
  20477. }
  20478. gl.bindVertexArray( vaoGPU );
  20479. //
  20480. const index = renderObject.getIndex();
  20481. //
  20482. const lastObject = contextData.lastOcclusionObject;
  20483. if ( lastObject !== object && lastObject !== undefined ) {
  20484. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  20485. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  20486. contextData.occlusionQueryIndex ++;
  20487. }
  20488. if ( object.occlusionTest === true ) {
  20489. const query = gl.createQuery();
  20490. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  20491. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  20492. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  20493. }
  20494. contextData.lastOcclusionObject = object;
  20495. }
  20496. //
  20497. const renderer = this.bufferRenderer;
  20498. if ( object.isPoints ) renderer.mode = gl.POINTS;
  20499. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  20500. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  20501. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  20502. else {
  20503. if ( material.wireframe === true ) {
  20504. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  20505. renderer.mode = gl.LINES;
  20506. } else {
  20507. renderer.mode = gl.TRIANGLES;
  20508. }
  20509. }
  20510. //
  20511. const { vertexCount, instanceCount } = drawParams;
  20512. let { firstVertex } = drawParams;
  20513. renderer.object = object;
  20514. if ( index !== null ) {
  20515. firstVertex *= index.array.BYTES_PER_ELEMENT;
  20516. const indexData = this.get( index );
  20517. renderer.index = index.count;
  20518. renderer.type = indexData.type;
  20519. } else {
  20520. renderer.index = 0;
  20521. }
  20522. if ( object.isBatchedMesh ) {
  20523. if ( object._multiDrawInstances !== null ) {
  20524. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  20525. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  20526. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  20527. } else {
  20528. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  20529. }
  20530. } else if ( instanceCount > 1 ) {
  20531. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  20532. } else {
  20533. renderer.render( firstVertex, vertexCount );
  20534. }
  20535. //
  20536. gl.bindVertexArray( null );
  20537. }
  20538. needsRenderUpdate( /*renderObject*/ ) {
  20539. return false;
  20540. }
  20541. getRenderCacheKey( /*renderObject*/ ) {
  20542. return '';
  20543. }
  20544. // textures
  20545. createDefaultTexture( texture ) {
  20546. this.textureUtils.createDefaultTexture( texture );
  20547. }
  20548. createTexture( texture, options ) {
  20549. this.textureUtils.createTexture( texture, options );
  20550. }
  20551. updateTexture( texture, options ) {
  20552. this.textureUtils.updateTexture( texture, options );
  20553. }
  20554. generateMipmaps( texture ) {
  20555. this.textureUtils.generateMipmaps( texture );
  20556. }
  20557. destroyTexture( texture ) {
  20558. this.textureUtils.destroyTexture( texture );
  20559. }
  20560. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  20561. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  20562. }
  20563. createSampler( /*texture*/ ) {
  20564. //console.warn( 'Abstract class.' );
  20565. }
  20566. destroySampler() {}
  20567. // node builder
  20568. createNodeBuilder( object, renderer ) {
  20569. return new GLSLNodeBuilder( object, renderer );
  20570. }
  20571. // program
  20572. createProgram( program ) {
  20573. const gl = this.gl;
  20574. const { stage, code } = program;
  20575. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  20576. gl.shaderSource( shader, code );
  20577. gl.compileShader( shader );
  20578. this.set( program, {
  20579. shaderGPU: shader
  20580. } );
  20581. }
  20582. destroyProgram( /*program*/ ) {
  20583. console.warn( 'Abstract class.' );
  20584. }
  20585. createRenderPipeline( renderObject, promises ) {
  20586. const gl = this.gl;
  20587. const pipeline = renderObject.pipeline;
  20588. // Program
  20589. const { fragmentProgram, vertexProgram } = pipeline;
  20590. const programGPU = gl.createProgram();
  20591. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  20592. const vertexShader = this.get( vertexProgram ).shaderGPU;
  20593. gl.attachShader( programGPU, fragmentShader );
  20594. gl.attachShader( programGPU, vertexShader );
  20595. gl.linkProgram( programGPU );
  20596. this.set( pipeline, {
  20597. programGPU,
  20598. fragmentShader,
  20599. vertexShader
  20600. } );
  20601. if ( promises !== null && this.parallel ) {
  20602. const p = new Promise( ( resolve /*, reject*/ ) => {
  20603. const parallel = this.parallel;
  20604. const checkStatus = () => {
  20605. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  20606. this._completeCompile( renderObject, pipeline );
  20607. resolve();
  20608. } else {
  20609. requestAnimationFrame( checkStatus );
  20610. }
  20611. };
  20612. checkStatus();
  20613. } );
  20614. promises.push( p );
  20615. return;
  20616. }
  20617. this._completeCompile( renderObject, pipeline );
  20618. }
  20619. _handleSource( string, errorLine ) {
  20620. const lines = string.split( '\n' );
  20621. const lines2 = [];
  20622. const from = Math.max( errorLine - 6, 0 );
  20623. const to = Math.min( errorLine + 6, lines.length );
  20624. for ( let i = from; i < to; i ++ ) {
  20625. const line = i + 1;
  20626. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  20627. }
  20628. return lines2.join( '\n' );
  20629. }
  20630. _getShaderErrors( gl, shader, type ) {
  20631. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  20632. const errors = gl.getShaderInfoLog( shader ).trim();
  20633. if ( status && errors === '' ) return '';
  20634. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  20635. if ( errorMatches ) {
  20636. const errorLine = parseInt( errorMatches[ 1 ] );
  20637. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  20638. } else {
  20639. return errors;
  20640. }
  20641. }
  20642. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  20643. if ( this.renderer.debug.checkShaderErrors ) {
  20644. const gl = this.gl;
  20645. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  20646. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  20647. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  20648. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  20649. } else {
  20650. // default error reporting
  20651. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  20652. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  20653. console.error(
  20654. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  20655. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  20656. 'Program Info Log: ' + programLog + '\n' +
  20657. vertexErrors + '\n' +
  20658. fragmentErrors
  20659. );
  20660. }
  20661. } else if ( programLog !== '' ) {
  20662. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  20663. }
  20664. }
  20665. }
  20666. _completeCompile( renderObject, pipeline ) {
  20667. const { state, gl } = this;
  20668. const pipelineData = this.get( pipeline );
  20669. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  20670. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  20671. this._logProgramError( programGPU, fragmentShader, vertexShader );
  20672. }
  20673. state.useProgram( programGPU );
  20674. // Bindings
  20675. const bindings = renderObject.getBindings();
  20676. this._setupBindings( bindings, programGPU );
  20677. //
  20678. this.set( pipeline, {
  20679. programGPU
  20680. } );
  20681. }
  20682. createComputePipeline( computePipeline, bindings ) {
  20683. const { state, gl } = this;
  20684. // Program
  20685. const fragmentProgram = {
  20686. stage: 'fragment',
  20687. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  20688. };
  20689. this.createProgram( fragmentProgram );
  20690. const { computeProgram } = computePipeline;
  20691. const programGPU = gl.createProgram();
  20692. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  20693. const vertexShader = this.get( computeProgram ).shaderGPU;
  20694. const transforms = computeProgram.transforms;
  20695. const transformVaryingNames = [];
  20696. const transformAttributeNodes = [];
  20697. for ( let i = 0; i < transforms.length; i ++ ) {
  20698. const transform = transforms[ i ];
  20699. transformVaryingNames.push( transform.varyingName );
  20700. transformAttributeNodes.push( transform.attributeNode );
  20701. }
  20702. gl.attachShader( programGPU, fragmentShader );
  20703. gl.attachShader( programGPU, vertexShader );
  20704. gl.transformFeedbackVaryings(
  20705. programGPU,
  20706. transformVaryingNames,
  20707. gl.SEPARATE_ATTRIBS
  20708. );
  20709. gl.linkProgram( programGPU );
  20710. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  20711. this._logProgramError( programGPU, fragmentShader, vertexShader );
  20712. }
  20713. state.useProgram( programGPU );
  20714. // Bindings
  20715. this._setupBindings( bindings, programGPU );
  20716. const attributeNodes = computeProgram.attributes;
  20717. const attributes = [];
  20718. const transformBuffers = [];
  20719. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  20720. const attribute = attributeNodes[ i ].node.attribute;
  20721. attributes.push( attribute );
  20722. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  20723. }
  20724. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  20725. const attribute = transformAttributeNodes[ i ].attribute;
  20726. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  20727. const attributeData = this.get( attribute );
  20728. transformBuffers.push( attributeData );
  20729. }
  20730. //
  20731. this.set( computePipeline, {
  20732. programGPU,
  20733. transformBuffers,
  20734. attributes
  20735. } );
  20736. }
  20737. createBindings( bindGroup, bindings ) {
  20738. if ( this._knownBindings.has( bindings ) === false ) {
  20739. this._knownBindings.add( bindings );
  20740. let uniformBuffers = 0;
  20741. let textures = 0;
  20742. for ( const bindGroup of bindings ) {
  20743. this.set( bindGroup, {
  20744. textures: textures,
  20745. uniformBuffers: uniformBuffers
  20746. } );
  20747. for ( const binding of bindGroup.bindings ) {
  20748. if ( binding.isUniformBuffer ) uniformBuffers ++;
  20749. if ( binding.isSampledTexture ) textures ++;
  20750. }
  20751. }
  20752. }
  20753. this.updateBindings( bindGroup, bindings );
  20754. }
  20755. updateBindings( bindGroup /*, bindings*/ ) {
  20756. const { gl } = this;
  20757. const bindGroupData = this.get( bindGroup );
  20758. let i = bindGroupData.uniformBuffers;
  20759. let t = bindGroupData.textures;
  20760. for ( const binding of bindGroup.bindings ) {
  20761. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  20762. const data = binding.buffer;
  20763. const bufferGPU = gl.createBuffer();
  20764. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  20765. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  20766. this.set( binding, {
  20767. index: i ++,
  20768. bufferGPU
  20769. } );
  20770. } else if ( binding.isSampledTexture ) {
  20771. const { textureGPU, glTextureType } = this.get( binding.texture );
  20772. this.set( binding, {
  20773. index: t ++,
  20774. textureGPU,
  20775. glTextureType
  20776. } );
  20777. }
  20778. }
  20779. }
  20780. updateBinding( binding ) {
  20781. const gl = this.gl;
  20782. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  20783. const bindingData = this.get( binding );
  20784. const bufferGPU = bindingData.bufferGPU;
  20785. const data = binding.buffer;
  20786. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  20787. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  20788. }
  20789. }
  20790. // attributes
  20791. createIndexAttribute( attribute ) {
  20792. const gl = this.gl;
  20793. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  20794. }
  20795. createAttribute( attribute ) {
  20796. if ( this.has( attribute ) ) return;
  20797. const gl = this.gl;
  20798. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  20799. }
  20800. createStorageAttribute( attribute ) {
  20801. if ( this.has( attribute ) ) return;
  20802. const gl = this.gl;
  20803. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  20804. }
  20805. updateAttribute( attribute ) {
  20806. this.attributeUtils.updateAttribute( attribute );
  20807. }
  20808. destroyAttribute( attribute ) {
  20809. this.attributeUtils.destroyAttribute( attribute );
  20810. }
  20811. updateSize() {
  20812. //console.warn( 'Abstract class.' );
  20813. }
  20814. hasFeature( name ) {
  20815. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  20816. const extensions = this.extensions;
  20817. for ( let i = 0; i < keysMatching.length; i ++ ) {
  20818. if ( extensions.has( keysMatching[ i ] ) ) return true;
  20819. }
  20820. return false;
  20821. }
  20822. getMaxAnisotropy() {
  20823. return this.capabilities.getMaxAnisotropy();
  20824. }
  20825. copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level ) {
  20826. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  20827. }
  20828. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  20829. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  20830. }
  20831. _setFramebuffer( descriptor ) {
  20832. const { gl, state } = this;
  20833. let currentFrameBuffer = null;
  20834. if ( descriptor.textures !== null ) {
  20835. const renderTarget = descriptor.renderTarget;
  20836. const renderTargetContextData = this.get( renderTarget );
  20837. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  20838. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  20839. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  20840. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  20841. const cacheKey = getCacheKey( descriptor );
  20842. let fb;
  20843. if ( isCube ) {
  20844. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  20845. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  20846. } else {
  20847. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  20848. fb = renderTargetContextData.framebuffers[ cacheKey ];
  20849. }
  20850. if ( fb === undefined ) {
  20851. fb = gl.createFramebuffer();
  20852. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  20853. const textures = descriptor.textures;
  20854. if ( isCube ) {
  20855. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  20856. const { textureGPU } = this.get( textures[ 0 ] );
  20857. const cubeFace = this.renderer._activeCubeFace;
  20858. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  20859. } else {
  20860. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  20861. for ( let i = 0; i < textures.length; i ++ ) {
  20862. const texture = textures[ i ];
  20863. const textureData = this.get( texture );
  20864. textureData.renderTarget = descriptor.renderTarget;
  20865. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  20866. const attachment = gl.COLOR_ATTACHMENT0 + i;
  20867. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  20868. }
  20869. state.drawBuffers( descriptor, fb );
  20870. }
  20871. if ( descriptor.depthTexture !== null ) {
  20872. const textureData = this.get( descriptor.depthTexture );
  20873. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  20874. textureData.renderTarget = descriptor.renderTarget;
  20875. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  20876. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  20877. }
  20878. }
  20879. if ( samples > 0 ) {
  20880. if ( msaaFb === undefined ) {
  20881. const invalidationArray = [];
  20882. msaaFb = gl.createFramebuffer();
  20883. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  20884. const msaaRenderbuffers = [];
  20885. const textures = descriptor.textures;
  20886. for ( let i = 0; i < textures.length; i ++ ) {
  20887. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  20888. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  20889. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  20890. if ( depthBuffer ) {
  20891. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  20892. invalidationArray.push( depthStyle );
  20893. }
  20894. const texture = descriptor.textures[ i ];
  20895. const textureData = this.get( texture );
  20896. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  20897. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  20898. }
  20899. renderTargetContextData.msaaFrameBuffer = msaaFb;
  20900. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  20901. if ( depthRenderbuffer === undefined ) {
  20902. depthRenderbuffer = gl.createRenderbuffer();
  20903. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor );
  20904. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  20905. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  20906. invalidationArray.push( depthStyle );
  20907. }
  20908. renderTargetContextData.invalidationArray = invalidationArray;
  20909. }
  20910. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  20911. } else {
  20912. currentFrameBuffer = fb;
  20913. }
  20914. }
  20915. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  20916. }
  20917. _getVaoKey( index, attributes ) {
  20918. let key = [];
  20919. if ( index !== null ) {
  20920. const indexData = this.get( index );
  20921. key += ':' + indexData.id;
  20922. }
  20923. for ( let i = 0; i < attributes.length; i ++ ) {
  20924. const attributeData = this.get( attributes[ i ] );
  20925. key += ':' + attributeData.id;
  20926. }
  20927. return key;
  20928. }
  20929. _createVao( index, attributes ) {
  20930. const { gl } = this;
  20931. const vaoGPU = gl.createVertexArray();
  20932. let key = '';
  20933. let staticVao = true;
  20934. gl.bindVertexArray( vaoGPU );
  20935. if ( index !== null ) {
  20936. const indexData = this.get( index );
  20937. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  20938. key += ':' + indexData.id;
  20939. }
  20940. for ( let i = 0; i < attributes.length; i ++ ) {
  20941. const attribute = attributes[ i ];
  20942. const attributeData = this.get( attribute );
  20943. key += ':' + attributeData.id;
  20944. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  20945. gl.enableVertexAttribArray( i );
  20946. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  20947. let stride, offset;
  20948. if ( attribute.isInterleavedBufferAttribute === true ) {
  20949. stride = attribute.data.stride * attributeData.bytesPerElement;
  20950. offset = attribute.offset * attributeData.bytesPerElement;
  20951. } else {
  20952. stride = 0;
  20953. offset = 0;
  20954. }
  20955. if ( attributeData.isInteger ) {
  20956. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  20957. } else {
  20958. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  20959. }
  20960. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  20961. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  20962. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  20963. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  20964. }
  20965. }
  20966. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  20967. this.vaoCache[ key ] = vaoGPU;
  20968. return { vaoGPU, staticVao };
  20969. }
  20970. _getTransformFeedback( transformBuffers ) {
  20971. let key = '';
  20972. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  20973. key += ':' + transformBuffers[ i ].id;
  20974. }
  20975. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  20976. if ( transformFeedbackGPU !== undefined ) {
  20977. return transformFeedbackGPU;
  20978. }
  20979. const { gl } = this;
  20980. transformFeedbackGPU = gl.createTransformFeedback();
  20981. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  20982. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  20983. const attributeData = transformBuffers[ i ];
  20984. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  20985. }
  20986. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  20987. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  20988. return transformFeedbackGPU;
  20989. }
  20990. _setupBindings( bindings, programGPU ) {
  20991. const gl = this.gl;
  20992. for ( const bindGroup of bindings ) {
  20993. for ( const binding of bindGroup.bindings ) {
  20994. const bindingData = this.get( binding );
  20995. const index = bindingData.index;
  20996. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  20997. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  20998. gl.uniformBlockBinding( programGPU, location, index );
  20999. } else if ( binding.isSampledTexture ) {
  21000. const location = gl.getUniformLocation( programGPU, binding.name );
  21001. gl.uniform1i( location, index );
  21002. }
  21003. }
  21004. }
  21005. }
  21006. _bindUniforms( bindings ) {
  21007. const { gl, state } = this;
  21008. for ( const bindGroup of bindings ) {
  21009. for ( const binding of bindGroup.bindings ) {
  21010. const bindingData = this.get( binding );
  21011. const index = bindingData.index;
  21012. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  21013. // TODO USE bindBufferRange to group multiple uniform buffers
  21014. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  21015. } else if ( binding.isSampledTexture ) {
  21016. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  21017. }
  21018. }
  21019. }
  21020. }
  21021. dispose() {
  21022. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  21023. }
  21024. }
  21025. const GPUPrimitiveTopology = {
  21026. PointList: 'point-list',
  21027. LineList: 'line-list',
  21028. LineStrip: 'line-strip',
  21029. TriangleList: 'triangle-list',
  21030. TriangleStrip: 'triangle-strip',
  21031. };
  21032. const GPUCompareFunction = {
  21033. Never: 'never',
  21034. Less: 'less',
  21035. Equal: 'equal',
  21036. LessEqual: 'less-equal',
  21037. Greater: 'greater',
  21038. NotEqual: 'not-equal',
  21039. GreaterEqual: 'greater-equal',
  21040. Always: 'always'
  21041. };
  21042. const GPUStoreOp = {
  21043. Store: 'store',
  21044. Discard: 'discard'
  21045. };
  21046. const GPULoadOp = {
  21047. Load: 'load',
  21048. Clear: 'clear'
  21049. };
  21050. const GPUFrontFace = {
  21051. CCW: 'ccw',
  21052. CW: 'cw'
  21053. };
  21054. const GPUCullMode = {
  21055. None: 'none',
  21056. Front: 'front',
  21057. Back: 'back'
  21058. };
  21059. const GPUIndexFormat = {
  21060. Uint16: 'uint16',
  21061. Uint32: 'uint32'
  21062. };
  21063. const GPUTextureFormat = {
  21064. // 8-bit formats
  21065. R8Unorm: 'r8unorm',
  21066. R8Snorm: 'r8snorm',
  21067. R8Uint: 'r8uint',
  21068. R8Sint: 'r8sint',
  21069. // 16-bit formats
  21070. R16Uint: 'r16uint',
  21071. R16Sint: 'r16sint',
  21072. R16Float: 'r16float',
  21073. RG8Unorm: 'rg8unorm',
  21074. RG8Snorm: 'rg8snorm',
  21075. RG8Uint: 'rg8uint',
  21076. RG8Sint: 'rg8sint',
  21077. // 32-bit formats
  21078. R32Uint: 'r32uint',
  21079. R32Sint: 'r32sint',
  21080. R32Float: 'r32float',
  21081. RG16Uint: 'rg16uint',
  21082. RG16Sint: 'rg16sint',
  21083. RG16Float: 'rg16float',
  21084. RGBA8Unorm: 'rgba8unorm',
  21085. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  21086. RGBA8Snorm: 'rgba8snorm',
  21087. RGBA8Uint: 'rgba8uint',
  21088. RGBA8Sint: 'rgba8sint',
  21089. BGRA8Unorm: 'bgra8unorm',
  21090. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  21091. // Packed 32-bit formats
  21092. RGB9E5UFloat: 'rgb9e5ufloat',
  21093. RGB10A2Unorm: 'rgb10a2unorm',
  21094. RG11B10uFloat: 'rgb10a2unorm',
  21095. // 64-bit formats
  21096. RG32Uint: 'rg32uint',
  21097. RG32Sint: 'rg32sint',
  21098. RG32Float: 'rg32float',
  21099. RGBA16Uint: 'rgba16uint',
  21100. RGBA16Sint: 'rgba16sint',
  21101. RGBA16Float: 'rgba16float',
  21102. // 128-bit formats
  21103. RGBA32Uint: 'rgba32uint',
  21104. RGBA32Sint: 'rgba32sint',
  21105. RGBA32Float: 'rgba32float',
  21106. // Depth and stencil formats
  21107. Stencil8: 'stencil8',
  21108. Depth16Unorm: 'depth16unorm',
  21109. Depth24Plus: 'depth24plus',
  21110. Depth24PlusStencil8: 'depth24plus-stencil8',
  21111. Depth32Float: 'depth32float',
  21112. // 'depth32float-stencil8' extension
  21113. Depth32FloatStencil8: 'depth32float-stencil8',
  21114. // BC compressed formats usable if 'texture-compression-bc' is both
  21115. // supported by the device/user agent and enabled in requestDevice.
  21116. BC1RGBAUnorm: 'bc1-rgba-unorm',
  21117. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  21118. BC2RGBAUnorm: 'bc2-rgba-unorm',
  21119. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  21120. BC3RGBAUnorm: 'bc3-rgba-unorm',
  21121. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  21122. BC4RUnorm: 'bc4-r-unorm',
  21123. BC4RSnorm: 'bc4-r-snorm',
  21124. BC5RGUnorm: 'bc5-rg-unorm',
  21125. BC5RGSnorm: 'bc5-rg-snorm',
  21126. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  21127. BC6HRGBFloat: 'bc6h-rgb-float',
  21128. BC7RGBAUnorm: 'bc7-rgba-unorm',
  21129. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  21130. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  21131. // supported by the device/user agent and enabled in requestDevice.
  21132. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  21133. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  21134. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  21135. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  21136. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  21137. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  21138. EACR11Unorm: 'eac-r11unorm',
  21139. EACR11Snorm: 'eac-r11snorm',
  21140. EACRG11Unorm: 'eac-rg11unorm',
  21141. EACRG11Snorm: 'eac-rg11snorm',
  21142. // ASTC compressed formats usable if 'texture-compression-astc' is both
  21143. // supported by the device/user agent and enabled in requestDevice.
  21144. ASTC4x4Unorm: 'astc-4x4-unorm',
  21145. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  21146. ASTC5x4Unorm: 'astc-5x4-unorm',
  21147. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  21148. ASTC5x5Unorm: 'astc-5x5-unorm',
  21149. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  21150. ASTC6x5Unorm: 'astc-6x5-unorm',
  21151. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  21152. ASTC6x6Unorm: 'astc-6x6-unorm',
  21153. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  21154. ASTC8x5Unorm: 'astc-8x5-unorm',
  21155. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  21156. ASTC8x6Unorm: 'astc-8x6-unorm',
  21157. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  21158. ASTC8x8Unorm: 'astc-8x8-unorm',
  21159. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  21160. ASTC10x5Unorm: 'astc-10x5-unorm',
  21161. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  21162. ASTC10x6Unorm: 'astc-10x6-unorm',
  21163. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  21164. ASTC10x8Unorm: 'astc-10x8-unorm',
  21165. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  21166. ASTC10x10Unorm: 'astc-10x10-unorm',
  21167. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  21168. ASTC12x10Unorm: 'astc-12x10-unorm',
  21169. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  21170. ASTC12x12Unorm: 'astc-12x12-unorm',
  21171. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  21172. };
  21173. const GPUAddressMode = {
  21174. ClampToEdge: 'clamp-to-edge',
  21175. Repeat: 'repeat',
  21176. MirrorRepeat: 'mirror-repeat'
  21177. };
  21178. const GPUFilterMode = {
  21179. Linear: 'linear',
  21180. Nearest: 'nearest'
  21181. };
  21182. const GPUBlendFactor = {
  21183. Zero: 'zero',
  21184. One: 'one',
  21185. Src: 'src',
  21186. OneMinusSrc: 'one-minus-src',
  21187. SrcAlpha: 'src-alpha',
  21188. OneMinusSrcAlpha: 'one-minus-src-alpha',
  21189. Dst: 'dst',
  21190. OneMinusDstColor: 'one-minus-dst',
  21191. DstAlpha: 'dst-alpha',
  21192. OneMinusDstAlpha: 'one-minus-dst-alpha',
  21193. SrcAlphaSaturated: 'src-alpha-saturated',
  21194. Constant: 'constant',
  21195. OneMinusConstant: 'one-minus-constant'
  21196. };
  21197. const GPUBlendOperation = {
  21198. Add: 'add',
  21199. Subtract: 'subtract',
  21200. ReverseSubtract: 'reverse-subtract',
  21201. Min: 'min',
  21202. Max: 'max'
  21203. };
  21204. const GPUColorWriteFlags = {
  21205. None: 0,
  21206. Red: 0x1,
  21207. Green: 0x2,
  21208. Blue: 0x4,
  21209. Alpha: 0x8,
  21210. All: 0xF
  21211. };
  21212. const GPUStencilOperation = {
  21213. Keep: 'keep',
  21214. Zero: 'zero',
  21215. Replace: 'replace',
  21216. Invert: 'invert',
  21217. IncrementClamp: 'increment-clamp',
  21218. DecrementClamp: 'decrement-clamp',
  21219. IncrementWrap: 'increment-wrap',
  21220. DecrementWrap: 'decrement-wrap'
  21221. };
  21222. const GPUBufferBindingType = {
  21223. Uniform: 'uniform',
  21224. Storage: 'storage',
  21225. ReadOnlyStorage: 'read-only-storage'
  21226. };
  21227. const GPUStorageTextureAccess = {
  21228. WriteOnly: 'write-only',
  21229. ReadOnly: 'read-only',
  21230. ReadWrite: 'read-write',
  21231. };
  21232. const GPUTextureSampleType = {
  21233. Float: 'float',
  21234. UnfilterableFloat: 'unfilterable-float',
  21235. Depth: 'depth',
  21236. SInt: 'sint',
  21237. UInt: 'uint'
  21238. };
  21239. const GPUTextureDimension = {
  21240. OneD: '1d',
  21241. TwoD: '2d',
  21242. ThreeD: '3d'
  21243. };
  21244. const GPUTextureViewDimension = {
  21245. OneD: '1d',
  21246. TwoD: '2d',
  21247. TwoDArray: '2d-array',
  21248. Cube: 'cube',
  21249. CubeArray: 'cube-array',
  21250. ThreeD: '3d'
  21251. };
  21252. const GPUTextureAspect = {
  21253. All: 'all',
  21254. StencilOnly: 'stencil-only',
  21255. DepthOnly: 'depth-only'
  21256. };
  21257. const GPUInputStepMode = {
  21258. Vertex: 'vertex',
  21259. Instance: 'instance'
  21260. };
  21261. const GPUFeatureName = {
  21262. DepthClipControl: 'depth-clip-control',
  21263. Depth32FloatStencil8: 'depth32float-stencil8',
  21264. TextureCompressionBC: 'texture-compression-bc',
  21265. TextureCompressionETC2: 'texture-compression-etc2',
  21266. TextureCompressionASTC: 'texture-compression-astc',
  21267. TimestampQuery: 'timestamp-query',
  21268. IndirectFirstInstance: 'indirect-first-instance',
  21269. ShaderF16: 'shader-f16',
  21270. RG11B10UFloat: 'rg11b10ufloat-renderable',
  21271. BGRA8UNormStorage: 'bgra8unorm-storage',
  21272. Float32Filterable: 'float32-filterable',
  21273. ClipDistances: 'clip-distances',
  21274. DualSourceBlending: 'dual-source-blending',
  21275. Subgroups: 'subgroups'
  21276. };
  21277. class Sampler extends Binding {
  21278. constructor( name, texture ) {
  21279. super( name );
  21280. this.texture = texture;
  21281. this.version = texture ? texture.version : 0;
  21282. this.isSampler = true;
  21283. }
  21284. }
  21285. class NodeSampler extends Sampler {
  21286. constructor( name, textureNode, groupNode ) {
  21287. super( name, textureNode ? textureNode.value : null );
  21288. this.textureNode = textureNode;
  21289. this.groupNode = groupNode;
  21290. }
  21291. update() {
  21292. this.texture = this.textureNode.value;
  21293. }
  21294. }
  21295. class StorageBuffer extends Buffer {
  21296. constructor( name, attribute ) {
  21297. super( name, attribute ? attribute.array : null );
  21298. this.attribute = attribute;
  21299. this.isStorageBuffer = true;
  21300. }
  21301. }
  21302. let _id = 0;
  21303. class NodeStorageBuffer extends StorageBuffer {
  21304. constructor( nodeUniform, groupNode ) {
  21305. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  21306. this.nodeUniform = nodeUniform;
  21307. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  21308. this.groupNode = groupNode;
  21309. }
  21310. get buffer() {
  21311. return this.nodeUniform.value;
  21312. }
  21313. }
  21314. class WebGPUTexturePassUtils extends DataMap {
  21315. constructor( device ) {
  21316. super();
  21317. this.device = device;
  21318. const mipmapVertexSource = `
  21319. struct VarysStruct {
  21320. @builtin( position ) Position: vec4<f32>,
  21321. @location( 0 ) vTex : vec2<f32>
  21322. };
  21323. @vertex
  21324. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  21325. var Varys : VarysStruct;
  21326. var pos = array< vec2<f32>, 4 >(
  21327. vec2<f32>( -1.0, 1.0 ),
  21328. vec2<f32>( 1.0, 1.0 ),
  21329. vec2<f32>( -1.0, -1.0 ),
  21330. vec2<f32>( 1.0, -1.0 )
  21331. );
  21332. var tex = array< vec2<f32>, 4 >(
  21333. vec2<f32>( 0.0, 0.0 ),
  21334. vec2<f32>( 1.0, 0.0 ),
  21335. vec2<f32>( 0.0, 1.0 ),
  21336. vec2<f32>( 1.0, 1.0 )
  21337. );
  21338. Varys.vTex = tex[ vertexIndex ];
  21339. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  21340. return Varys;
  21341. }
  21342. `;
  21343. const mipmapFragmentSource = `
  21344. @group( 0 ) @binding( 0 )
  21345. var imgSampler : sampler;
  21346. @group( 0 ) @binding( 1 )
  21347. var img : texture_2d<f32>;
  21348. @fragment
  21349. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  21350. return textureSample( img, imgSampler, vTex );
  21351. }
  21352. `;
  21353. const flipYFragmentSource = `
  21354. @group( 0 ) @binding( 0 )
  21355. var imgSampler : sampler;
  21356. @group( 0 ) @binding( 1 )
  21357. var img : texture_2d<f32>;
  21358. @fragment
  21359. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  21360. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  21361. }
  21362. `;
  21363. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  21364. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  21365. // We'll need a new pipeline for every texture format used.
  21366. this.transferPipelines = {};
  21367. this.flipYPipelines = {};
  21368. this.mipmapVertexShaderModule = device.createShaderModule( {
  21369. label: 'mipmapVertex',
  21370. code: mipmapVertexSource
  21371. } );
  21372. this.mipmapFragmentShaderModule = device.createShaderModule( {
  21373. label: 'mipmapFragment',
  21374. code: mipmapFragmentSource
  21375. } );
  21376. this.flipYFragmentShaderModule = device.createShaderModule( {
  21377. label: 'flipYFragment',
  21378. code: flipYFragmentSource
  21379. } );
  21380. }
  21381. getTransferPipeline( format ) {
  21382. let pipeline = this.transferPipelines[ format ];
  21383. if ( pipeline === undefined ) {
  21384. pipeline = this.device.createRenderPipeline( {
  21385. label: `mipmap-${ format }`,
  21386. vertex: {
  21387. module: this.mipmapVertexShaderModule,
  21388. entryPoint: 'main'
  21389. },
  21390. fragment: {
  21391. module: this.mipmapFragmentShaderModule,
  21392. entryPoint: 'main',
  21393. targets: [ { format } ]
  21394. },
  21395. primitive: {
  21396. topology: GPUPrimitiveTopology.TriangleStrip,
  21397. stripIndexFormat: GPUIndexFormat.Uint32
  21398. },
  21399. layout: 'auto'
  21400. } );
  21401. this.transferPipelines[ format ] = pipeline;
  21402. }
  21403. return pipeline;
  21404. }
  21405. getFlipYPipeline( format ) {
  21406. let pipeline = this.flipYPipelines[ format ];
  21407. if ( pipeline === undefined ) {
  21408. pipeline = this.device.createRenderPipeline( {
  21409. label: `flipY-${ format }`,
  21410. vertex: {
  21411. module: this.mipmapVertexShaderModule,
  21412. entryPoint: 'main'
  21413. },
  21414. fragment: {
  21415. module: this.flipYFragmentShaderModule,
  21416. entryPoint: 'main',
  21417. targets: [ { format } ]
  21418. },
  21419. primitive: {
  21420. topology: GPUPrimitiveTopology.TriangleStrip,
  21421. stripIndexFormat: GPUIndexFormat.Uint32
  21422. },
  21423. layout: 'auto'
  21424. } );
  21425. this.flipYPipelines[ format ] = pipeline;
  21426. }
  21427. return pipeline;
  21428. }
  21429. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  21430. const format = textureGPUDescriptor.format;
  21431. const { width, height } = textureGPUDescriptor.size;
  21432. const transferPipeline = this.getTransferPipeline( format );
  21433. const flipYPipeline = this.getFlipYPipeline( format );
  21434. const tempTexture = this.device.createTexture( {
  21435. size: { width, height, depthOrArrayLayers: 1 },
  21436. format,
  21437. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  21438. } );
  21439. const srcView = textureGPU.createView( {
  21440. baseMipLevel: 0,
  21441. mipLevelCount: 1,
  21442. dimension: GPUTextureViewDimension.TwoD,
  21443. baseArrayLayer
  21444. } );
  21445. const dstView = tempTexture.createView( {
  21446. baseMipLevel: 0,
  21447. mipLevelCount: 1,
  21448. dimension: GPUTextureViewDimension.TwoD,
  21449. baseArrayLayer: 0
  21450. } );
  21451. const commandEncoder = this.device.createCommandEncoder( {} );
  21452. const pass = ( pipeline, sourceView, destinationView ) => {
  21453. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  21454. const bindGroup = this.device.createBindGroup( {
  21455. layout: bindGroupLayout,
  21456. entries: [ {
  21457. binding: 0,
  21458. resource: this.flipYSampler
  21459. }, {
  21460. binding: 1,
  21461. resource: sourceView
  21462. } ]
  21463. } );
  21464. const passEncoder = commandEncoder.beginRenderPass( {
  21465. colorAttachments: [ {
  21466. view: destinationView,
  21467. loadOp: GPULoadOp.Clear,
  21468. storeOp: GPUStoreOp.Store,
  21469. clearValue: [ 0, 0, 0, 0 ]
  21470. } ]
  21471. } );
  21472. passEncoder.setPipeline( pipeline );
  21473. passEncoder.setBindGroup( 0, bindGroup );
  21474. passEncoder.draw( 4, 1, 0, 0 );
  21475. passEncoder.end();
  21476. };
  21477. pass( transferPipeline, srcView, dstView );
  21478. pass( flipYPipeline, dstView, srcView );
  21479. this.device.queue.submit( [ commandEncoder.finish() ] );
  21480. tempTexture.destroy();
  21481. }
  21482. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  21483. const textureData = this.get( textureGPU );
  21484. if ( textureData.useCount === undefined ) {
  21485. textureData.useCount = 0;
  21486. textureData.layers = [];
  21487. }
  21488. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  21489. const commandEncoder = this.device.createCommandEncoder( {} );
  21490. this._mipmapRunBundles( commandEncoder, passes );
  21491. this.device.queue.submit( [ commandEncoder.finish() ] );
  21492. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  21493. textureData.useCount ++;
  21494. }
  21495. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  21496. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  21497. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  21498. let srcView = textureGPU.createView( {
  21499. baseMipLevel: 0,
  21500. mipLevelCount: 1,
  21501. dimension: GPUTextureViewDimension.TwoD,
  21502. baseArrayLayer
  21503. } );
  21504. const passes = [];
  21505. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  21506. const bindGroup = this.device.createBindGroup( {
  21507. layout: bindGroupLayout,
  21508. entries: [ {
  21509. binding: 0,
  21510. resource: this.mipmapSampler
  21511. }, {
  21512. binding: 1,
  21513. resource: srcView
  21514. } ]
  21515. } );
  21516. const dstView = textureGPU.createView( {
  21517. baseMipLevel: i,
  21518. mipLevelCount: 1,
  21519. dimension: GPUTextureViewDimension.TwoD,
  21520. baseArrayLayer
  21521. } );
  21522. const passDescriptor = {
  21523. colorAttachments: [ {
  21524. view: dstView,
  21525. loadOp: GPULoadOp.Clear,
  21526. storeOp: GPUStoreOp.Store,
  21527. clearValue: [ 0, 0, 0, 0 ]
  21528. } ]
  21529. };
  21530. const passEncoder = this.device.createRenderBundleEncoder( {
  21531. colorFormats: [ textureGPUDescriptor.format ]
  21532. } );
  21533. passEncoder.setPipeline( pipeline );
  21534. passEncoder.setBindGroup( 0, bindGroup );
  21535. passEncoder.draw( 4, 1, 0, 0 );
  21536. passes.push( {
  21537. renderBundles: [ passEncoder.finish() ],
  21538. passDescriptor
  21539. } );
  21540. srcView = dstView;
  21541. }
  21542. return passes;
  21543. }
  21544. _mipmapRunBundles( commandEncoder, passes ) {
  21545. const levels = passes.length;
  21546. for ( let i = 0; i < levels; i ++ ) {
  21547. const pass = passes[ i ];
  21548. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  21549. passEncoder.executeBundles( pass.renderBundles );
  21550. passEncoder.end();
  21551. }
  21552. }
  21553. }
  21554. const _compareToWebGPU = {
  21555. [ NeverCompare ]: 'never',
  21556. [ LessCompare ]: 'less',
  21557. [ EqualCompare ]: 'equal',
  21558. [ LessEqualCompare ]: 'less-equal',
  21559. [ GreaterCompare ]: 'greater',
  21560. [ GreaterEqualCompare ]: 'greater-equal',
  21561. [ AlwaysCompare ]: 'always',
  21562. [ NotEqualCompare ]: 'not-equal'
  21563. };
  21564. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  21565. class WebGPUTextureUtils {
  21566. constructor( backend ) {
  21567. this.backend = backend;
  21568. this._passUtils = null;
  21569. this.defaultTexture = {};
  21570. this.defaultCubeTexture = {};
  21571. this.defaultVideoFrame = null;
  21572. this.colorBuffer = null;
  21573. this.depthTexture = new DepthTexture();
  21574. this.depthTexture.name = 'depthBuffer';
  21575. }
  21576. createSampler( texture ) {
  21577. const backend = this.backend;
  21578. const device = backend.device;
  21579. const textureGPU = backend.get( texture );
  21580. const samplerDescriptorGPU = {
  21581. addressModeU: this._convertAddressMode( texture.wrapS ),
  21582. addressModeV: this._convertAddressMode( texture.wrapT ),
  21583. addressModeW: this._convertAddressMode( texture.wrapR ),
  21584. magFilter: this._convertFilterMode( texture.magFilter ),
  21585. minFilter: this._convertFilterMode( texture.minFilter ),
  21586. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  21587. maxAnisotropy: 1
  21588. };
  21589. // anisotropy can only be used when all filter modes are set to linear.
  21590. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  21591. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  21592. }
  21593. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  21594. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  21595. }
  21596. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  21597. }
  21598. createDefaultTexture( texture ) {
  21599. let textureGPU;
  21600. const format = getFormat( texture );
  21601. if ( texture.isCubeTexture ) {
  21602. textureGPU = this._getDefaultCubeTextureGPU( format );
  21603. } else if ( texture.isVideoTexture ) {
  21604. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  21605. } else {
  21606. textureGPU = this._getDefaultTextureGPU( format );
  21607. }
  21608. this.backend.get( texture ).texture = textureGPU;
  21609. }
  21610. createTexture( texture, options = {} ) {
  21611. const backend = this.backend;
  21612. const textureData = backend.get( texture );
  21613. if ( textureData.initialized ) {
  21614. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  21615. }
  21616. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  21617. if ( options.levels === undefined ) options.levels = 1;
  21618. if ( options.depth === undefined ) options.depth = 1;
  21619. const { width, height, depth, levels } = options;
  21620. if ( texture.isFramebufferTexture ) {
  21621. if ( options.renderTarget ) {
  21622. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  21623. } else {
  21624. options.format = this.backend.utils.getPreferredCanvasFormat();
  21625. }
  21626. }
  21627. const dimension = this._getDimension( texture );
  21628. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  21629. textureData.format = format;
  21630. let sampleCount = options.sampleCount !== undefined ? options.sampleCount : 1;
  21631. sampleCount = backend.utils.getSampleCount( sampleCount );
  21632. const primarySampleCount = texture.isRenderTargetTexture && ! texture.isMultisampleRenderTargetTexture ? 1 : sampleCount;
  21633. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  21634. if ( texture.isStorageTexture === true ) {
  21635. usage |= GPUTextureUsage.STORAGE_BINDING;
  21636. }
  21637. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  21638. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  21639. }
  21640. const textureDescriptorGPU = {
  21641. label: texture.name,
  21642. size: {
  21643. width: width,
  21644. height: height,
  21645. depthOrArrayLayers: depth,
  21646. },
  21647. mipLevelCount: levels,
  21648. sampleCount: primarySampleCount,
  21649. dimension: dimension,
  21650. format: format,
  21651. usage: usage
  21652. };
  21653. // texture creation
  21654. if ( texture.isVideoTexture ) {
  21655. const video = texture.source.data;
  21656. const videoFrame = new VideoFrame( video );
  21657. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  21658. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  21659. videoFrame.close();
  21660. textureData.externalTexture = video;
  21661. } else {
  21662. if ( format === undefined ) {
  21663. console.warn( 'WebGPURenderer: Texture format not supported.' );
  21664. return this.createDefaultTexture( texture );
  21665. }
  21666. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  21667. }
  21668. if ( texture.isRenderTargetTexture && sampleCount > 1 && ! texture.isMultisampleRenderTargetTexture ) {
  21669. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  21670. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  21671. msaaTextureDescriptorGPU.sampleCount = sampleCount;
  21672. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  21673. }
  21674. textureData.initialized = true;
  21675. textureData.textureDescriptorGPU = textureDescriptorGPU;
  21676. }
  21677. destroyTexture( texture ) {
  21678. const backend = this.backend;
  21679. const textureData = backend.get( texture );
  21680. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  21681. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  21682. backend.delete( texture );
  21683. }
  21684. destroySampler( texture ) {
  21685. const backend = this.backend;
  21686. const textureData = backend.get( texture );
  21687. delete textureData.sampler;
  21688. }
  21689. generateMipmaps( texture ) {
  21690. const textureData = this.backend.get( texture );
  21691. if ( texture.isCubeTexture ) {
  21692. for ( let i = 0; i < 6; i ++ ) {
  21693. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  21694. }
  21695. } else {
  21696. const depth = texture.image.depth || 1;
  21697. for ( let i = 0; i < depth; i ++ ) {
  21698. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  21699. }
  21700. }
  21701. }
  21702. getColorBuffer() {
  21703. if ( this.colorBuffer ) this.colorBuffer.destroy();
  21704. const backend = this.backend;
  21705. const { width, height } = backend.getDrawingBufferSize();
  21706. this.colorBuffer = backend.device.createTexture( {
  21707. label: 'colorBuffer',
  21708. size: {
  21709. width: width,
  21710. height: height,
  21711. depthOrArrayLayers: 1
  21712. },
  21713. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  21714. format: backend.utils.getPreferredCanvasFormat(),
  21715. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  21716. } );
  21717. return this.colorBuffer;
  21718. }
  21719. getDepthBuffer( depth = true, stencil = false ) {
  21720. const backend = this.backend;
  21721. const { width, height } = backend.getDrawingBufferSize();
  21722. const depthTexture = this.depthTexture;
  21723. const depthTextureGPU = backend.get( depthTexture ).texture;
  21724. let format, type;
  21725. if ( stencil ) {
  21726. format = DepthStencilFormat;
  21727. type = UnsignedInt248Type;
  21728. } else if ( depth ) {
  21729. format = DepthFormat;
  21730. type = UnsignedIntType;
  21731. }
  21732. if ( depthTextureGPU !== undefined ) {
  21733. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  21734. return depthTextureGPU;
  21735. }
  21736. this.destroyTexture( depthTexture );
  21737. }
  21738. depthTexture.name = 'depthBuffer';
  21739. depthTexture.format = format;
  21740. depthTexture.type = type;
  21741. depthTexture.image.width = width;
  21742. depthTexture.image.height = height;
  21743. this.createTexture( depthTexture, { sampleCount: backend.utils.getSampleCount( backend.renderer.samples ), width, height } );
  21744. return backend.get( depthTexture ).texture;
  21745. }
  21746. updateTexture( texture, options ) {
  21747. const textureData = this.backend.get( texture );
  21748. const { textureDescriptorGPU } = textureData;
  21749. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  21750. return;
  21751. // transfer texture data
  21752. if ( texture.isDataTexture ) {
  21753. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  21754. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  21755. for ( let i = 0; i < options.image.depth; i ++ ) {
  21756. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  21757. }
  21758. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  21759. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  21760. } else if ( texture.isCubeTexture ) {
  21761. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  21762. } else if ( texture.isVideoTexture ) {
  21763. const video = texture.source.data;
  21764. textureData.externalTexture = video;
  21765. } else {
  21766. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  21767. }
  21768. //
  21769. textureData.version = texture.version;
  21770. if ( texture.onUpdate ) texture.onUpdate( texture );
  21771. }
  21772. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  21773. const device = this.backend.device;
  21774. const textureData = this.backend.get( texture );
  21775. const textureGPU = textureData.texture;
  21776. const format = textureData.textureDescriptorGPU.format;
  21777. const bytesPerTexel = this._getBytesPerTexel( format );
  21778. let bytesPerRow = width * bytesPerTexel;
  21779. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  21780. const readBuffer = device.createBuffer(
  21781. {
  21782. size: width * height * bytesPerTexel,
  21783. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  21784. }
  21785. );
  21786. const encoder = device.createCommandEncoder();
  21787. encoder.copyTextureToBuffer(
  21788. {
  21789. texture: textureGPU,
  21790. origin: { x, y, z: faceIndex },
  21791. },
  21792. {
  21793. buffer: readBuffer,
  21794. bytesPerRow: bytesPerRow
  21795. },
  21796. {
  21797. width: width,
  21798. height: height
  21799. }
  21800. );
  21801. const typedArrayType = this._getTypedArrayType( format );
  21802. device.queue.submit( [ encoder.finish() ] );
  21803. await readBuffer.mapAsync( GPUMapMode.READ );
  21804. const buffer = readBuffer.getMappedRange();
  21805. return new typedArrayType( buffer );
  21806. }
  21807. _isEnvironmentTexture( texture ) {
  21808. const mapping = texture.mapping;
  21809. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  21810. }
  21811. _getDefaultTextureGPU( format ) {
  21812. let defaultTexture = this.defaultTexture[ format ];
  21813. if ( defaultTexture === undefined ) {
  21814. const texture = new Texture();
  21815. texture.minFilter = NearestFilter;
  21816. texture.magFilter = NearestFilter;
  21817. this.createTexture( texture, { width: 1, height: 1, format } );
  21818. this.defaultTexture[ format ] = defaultTexture = texture;
  21819. }
  21820. return this.backend.get( defaultTexture ).texture;
  21821. }
  21822. _getDefaultCubeTextureGPU( format ) {
  21823. let defaultCubeTexture = this.defaultTexture[ format ];
  21824. if ( defaultCubeTexture === undefined ) {
  21825. const texture = new CubeTexture();
  21826. texture.minFilter = NearestFilter;
  21827. texture.magFilter = NearestFilter;
  21828. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  21829. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  21830. }
  21831. return this.backend.get( defaultCubeTexture ).texture;
  21832. }
  21833. _getDefaultVideoFrame() {
  21834. let defaultVideoFrame = this.defaultVideoFrame;
  21835. if ( defaultVideoFrame === null ) {
  21836. const init = {
  21837. timestamp: 0,
  21838. codedWidth: 1,
  21839. codedHeight: 1,
  21840. format: 'RGBA',
  21841. };
  21842. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  21843. }
  21844. return defaultVideoFrame;
  21845. }
  21846. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  21847. for ( let i = 0; i < 6; i ++ ) {
  21848. const image = images[ i ];
  21849. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  21850. if ( image.isDataTexture ) {
  21851. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  21852. } else {
  21853. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  21854. }
  21855. }
  21856. }
  21857. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  21858. const device = this.backend.device;
  21859. device.queue.copyExternalImageToTexture(
  21860. {
  21861. source: image
  21862. }, {
  21863. texture: textureGPU,
  21864. mipLevel: 0,
  21865. origin: { x: 0, y: 0, z: originDepth }
  21866. }, {
  21867. width: image.width,
  21868. height: image.height,
  21869. depthOrArrayLayers: 1
  21870. }
  21871. );
  21872. if ( flipY === true ) {
  21873. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  21874. }
  21875. }
  21876. _getPassUtils() {
  21877. let passUtils = this._passUtils;
  21878. if ( passUtils === null ) {
  21879. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  21880. }
  21881. return passUtils;
  21882. }
  21883. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  21884. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  21885. }
  21886. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  21887. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  21888. }
  21889. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  21890. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  21891. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  21892. const device = this.backend.device;
  21893. const data = image.data;
  21894. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  21895. const bytesPerRow = image.width * bytesPerTexel;
  21896. device.queue.writeTexture(
  21897. {
  21898. texture: textureGPU,
  21899. mipLevel: 0,
  21900. origin: { x: 0, y: 0, z: originDepth }
  21901. },
  21902. data,
  21903. {
  21904. offset: image.width * image.height * bytesPerTexel * depth,
  21905. bytesPerRow
  21906. },
  21907. {
  21908. width: image.width,
  21909. height: image.height,
  21910. depthOrArrayLayers: 1
  21911. } );
  21912. if ( flipY === true ) {
  21913. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  21914. }
  21915. }
  21916. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  21917. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  21918. const device = this.backend.device;
  21919. const blockData = this._getBlockData( textureDescriptorGPU.format );
  21920. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  21921. for ( let i = 0; i < mipmaps.length; i ++ ) {
  21922. const mipmap = mipmaps[ i ];
  21923. const width = mipmap.width;
  21924. const height = mipmap.height;
  21925. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  21926. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  21927. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  21928. for ( let j = 0; j < depth; j ++ ) {
  21929. device.queue.writeTexture(
  21930. {
  21931. texture: textureGPU,
  21932. mipLevel: i,
  21933. origin: { x: 0, y: 0, z: j }
  21934. },
  21935. mipmap.data,
  21936. {
  21937. offset: j * bytesPerImage,
  21938. bytesPerRow,
  21939. rowsPerImage: Math.ceil( height / blockData.height )
  21940. },
  21941. {
  21942. width: Math.ceil( width / blockData.width ) * blockData.width,
  21943. height: Math.ceil( height / blockData.height ) * blockData.height,
  21944. depthOrArrayLayers: 1
  21945. }
  21946. );
  21947. }
  21948. }
  21949. }
  21950. _getBlockData( format ) {
  21951. // this method is only relevant for compressed texture formats
  21952. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  21953. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  21954. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  21955. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  21956. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  21957. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  21958. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  21959. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  21960. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  21961. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  21962. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  21963. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  21964. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  21965. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  21966. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  21967. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  21968. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  21969. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  21970. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  21971. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  21972. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  21973. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  21974. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  21975. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  21976. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  21977. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  21978. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  21979. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  21980. }
  21981. _convertAddressMode( value ) {
  21982. let addressMode = GPUAddressMode.ClampToEdge;
  21983. if ( value === RepeatWrapping ) {
  21984. addressMode = GPUAddressMode.Repeat;
  21985. } else if ( value === MirroredRepeatWrapping ) {
  21986. addressMode = GPUAddressMode.MirrorRepeat;
  21987. }
  21988. return addressMode;
  21989. }
  21990. _convertFilterMode( value ) {
  21991. let filterMode = GPUFilterMode.Linear;
  21992. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  21993. filterMode = GPUFilterMode.Nearest;
  21994. }
  21995. return filterMode;
  21996. }
  21997. _getBytesPerTexel( format ) {
  21998. // 8-bit formats
  21999. if ( format === GPUTextureFormat.R8Unorm ||
  22000. format === GPUTextureFormat.R8Snorm ||
  22001. format === GPUTextureFormat.R8Uint ||
  22002. format === GPUTextureFormat.R8Sint ) return 1;
  22003. // 16-bit formats
  22004. if ( format === GPUTextureFormat.R16Uint ||
  22005. format === GPUTextureFormat.R16Sint ||
  22006. format === GPUTextureFormat.R16Float ||
  22007. format === GPUTextureFormat.RG8Unorm ||
  22008. format === GPUTextureFormat.RG8Snorm ||
  22009. format === GPUTextureFormat.RG8Uint ||
  22010. format === GPUTextureFormat.RG8Sint ) return 2;
  22011. // 32-bit formats
  22012. if ( format === GPUTextureFormat.R32Uint ||
  22013. format === GPUTextureFormat.R32Sint ||
  22014. format === GPUTextureFormat.R32Float ||
  22015. format === GPUTextureFormat.RG16Uint ||
  22016. format === GPUTextureFormat.RG16Sint ||
  22017. format === GPUTextureFormat.RG16Float ||
  22018. format === GPUTextureFormat.RGBA8Unorm ||
  22019. format === GPUTextureFormat.RGBA8UnormSRGB ||
  22020. format === GPUTextureFormat.RGBA8Snorm ||
  22021. format === GPUTextureFormat.RGBA8Uint ||
  22022. format === GPUTextureFormat.RGBA8Sint ||
  22023. format === GPUTextureFormat.BGRA8Unorm ||
  22024. format === GPUTextureFormat.BGRA8UnormSRGB ||
  22025. // Packed 32-bit formats
  22026. format === GPUTextureFormat.RGB9E5UFloat ||
  22027. format === GPUTextureFormat.RGB10A2Unorm ||
  22028. format === GPUTextureFormat.RG11B10UFloat ||
  22029. format === GPUTextureFormat.Depth32Float ||
  22030. format === GPUTextureFormat.Depth24Plus ||
  22031. format === GPUTextureFormat.Depth24PlusStencil8 ||
  22032. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  22033. // 64-bit formats
  22034. if ( format === GPUTextureFormat.RG32Uint ||
  22035. format === GPUTextureFormat.RG32Sint ||
  22036. format === GPUTextureFormat.RG32Float ||
  22037. format === GPUTextureFormat.RGBA16Uint ||
  22038. format === GPUTextureFormat.RGBA16Sint ||
  22039. format === GPUTextureFormat.RGBA16Float ) return 8;
  22040. // 128-bit formats
  22041. if ( format === GPUTextureFormat.RGBA32Uint ||
  22042. format === GPUTextureFormat.RGBA32Sint ||
  22043. format === GPUTextureFormat.RGBA32Float ) return 16;
  22044. }
  22045. _getTypedArrayType( format ) {
  22046. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  22047. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  22048. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  22049. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  22050. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  22051. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  22052. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  22053. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  22054. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  22055. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  22056. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  22057. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  22058. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  22059. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  22060. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  22061. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  22062. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  22063. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  22064. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  22065. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  22066. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  22067. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  22068. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  22069. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  22070. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  22071. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  22072. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  22073. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  22074. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  22075. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  22076. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  22077. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  22078. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  22079. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  22080. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  22081. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  22082. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  22083. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  22084. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  22085. }
  22086. _getDimension( texture ) {
  22087. let dimension;
  22088. if ( texture.isData3DTexture ) {
  22089. dimension = GPUTextureDimension.ThreeD;
  22090. } else {
  22091. dimension = GPUTextureDimension.TwoD;
  22092. }
  22093. return dimension;
  22094. }
  22095. }
  22096. function getFormat( texture, device = null ) {
  22097. const format = texture.format;
  22098. const type = texture.type;
  22099. const colorSpace = texture.colorSpace;
  22100. let formatGPU;
  22101. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  22102. switch ( format ) {
  22103. case RGBA_S3TC_DXT1_Format:
  22104. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  22105. break;
  22106. case RGBA_S3TC_DXT3_Format:
  22107. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  22108. break;
  22109. case RGBA_S3TC_DXT5_Format:
  22110. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  22111. break;
  22112. case RGB_ETC2_Format:
  22113. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  22114. break;
  22115. case RGBA_ETC2_EAC_Format:
  22116. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  22117. break;
  22118. case RGBA_ASTC_4x4_Format:
  22119. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  22120. break;
  22121. case RGBA_ASTC_5x4_Format:
  22122. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  22123. break;
  22124. case RGBA_ASTC_5x5_Format:
  22125. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  22126. break;
  22127. case RGBA_ASTC_6x5_Format:
  22128. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  22129. break;
  22130. case RGBA_ASTC_6x6_Format:
  22131. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  22132. break;
  22133. case RGBA_ASTC_8x5_Format:
  22134. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  22135. break;
  22136. case RGBA_ASTC_8x6_Format:
  22137. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  22138. break;
  22139. case RGBA_ASTC_8x8_Format:
  22140. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  22141. break;
  22142. case RGBA_ASTC_10x5_Format:
  22143. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  22144. break;
  22145. case RGBA_ASTC_10x6_Format:
  22146. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  22147. break;
  22148. case RGBA_ASTC_10x8_Format:
  22149. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  22150. break;
  22151. case RGBA_ASTC_10x10_Format:
  22152. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  22153. break;
  22154. case RGBA_ASTC_12x10_Format:
  22155. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  22156. break;
  22157. case RGBA_ASTC_12x12_Format:
  22158. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  22159. break;
  22160. case RGBAFormat:
  22161. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  22162. break;
  22163. default:
  22164. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  22165. }
  22166. } else {
  22167. switch ( format ) {
  22168. case RGBAFormat:
  22169. switch ( type ) {
  22170. case ByteType:
  22171. formatGPU = GPUTextureFormat.RGBA8Snorm;
  22172. break;
  22173. case ShortType:
  22174. formatGPU = GPUTextureFormat.RGBA16Sint;
  22175. break;
  22176. case UnsignedShortType:
  22177. formatGPU = GPUTextureFormat.RGBA16Uint;
  22178. break;
  22179. case UnsignedIntType:
  22180. formatGPU = GPUTextureFormat.RGBA32Uint;
  22181. break;
  22182. case IntType:
  22183. formatGPU = GPUTextureFormat.RGBA32Sint;
  22184. break;
  22185. case UnsignedByteType:
  22186. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  22187. break;
  22188. case HalfFloatType:
  22189. formatGPU = GPUTextureFormat.RGBA16Float;
  22190. break;
  22191. case FloatType:
  22192. formatGPU = GPUTextureFormat.RGBA32Float;
  22193. break;
  22194. default:
  22195. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  22196. }
  22197. break;
  22198. case RGBFormat:
  22199. switch ( type ) {
  22200. case UnsignedInt5999Type:
  22201. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  22202. break;
  22203. default:
  22204. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  22205. }
  22206. break;
  22207. case RedFormat:
  22208. switch ( type ) {
  22209. case ByteType:
  22210. formatGPU = GPUTextureFormat.R8Snorm;
  22211. break;
  22212. case ShortType:
  22213. formatGPU = GPUTextureFormat.R16Sint;
  22214. break;
  22215. case UnsignedShortType:
  22216. formatGPU = GPUTextureFormat.R16Uint;
  22217. break;
  22218. case UnsignedIntType:
  22219. formatGPU = GPUTextureFormat.R32Uint;
  22220. break;
  22221. case IntType:
  22222. formatGPU = GPUTextureFormat.R32Sint;
  22223. break;
  22224. case UnsignedByteType:
  22225. formatGPU = GPUTextureFormat.R8Unorm;
  22226. break;
  22227. case HalfFloatType:
  22228. formatGPU = GPUTextureFormat.R16Float;
  22229. break;
  22230. case FloatType:
  22231. formatGPU = GPUTextureFormat.R32Float;
  22232. break;
  22233. default:
  22234. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  22235. }
  22236. break;
  22237. case RGFormat:
  22238. switch ( type ) {
  22239. case ByteType:
  22240. formatGPU = GPUTextureFormat.RG8Snorm;
  22241. break;
  22242. case ShortType:
  22243. formatGPU = GPUTextureFormat.RG16Sint;
  22244. break;
  22245. case UnsignedShortType:
  22246. formatGPU = GPUTextureFormat.RG16Uint;
  22247. break;
  22248. case UnsignedIntType:
  22249. formatGPU = GPUTextureFormat.RG32Uint;
  22250. break;
  22251. case IntType:
  22252. formatGPU = GPUTextureFormat.RG32Sint;
  22253. break;
  22254. case UnsignedByteType:
  22255. formatGPU = GPUTextureFormat.RG8Unorm;
  22256. break;
  22257. case HalfFloatType:
  22258. formatGPU = GPUTextureFormat.RG16Float;
  22259. break;
  22260. case FloatType:
  22261. formatGPU = GPUTextureFormat.RG32Float;
  22262. break;
  22263. default:
  22264. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  22265. }
  22266. break;
  22267. case DepthFormat:
  22268. switch ( type ) {
  22269. case UnsignedShortType:
  22270. formatGPU = GPUTextureFormat.Depth16Unorm;
  22271. break;
  22272. case UnsignedIntType:
  22273. formatGPU = GPUTextureFormat.Depth24Plus;
  22274. break;
  22275. case FloatType:
  22276. formatGPU = GPUTextureFormat.Depth32Float;
  22277. break;
  22278. default:
  22279. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  22280. }
  22281. break;
  22282. case DepthStencilFormat:
  22283. switch ( type ) {
  22284. case UnsignedInt248Type:
  22285. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  22286. break;
  22287. case FloatType:
  22288. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  22289. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  22290. }
  22291. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  22292. break;
  22293. default:
  22294. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  22295. }
  22296. break;
  22297. case RedIntegerFormat:
  22298. switch ( type ) {
  22299. case IntType:
  22300. formatGPU = GPUTextureFormat.R32Sint;
  22301. break;
  22302. case UnsignedIntType:
  22303. formatGPU = GPUTextureFormat.R32Uint;
  22304. break;
  22305. default:
  22306. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  22307. }
  22308. break;
  22309. case RGIntegerFormat:
  22310. switch ( type ) {
  22311. case IntType:
  22312. formatGPU = GPUTextureFormat.RG32Sint;
  22313. break;
  22314. case UnsignedIntType:
  22315. formatGPU = GPUTextureFormat.RG32Uint;
  22316. break;
  22317. default:
  22318. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  22319. }
  22320. break;
  22321. case RGBAIntegerFormat:
  22322. switch ( type ) {
  22323. case IntType:
  22324. formatGPU = GPUTextureFormat.RGBA32Sint;
  22325. break;
  22326. case UnsignedIntType:
  22327. formatGPU = GPUTextureFormat.RGBA32Uint;
  22328. break;
  22329. default:
  22330. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  22331. }
  22332. break;
  22333. default:
  22334. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  22335. }
  22336. }
  22337. return formatGPU;
  22338. }
  22339. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  22340. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  22341. const wgslTypeLib$1 = {
  22342. 'f32': 'float',
  22343. 'i32': 'int',
  22344. 'u32': 'uint',
  22345. 'bool': 'bool',
  22346. 'vec2<f32>': 'vec2',
  22347. 'vec2<i32>': 'ivec2',
  22348. 'vec2<u32>': 'uvec2',
  22349. 'vec2<bool>': 'bvec2',
  22350. 'vec2f': 'vec2',
  22351. 'vec2i': 'ivec2',
  22352. 'vec2u': 'uvec2',
  22353. 'vec2b': 'bvec2',
  22354. 'vec3<f32>': 'vec3',
  22355. 'vec3<i32>': 'ivec3',
  22356. 'vec3<u32>': 'uvec3',
  22357. 'vec3<bool>': 'bvec3',
  22358. 'vec3f': 'vec3',
  22359. 'vec3i': 'ivec3',
  22360. 'vec3u': 'uvec3',
  22361. 'vec3b': 'bvec3',
  22362. 'vec4<f32>': 'vec4',
  22363. 'vec4<i32>': 'ivec4',
  22364. 'vec4<u32>': 'uvec4',
  22365. 'vec4<bool>': 'bvec4',
  22366. 'vec4f': 'vec4',
  22367. 'vec4i': 'ivec4',
  22368. 'vec4u': 'uvec4',
  22369. 'vec4b': 'bvec4',
  22370. 'mat2x2<f32>': 'mat2',
  22371. 'mat2x2f': 'mat2',
  22372. 'mat3x3<f32>': 'mat3',
  22373. 'mat3x3f': 'mat3',
  22374. 'mat4x4<f32>': 'mat4',
  22375. 'mat4x4f': 'mat4',
  22376. 'sampler': 'sampler',
  22377. 'texture_1d': 'texture',
  22378. 'texture_2d': 'texture',
  22379. 'texture_2d_array': 'texture',
  22380. 'texture_multisampled_2d': 'cubeTexture',
  22381. 'texture_depth_2d': 'depthTexture',
  22382. 'texture_3d': 'texture3D',
  22383. 'texture_cube': 'cubeTexture',
  22384. 'texture_cube_array': 'cubeTexture',
  22385. 'texture_storage_1d': 'storageTexture',
  22386. 'texture_storage_2d': 'storageTexture',
  22387. 'texture_storage_2d_array': 'storageTexture',
  22388. 'texture_storage_3d': 'storageTexture'
  22389. };
  22390. const parse = ( source ) => {
  22391. source = source.trim();
  22392. const declaration = source.match( declarationRegexp );
  22393. if ( declaration !== null && declaration.length === 4 ) {
  22394. const inputsCode = declaration[ 2 ];
  22395. const propsMatches = [];
  22396. let match = null;
  22397. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  22398. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  22399. }
  22400. // Process matches to correctly pair names and types
  22401. const inputs = [];
  22402. for ( let i = 0; i < propsMatches.length; i ++ ) {
  22403. const { name, type } = propsMatches[ i ];
  22404. let resolvedType = type;
  22405. if ( resolvedType.startsWith( 'ptr' ) ) {
  22406. resolvedType = 'pointer';
  22407. } else {
  22408. if ( resolvedType.startsWith( 'texture' ) ) {
  22409. resolvedType = type.split( '<' )[ 0 ];
  22410. }
  22411. resolvedType = wgslTypeLib$1[ resolvedType ];
  22412. }
  22413. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  22414. }
  22415. const blockCode = source.substring( declaration[ 0 ].length );
  22416. const outputType = declaration[ 3 ] || 'void';
  22417. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  22418. const type = wgslTypeLib$1[ outputType ] || outputType;
  22419. return {
  22420. type,
  22421. inputs,
  22422. name,
  22423. inputsCode,
  22424. blockCode,
  22425. outputType
  22426. };
  22427. } else {
  22428. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  22429. }
  22430. };
  22431. class WGSLNodeFunction extends NodeFunction {
  22432. constructor( source ) {
  22433. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  22434. super( type, inputs, name );
  22435. this.inputsCode = inputsCode;
  22436. this.blockCode = blockCode;
  22437. this.outputType = outputType;
  22438. }
  22439. getCode( name = this.name ) {
  22440. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  22441. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  22442. }
  22443. }
  22444. class WGSLNodeParser extends NodeParser {
  22445. parseFunction( source ) {
  22446. return new WGSLNodeFunction( source );
  22447. }
  22448. }
  22449. // GPUShaderStage is not defined in browsers not supporting WebGPU
  22450. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  22451. const accessNames = {
  22452. [ NodeAccess.READ_ONLY ]: 'read',
  22453. [ NodeAccess.WRITE_ONLY ]: 'write',
  22454. [ NodeAccess.READ_WRITE ]: 'read_write'
  22455. };
  22456. const wrapNames = {
  22457. [ RepeatWrapping ]: 'repeat',
  22458. [ ClampToEdgeWrapping ]: 'clamp',
  22459. [ MirroredRepeatWrapping ]: 'mirror'
  22460. };
  22461. const gpuShaderStageLib = {
  22462. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  22463. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  22464. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  22465. };
  22466. const supports = {
  22467. instance: true,
  22468. swizzleAssign: false,
  22469. storageBuffer: true
  22470. };
  22471. const wgslFnOpLib = {
  22472. '^^': 'tsl_xor'
  22473. };
  22474. const wgslTypeLib = {
  22475. float: 'f32',
  22476. int: 'i32',
  22477. uint: 'u32',
  22478. bool: 'bool',
  22479. color: 'vec3<f32>',
  22480. vec2: 'vec2<f32>',
  22481. ivec2: 'vec2<i32>',
  22482. uvec2: 'vec2<u32>',
  22483. bvec2: 'vec2<bool>',
  22484. vec3: 'vec3<f32>',
  22485. ivec3: 'vec3<i32>',
  22486. uvec3: 'vec3<u32>',
  22487. bvec3: 'vec3<bool>',
  22488. vec4: 'vec4<f32>',
  22489. ivec4: 'vec4<i32>',
  22490. uvec4: 'vec4<u32>',
  22491. bvec4: 'vec4<bool>',
  22492. mat2: 'mat2x2<f32>',
  22493. mat3: 'mat3x3<f32>',
  22494. mat4: 'mat4x4<f32>'
  22495. };
  22496. const wgslCodeCache = {};
  22497. const wgslPolyfill = {
  22498. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  22499. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  22500. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  22501. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  22502. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  22503. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  22504. 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 ); }' ),
  22505. 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 ); }' ),
  22506. 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 ); }' ),
  22507. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  22508. 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 ); }' ),
  22509. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  22510. biquadraticTexture: new CodeNode( /* wgsl */`
  22511. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  22512. let res = vec2f( iRes );
  22513. let uvScaled = coord * res;
  22514. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  22515. // https://www.shadertoy.com/view/WtyXRy
  22516. let uv = uvWrapping - 0.5;
  22517. let iuv = floor( uv );
  22518. let f = fract( uv );
  22519. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  22520. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  22521. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  22522. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  22523. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  22524. }
  22525. ` )
  22526. };
  22527. const wgslMethods = {
  22528. dFdx: 'dpdx',
  22529. dFdy: '- dpdy',
  22530. mod_float: 'tsl_mod_float',
  22531. mod_vec2: 'tsl_mod_vec2',
  22532. mod_vec3: 'tsl_mod_vec3',
  22533. mod_vec4: 'tsl_mod_vec4',
  22534. equals_bool: 'tsl_equals_bool',
  22535. equals_bvec2: 'tsl_equals_bvec2',
  22536. equals_bvec3: 'tsl_equals_bvec3',
  22537. equals_bvec4: 'tsl_equals_bvec4',
  22538. inversesqrt: 'inverseSqrt',
  22539. bitcast: 'bitcast<f32>'
  22540. };
  22541. // WebGPU issue: does not support pow() with negative base on Windows
  22542. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  22543. 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 ); }' );
  22544. 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 ] );
  22545. 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 ] );
  22546. 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 ] );
  22547. wgslMethods.pow_float = 'tsl_pow_float';
  22548. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  22549. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  22550. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  22551. }
  22552. //
  22553. let diagnostics = '';
  22554. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  22555. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  22556. }
  22557. //
  22558. class WGSLNodeBuilder extends NodeBuilder {
  22559. constructor( object, renderer ) {
  22560. super( object, renderer, new WGSLNodeParser() );
  22561. this.uniformGroups = {};
  22562. this.builtins = {};
  22563. this.directives = {};
  22564. this.scopedArrays = new Map();
  22565. }
  22566. needsToWorkingColorSpace( texture ) {
  22567. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  22568. }
  22569. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  22570. if ( shaderStage === 'fragment' ) {
  22571. if ( depthSnippet ) {
  22572. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  22573. } else {
  22574. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  22575. }
  22576. } else if ( this.isFilteredTexture( texture ) ) {
  22577. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  22578. } else {
  22579. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0' );
  22580. }
  22581. }
  22582. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  22583. if ( shaderStage === 'fragment' ) {
  22584. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  22585. } else {
  22586. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  22587. }
  22588. }
  22589. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  22590. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false ) {
  22591. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  22592. } else if ( this.isFilteredTexture( texture ) ) {
  22593. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  22594. } else {
  22595. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  22596. }
  22597. }
  22598. generateWrapFunction( texture ) {
  22599. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }T`;
  22600. let nodeCode = wgslCodeCache[ functionName ];
  22601. if ( nodeCode === undefined ) {
  22602. const includes = [];
  22603. let code = `fn ${ functionName }( coord : vec2f ) -> vec2f {\n\n\treturn vec2f(\n`;
  22604. const addWrapSnippet = ( wrap, axis ) => {
  22605. if ( wrap === RepeatWrapping ) {
  22606. includes.push( wgslPolyfill.repeatWrapping_float );
  22607. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  22608. } else if ( wrap === ClampToEdgeWrapping ) {
  22609. includes.push( wgslPolyfill.clampWrapping_float );
  22610. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  22611. } else if ( wrap === MirroredRepeatWrapping ) {
  22612. includes.push( wgslPolyfill.mirrorWrapping_float );
  22613. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  22614. } else {
  22615. code += `\t\tcoord.${ axis }`;
  22616. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  22617. }
  22618. };
  22619. addWrapSnippet( texture.wrapS, 'x' );
  22620. code += ',\n';
  22621. addWrapSnippet( texture.wrapT, 'y' );
  22622. code += '\n\t);\n\n}\n';
  22623. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  22624. }
  22625. nodeCode.build( this );
  22626. return functionName;
  22627. }
  22628. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  22629. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  22630. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  22631. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  22632. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  22633. let textureDimensionsParams;
  22634. if ( texture.isMultisampleRenderTargetTexture === true ) {
  22635. textureDimensionsParams = textureProperty;
  22636. } else {
  22637. textureDimensionsParams = `${ textureProperty }, u32( ${ levelSnippet } )`;
  22638. }
  22639. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, 'uvec2' ) );
  22640. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  22641. }
  22642. return textureDimensionNode.build( this );
  22643. }
  22644. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  22645. this._include( 'biquadraticTexture' );
  22646. const wrapFunction = this.generateWrapFunction( texture );
  22647. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  22648. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  22649. }
  22650. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  22651. const wrapFunction = this.generateWrapFunction( texture );
  22652. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  22653. const coordSnippet = `vec2u( ${ wrapFunction }( ${ uvSnippet } ) * vec2f( ${ textureDimension } ) )`;
  22654. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  22655. }
  22656. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  22657. if ( texture.isVideoTexture === true || texture.isStorageTexture === true ) {
  22658. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  22659. } else if ( depthSnippet ) {
  22660. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  22661. } else {
  22662. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  22663. }
  22664. }
  22665. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  22666. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  22667. }
  22668. isSampleCompare( texture ) {
  22669. return texture.isDepthTexture === true && texture.compareFunction !== null;
  22670. }
  22671. isUnfilterable( texture ) {
  22672. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  22673. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  22674. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  22675. texture.isMultisampleRenderTargetTexture === true;
  22676. }
  22677. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  22678. let snippet = null;
  22679. if ( texture.isVideoTexture === true ) {
  22680. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  22681. } else if ( this.isUnfilterable( texture ) ) {
  22682. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  22683. } else {
  22684. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  22685. }
  22686. return snippet;
  22687. }
  22688. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  22689. if ( shaderStage === 'fragment' ) {
  22690. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  22691. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  22692. } else {
  22693. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  22694. }
  22695. }
  22696. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  22697. if ( shaderStage === 'fragment' ) {
  22698. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  22699. } else {
  22700. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  22701. }
  22702. }
  22703. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  22704. let snippet = null;
  22705. if ( texture.isVideoTexture === true ) {
  22706. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  22707. } else {
  22708. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  22709. }
  22710. return snippet;
  22711. }
  22712. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  22713. if ( shaderStage === 'fragment' ) {
  22714. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  22715. } else {
  22716. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  22717. }
  22718. }
  22719. getPropertyName( node, shaderStage = this.shaderStage ) {
  22720. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  22721. if ( shaderStage === 'vertex' ) {
  22722. return `varyings.${ node.name }`;
  22723. }
  22724. } else if ( node.isNodeUniform === true ) {
  22725. const name = node.name;
  22726. const type = node.type;
  22727. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  22728. return name;
  22729. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  22730. return `NodeBuffer_${ node.id }.${name}`;
  22731. } else {
  22732. return node.groupNode.name + '.' + name;
  22733. }
  22734. }
  22735. return super.getPropertyName( node );
  22736. }
  22737. getOutputStructName() {
  22738. return 'output';
  22739. }
  22740. _getUniformGroupCount( shaderStage ) {
  22741. return Object.keys( this.uniforms[ shaderStage ] ).length;
  22742. }
  22743. getFunctionOperator( op ) {
  22744. const fnOp = wgslFnOpLib[ op ];
  22745. if ( fnOp !== undefined ) {
  22746. this._include( fnOp );
  22747. return fnOp;
  22748. }
  22749. return null;
  22750. }
  22751. getNodeAccess( node, shaderStage ) {
  22752. if ( shaderStage !== 'compute' )
  22753. return NodeAccess.READ_ONLY;
  22754. return node.access;
  22755. }
  22756. getStorageAccess( node, shaderStage ) {
  22757. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  22758. }
  22759. getUniformFromNode( node, type, shaderStage, name = null ) {
  22760. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  22761. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  22762. if ( nodeData.uniformGPU === undefined ) {
  22763. let uniformGPU;
  22764. const group = node.groupNode;
  22765. const groupName = group.name;
  22766. const bindings = this.getBindGroupArray( groupName, shaderStage );
  22767. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  22768. let texture = null;
  22769. const access = this.getNodeAccess( node, shaderStage );
  22770. if ( type === 'texture' || type === 'storageTexture' ) {
  22771. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  22772. } else if ( type === 'cubeTexture' ) {
  22773. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  22774. } else if ( type === 'texture3D' ) {
  22775. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  22776. }
  22777. texture.store = node.isStorageTextureNode === true;
  22778. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  22779. if ( shaderStage === 'fragment' && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  22780. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  22781. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  22782. bindings.push( sampler, texture );
  22783. uniformGPU = [ sampler, texture ];
  22784. } else {
  22785. bindings.push( texture );
  22786. uniformGPU = [ texture ];
  22787. }
  22788. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  22789. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  22790. const buffer = new bufferClass( node, group );
  22791. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  22792. bindings.push( buffer );
  22793. uniformGPU = buffer;
  22794. } else {
  22795. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  22796. let uniformsGroup = uniformsStage[ groupName ];
  22797. if ( uniformsGroup === undefined ) {
  22798. uniformsGroup = new NodeUniformsGroup( groupName, group );
  22799. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  22800. uniformsStage[ groupName ] = uniformsGroup;
  22801. bindings.push( uniformsGroup );
  22802. }
  22803. uniformGPU = this.getNodeUniform( uniformNode, type );
  22804. uniformsGroup.addUniform( uniformGPU );
  22805. }
  22806. nodeData.uniformGPU = uniformGPU;
  22807. }
  22808. return uniformNode;
  22809. }
  22810. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  22811. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  22812. if ( map.has( name ) === false ) {
  22813. map.set( name, {
  22814. name,
  22815. property,
  22816. type
  22817. } );
  22818. }
  22819. return property;
  22820. }
  22821. hasBuiltin( name, shaderStage = this.shaderStage ) {
  22822. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  22823. }
  22824. getVertexIndex() {
  22825. if ( this.shaderStage === 'vertex' ) {
  22826. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  22827. }
  22828. return 'vertexIndex';
  22829. }
  22830. buildFunctionCode( shaderNode ) {
  22831. const layout = shaderNode.layout;
  22832. const flowData = this.flowShaderNode( shaderNode );
  22833. const parameters = [];
  22834. for ( const input of layout.inputs ) {
  22835. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  22836. }
  22837. //
  22838. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  22839. ${ flowData.vars }
  22840. ${ flowData.code }
  22841. `;
  22842. if ( flowData.result ) {
  22843. code += `\treturn ${ flowData.result };\n`;
  22844. }
  22845. code += '\n}\n';
  22846. //
  22847. return code;
  22848. }
  22849. getInstanceIndex() {
  22850. if ( this.shaderStage === 'vertex' ) {
  22851. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  22852. }
  22853. return 'instanceIndex';
  22854. }
  22855. getInvocationLocalIndex() {
  22856. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  22857. }
  22858. getSubgroupSize() {
  22859. this.enableSubGroups();
  22860. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  22861. }
  22862. getInvocationSubgroupIndex() {
  22863. this.enableSubGroups();
  22864. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  22865. }
  22866. getSubgroupIndex() {
  22867. this.enableSubGroups();
  22868. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  22869. }
  22870. getDrawIndex() {
  22871. return null;
  22872. }
  22873. getFrontFacing() {
  22874. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  22875. }
  22876. getFragCoord() {
  22877. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  22878. }
  22879. getFragDepth() {
  22880. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  22881. }
  22882. getClipDistance() {
  22883. return 'varyings.hw_clip_distances';
  22884. }
  22885. isFlipY() {
  22886. return false;
  22887. }
  22888. enableDirective( name, shaderStage = this.shaderStage ) {
  22889. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  22890. stage.add( name );
  22891. }
  22892. getDirectives( shaderStage ) {
  22893. const snippets = [];
  22894. const directives = this.directives[ shaderStage ];
  22895. if ( directives !== undefined ) {
  22896. for ( const directive of directives ) {
  22897. snippets.push( `enable ${directive};` );
  22898. }
  22899. }
  22900. return snippets.join( '\n' );
  22901. }
  22902. enableSubGroups() {
  22903. this.enableDirective( 'subgroups' );
  22904. }
  22905. enableSubgroupsF16() {
  22906. this.enableDirective( 'subgroups-f16' );
  22907. }
  22908. enableClipDistances() {
  22909. this.enableDirective( 'clip_distances' );
  22910. }
  22911. enableShaderF16() {
  22912. this.enableDirective( 'f16' );
  22913. }
  22914. enableDualSourceBlending() {
  22915. this.enableDirective( 'dual_source_blending' );
  22916. }
  22917. enableHardwareClipping( planeCount ) {
  22918. this.enableClipDistances();
  22919. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  22920. }
  22921. getBuiltins( shaderStage ) {
  22922. const snippets = [];
  22923. const builtins = this.builtins[ shaderStage ];
  22924. if ( builtins !== undefined ) {
  22925. for ( const { name, property, type } of builtins.values() ) {
  22926. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  22927. }
  22928. }
  22929. return snippets.join( ',\n\t' );
  22930. }
  22931. getScopedArray( name, scope, bufferType, bufferCount ) {
  22932. if ( this.scopedArrays.has( name ) === false ) {
  22933. this.scopedArrays.set( name, {
  22934. name,
  22935. scope,
  22936. bufferType,
  22937. bufferCount
  22938. } );
  22939. }
  22940. return name;
  22941. }
  22942. getScopedArrays( shaderStage ) {
  22943. if ( shaderStage !== 'compute' ) {
  22944. return;
  22945. }
  22946. const snippets = [];
  22947. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  22948. const type = this.getType( bufferType );
  22949. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  22950. }
  22951. return snippets.join( '\n' );
  22952. }
  22953. getAttributes( shaderStage ) {
  22954. const snippets = [];
  22955. if ( shaderStage === 'compute' ) {
  22956. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  22957. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  22958. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  22959. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  22960. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  22961. this.enableDirective( 'subgroups', shaderStage );
  22962. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  22963. }
  22964. }
  22965. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  22966. const builtins = this.getBuiltins( 'attribute' );
  22967. if ( builtins ) snippets.push( builtins );
  22968. const attributes = this.getAttributesArray();
  22969. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  22970. const attribute = attributes[ index ];
  22971. const name = attribute.name;
  22972. const type = this.getType( attribute.type );
  22973. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  22974. }
  22975. }
  22976. return snippets.join( ',\n\t' );
  22977. }
  22978. getStructMembers( struct ) {
  22979. const snippets = [];
  22980. const members = struct.getMemberTypes();
  22981. for ( let i = 0; i < members.length; i ++ ) {
  22982. const member = members[ i ];
  22983. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  22984. }
  22985. const builtins = this.getBuiltins( 'output' );
  22986. if ( builtins ) snippets.push( '\t' + builtins );
  22987. return snippets.join( ',\n' );
  22988. }
  22989. getStructs( shaderStage ) {
  22990. const snippets = [];
  22991. const structs = this.structs[ shaderStage ];
  22992. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  22993. const struct = structs[ index ];
  22994. const name = struct.name;
  22995. let snippet = `\struct ${ name } {\n`;
  22996. snippet += this.getStructMembers( struct );
  22997. snippet += '\n}';
  22998. snippets.push( snippet );
  22999. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  23000. }
  23001. return snippets.join( '\n\n' );
  23002. }
  23003. getVar( type, name ) {
  23004. return `var ${ name } : ${ this.getType( type ) }`;
  23005. }
  23006. getVars( shaderStage ) {
  23007. const snippets = [];
  23008. const vars = this.vars[ shaderStage ];
  23009. if ( vars !== undefined ) {
  23010. for ( const variable of vars ) {
  23011. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  23012. }
  23013. }
  23014. return `\n${ snippets.join( '\n' ) }\n`;
  23015. }
  23016. getVaryings( shaderStage ) {
  23017. const snippets = [];
  23018. if ( shaderStage === 'vertex' ) {
  23019. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  23020. }
  23021. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  23022. const varyings = this.varyings;
  23023. const vars = this.vars[ shaderStage ];
  23024. for ( let index = 0; index < varyings.length; index ++ ) {
  23025. const varying = varyings[ index ];
  23026. if ( varying.needsInterpolation ) {
  23027. let attributesSnippet = `@location( ${index} )`;
  23028. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  23029. attributesSnippet += ' @interpolate( flat )';
  23030. }
  23031. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  23032. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  23033. vars.push( varying );
  23034. }
  23035. }
  23036. }
  23037. const builtins = this.getBuiltins( shaderStage );
  23038. if ( builtins ) snippets.push( builtins );
  23039. const code = snippets.join( ',\n\t' );
  23040. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  23041. }
  23042. getUniforms( shaderStage ) {
  23043. const uniforms = this.uniforms[ shaderStage ];
  23044. const bindingSnippets = [];
  23045. const bufferSnippets = [];
  23046. const structSnippets = [];
  23047. const uniformGroups = {};
  23048. for ( const uniform of uniforms ) {
  23049. const groupName = uniform.groupNode.name;
  23050. const uniformIndexes = this.bindingsIndexes[ groupName ];
  23051. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  23052. const texture = uniform.node.value;
  23053. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  23054. if ( this.isSampleCompare( texture ) ) {
  23055. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  23056. } else {
  23057. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  23058. }
  23059. }
  23060. let textureType;
  23061. let multisampled = '';
  23062. if ( texture.isMultisampleRenderTargetTexture === true ) {
  23063. multisampled = '_multisampled';
  23064. }
  23065. if ( texture.isCubeTexture === true ) {
  23066. textureType = 'texture_cube<f32>';
  23067. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  23068. textureType = 'texture_2d_array<f32>';
  23069. } else if ( texture.isDepthTexture === true ) {
  23070. textureType = `texture_depth${multisampled}_2d`;
  23071. } else if ( texture.isVideoTexture === true ) {
  23072. textureType = 'texture_external';
  23073. } else if ( texture.isData3DTexture === true ) {
  23074. textureType = 'texture_3d<f32>';
  23075. } else if ( uniform.node.isStorageTextureNode === true ) {
  23076. const format = getFormat( texture );
  23077. const access = this.getStorageAccess( uniform.node, shaderStage );
  23078. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  23079. } else {
  23080. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  23081. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  23082. }
  23083. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  23084. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  23085. const bufferNode = uniform.node;
  23086. const bufferType = this.getType( bufferNode.bufferType );
  23087. const bufferCount = bufferNode.bufferCount;
  23088. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  23089. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${bufferType}>` : `${bufferType}`;
  23090. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >\n`;
  23091. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  23092. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  23093. } else {
  23094. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  23095. const groupName = uniform.groupNode.name;
  23096. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  23097. index: uniformIndexes.binding ++,
  23098. id: uniformIndexes.group,
  23099. snippets: []
  23100. } );
  23101. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  23102. }
  23103. }
  23104. for ( const name in uniformGroups ) {
  23105. const group = uniformGroups[ name ];
  23106. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  23107. }
  23108. let code = bindingSnippets.join( '\n' );
  23109. code += bufferSnippets.join( '\n' );
  23110. code += structSnippets.join( '\n' );
  23111. return code;
  23112. }
  23113. buildCode() {
  23114. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  23115. this.sortBindingGroups();
  23116. for ( const shaderStage in shadersData ) {
  23117. const stageData = shadersData[ shaderStage ];
  23118. stageData.uniforms = this.getUniforms( shaderStage );
  23119. stageData.attributes = this.getAttributes( shaderStage );
  23120. stageData.varyings = this.getVaryings( shaderStage );
  23121. stageData.structs = this.getStructs( shaderStage );
  23122. stageData.vars = this.getVars( shaderStage );
  23123. stageData.codes = this.getCodes( shaderStage );
  23124. stageData.directives = this.getDirectives( shaderStage );
  23125. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  23126. //
  23127. let flow = '// code\n\n';
  23128. flow += this.flowCode[ shaderStage ];
  23129. const flowNodes = this.flowNodes[ shaderStage ];
  23130. const mainNode = flowNodes[ flowNodes.length - 1 ];
  23131. const outputNode = mainNode.outputNode;
  23132. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  23133. for ( const node of flowNodes ) {
  23134. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  23135. const slotName = node.name;
  23136. if ( slotName ) {
  23137. if ( flow.length > 0 ) flow += '\n';
  23138. flow += `\t// flow -> ${ slotName }\n\t`;
  23139. }
  23140. flow += `${ flowSlotData.code }\n\t`;
  23141. if ( node === mainNode && shaderStage !== 'compute' ) {
  23142. flow += '// result\n\n\t';
  23143. if ( shaderStage === 'vertex' ) {
  23144. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  23145. } else if ( shaderStage === 'fragment' ) {
  23146. if ( isOutputStruct ) {
  23147. stageData.returnType = outputNode.nodeType;
  23148. flow += `return ${ flowSlotData.result };`;
  23149. } else {
  23150. let structSnippet = '\t@location(0) color: vec4<f32>';
  23151. const builtins = this.getBuiltins( 'output' );
  23152. if ( builtins ) structSnippet += ',\n\t' + builtins;
  23153. stageData.returnType = 'OutputStruct';
  23154. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  23155. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  23156. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  23157. }
  23158. }
  23159. }
  23160. }
  23161. stageData.flow = flow;
  23162. }
  23163. if ( this.material !== null ) {
  23164. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  23165. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  23166. } else {
  23167. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  23168. }
  23169. }
  23170. getMethod( method, output = null ) {
  23171. let wgslMethod;
  23172. if ( output !== null ) {
  23173. wgslMethod = this._getWGSLMethod( method + '_' + output );
  23174. }
  23175. if ( wgslMethod === undefined ) {
  23176. wgslMethod = this._getWGSLMethod( method );
  23177. }
  23178. return wgslMethod || method;
  23179. }
  23180. getType( type ) {
  23181. return wgslTypeLib[ type ] || type;
  23182. }
  23183. isAvailable( name ) {
  23184. let result = supports[ name ];
  23185. if ( result === undefined ) {
  23186. if ( name === 'float32Filterable' ) {
  23187. result = this.renderer.hasFeature( 'float32-filterable' );
  23188. } else if ( name === 'clipDistance' ) {
  23189. result = this.renderer.hasFeature( 'clip-distances' );
  23190. }
  23191. supports[ name ] = result;
  23192. }
  23193. return result;
  23194. }
  23195. _getWGSLMethod( method ) {
  23196. if ( wgslPolyfill[ method ] !== undefined ) {
  23197. this._include( method );
  23198. }
  23199. return wgslMethods[ method ];
  23200. }
  23201. _include( name ) {
  23202. const codeNode = wgslPolyfill[ name ];
  23203. codeNode.build( this );
  23204. if ( this.currentFunctionNode !== null ) {
  23205. this.currentFunctionNode.includes.push( codeNode );
  23206. }
  23207. return codeNode;
  23208. }
  23209. _getWGSLVertexCode( shaderData ) {
  23210. return `${ this.getSignature() }
  23211. // directives
  23212. ${shaderData.directives}
  23213. // uniforms
  23214. ${shaderData.uniforms}
  23215. // varyings
  23216. ${shaderData.varyings}
  23217. var<private> varyings : VaryingsStruct;
  23218. // codes
  23219. ${shaderData.codes}
  23220. @vertex
  23221. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  23222. // vars
  23223. ${shaderData.vars}
  23224. // flow
  23225. ${shaderData.flow}
  23226. return varyings;
  23227. }
  23228. `;
  23229. }
  23230. _getWGSLFragmentCode( shaderData ) {
  23231. return `${ this.getSignature() }
  23232. // global
  23233. ${ diagnostics }
  23234. // uniforms
  23235. ${shaderData.uniforms}
  23236. // structs
  23237. ${shaderData.structs}
  23238. // codes
  23239. ${shaderData.codes}
  23240. @fragment
  23241. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  23242. // vars
  23243. ${shaderData.vars}
  23244. // flow
  23245. ${shaderData.flow}
  23246. }
  23247. `;
  23248. }
  23249. _getWGSLComputeCode( shaderData, workgroupSize ) {
  23250. return `${ this.getSignature() }
  23251. // directives
  23252. ${shaderData.directives}
  23253. // system
  23254. var<private> instanceIndex : u32;
  23255. // locals
  23256. ${shaderData.scopedArrays}
  23257. // uniforms
  23258. ${shaderData.uniforms}
  23259. // codes
  23260. ${shaderData.codes}
  23261. @compute @workgroup_size( ${workgroupSize} )
  23262. fn main( ${shaderData.attributes} ) {
  23263. // system
  23264. instanceIndex = id.x + id.y * numWorkgroups.x * u32(${workgroupSize}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  23265. // vars
  23266. ${shaderData.vars}
  23267. // flow
  23268. ${shaderData.flow}
  23269. }
  23270. `;
  23271. }
  23272. _getWGSLStruct( name, vars ) {
  23273. return `
  23274. struct ${name} {
  23275. ${vars}
  23276. };`;
  23277. }
  23278. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  23279. const structName = name + 'Struct';
  23280. const structSnippet = this._getWGSLStruct( structName, vars );
  23281. return `${structSnippet}
  23282. @binding( ${binding} ) @group( ${group} )
  23283. var<${access}> ${name} : ${structName};`;
  23284. }
  23285. }
  23286. class WebGPUUtils {
  23287. constructor( backend ) {
  23288. this.backend = backend;
  23289. }
  23290. getCurrentDepthStencilFormat( renderContext ) {
  23291. let format;
  23292. if ( renderContext.depthTexture !== null ) {
  23293. format = this.getTextureFormatGPU( renderContext.depthTexture );
  23294. } else if ( renderContext.depth && renderContext.stencil ) {
  23295. format = GPUTextureFormat.Depth24PlusStencil8;
  23296. } else if ( renderContext.depth ) {
  23297. format = GPUTextureFormat.Depth24Plus;
  23298. }
  23299. return format;
  23300. }
  23301. getTextureFormatGPU( texture ) {
  23302. return this.backend.get( texture ).format;
  23303. }
  23304. getCurrentColorFormat( renderContext ) {
  23305. let format;
  23306. if ( renderContext.textures !== null ) {
  23307. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  23308. } else {
  23309. format = this.getPreferredCanvasFormat(); // default context format
  23310. }
  23311. return format;
  23312. }
  23313. getCurrentColorSpace( renderContext ) {
  23314. if ( renderContext.textures !== null ) {
  23315. return renderContext.textures[ 0 ].colorSpace;
  23316. }
  23317. return this.backend.renderer.outputColorSpace;
  23318. }
  23319. getPrimitiveTopology( object, material ) {
  23320. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  23321. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  23322. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  23323. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  23324. }
  23325. getSampleCount( sampleCount ) {
  23326. let count = 1;
  23327. if ( sampleCount > 1 ) {
  23328. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  23329. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  23330. if ( count === 2 ) {
  23331. count = 4;
  23332. }
  23333. }
  23334. return count;
  23335. }
  23336. getSampleCountRenderContext( renderContext ) {
  23337. if ( renderContext.textures !== null ) {
  23338. return this.getSampleCount( renderContext.sampleCount );
  23339. }
  23340. return this.getSampleCount( this.backend.renderer.samples );
  23341. }
  23342. getPreferredCanvasFormat() {
  23343. // TODO: Remove this check when Quest 34.5 is out
  23344. // https://github.com/mrdoob/three.js/pull/29221/files#r1731833949
  23345. if ( navigator.userAgent.includes( 'Quest' ) ) {
  23346. return GPUTextureFormat.BGRA8Unorm;
  23347. } else {
  23348. return navigator.gpu.getPreferredCanvasFormat();
  23349. }
  23350. }
  23351. }
  23352. const typedArraysToVertexFormatPrefix = new Map( [
  23353. [ Int8Array, [ 'sint8', 'snorm8' ]],
  23354. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  23355. [ Int16Array, [ 'sint16', 'snorm16' ]],
  23356. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  23357. [ Int32Array, [ 'sint32', 'snorm32' ]],
  23358. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  23359. [ Float32Array, [ 'float32', ]],
  23360. ] );
  23361. const typedAttributeToVertexFormatPrefix = new Map( [
  23362. [ Float16BufferAttribute, [ 'float16', ]],
  23363. ] );
  23364. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  23365. [ Int32Array, 'sint32' ],
  23366. [ Int16Array, 'sint32' ], // patch for INT16
  23367. [ Uint32Array, 'uint32' ],
  23368. [ Uint16Array, 'uint32' ], // patch for UINT16
  23369. [ Float32Array, 'float32' ]
  23370. ] );
  23371. class WebGPUAttributeUtils {
  23372. constructor( backend ) {
  23373. this.backend = backend;
  23374. }
  23375. createAttribute( attribute, usage ) {
  23376. const bufferAttribute = this._getBufferAttribute( attribute );
  23377. const backend = this.backend;
  23378. const bufferData = backend.get( bufferAttribute );
  23379. let buffer = bufferData.buffer;
  23380. if ( buffer === undefined ) {
  23381. const device = backend.device;
  23382. let array = bufferAttribute.array;
  23383. // patch for INT16 and UINT16
  23384. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  23385. const tempArray = new Uint32Array( array.length );
  23386. for ( let i = 0; i < array.length; i ++ ) {
  23387. tempArray[ i ] = array[ i ];
  23388. }
  23389. array = tempArray;
  23390. }
  23391. bufferAttribute.array = array;
  23392. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  23393. array = new array.constructor( bufferAttribute.count * 4 );
  23394. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  23395. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  23396. }
  23397. // Update BufferAttribute
  23398. bufferAttribute.itemSize = 4;
  23399. bufferAttribute.array = array;
  23400. }
  23401. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  23402. buffer = device.createBuffer( {
  23403. label: bufferAttribute.name,
  23404. size: size,
  23405. usage: usage,
  23406. mappedAtCreation: true
  23407. } );
  23408. new array.constructor( buffer.getMappedRange() ).set( array );
  23409. buffer.unmap();
  23410. bufferData.buffer = buffer;
  23411. }
  23412. }
  23413. updateAttribute( attribute ) {
  23414. const bufferAttribute = this._getBufferAttribute( attribute );
  23415. const backend = this.backend;
  23416. const device = backend.device;
  23417. const buffer = backend.get( bufferAttribute ).buffer;
  23418. const array = bufferAttribute.array;
  23419. const isTypedArray = this._isTypedArray( array );
  23420. const updateRanges = bufferAttribute.updateRanges;
  23421. if ( updateRanges.length === 0 ) {
  23422. // Not using update ranges
  23423. device.queue.writeBuffer(
  23424. buffer,
  23425. 0,
  23426. array,
  23427. 0
  23428. );
  23429. } else {
  23430. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  23431. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  23432. const range = updateRanges[ i ];
  23433. const dataOffset = range.start * byteOffsetFactor;
  23434. const size = range.count * byteOffsetFactor;
  23435. device.queue.writeBuffer(
  23436. buffer,
  23437. 0,
  23438. array,
  23439. dataOffset,
  23440. size
  23441. );
  23442. }
  23443. bufferAttribute.clearUpdateRanges();
  23444. }
  23445. }
  23446. createShaderVertexBuffers( renderObject ) {
  23447. const attributes = renderObject.getAttributes();
  23448. const vertexBuffers = new Map();
  23449. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  23450. const geometryAttribute = attributes[ slot ];
  23451. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  23452. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  23453. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  23454. if ( vertexBufferLayout === undefined ) {
  23455. let arrayStride, stepMode;
  23456. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  23457. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  23458. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  23459. } else {
  23460. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  23461. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  23462. }
  23463. // patch for INT16 and UINT16
  23464. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  23465. arrayStride = 4;
  23466. }
  23467. vertexBufferLayout = {
  23468. arrayStride,
  23469. attributes: [],
  23470. stepMode
  23471. };
  23472. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  23473. }
  23474. const format = this._getVertexFormat( geometryAttribute );
  23475. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  23476. vertexBufferLayout.attributes.push( {
  23477. shaderLocation: slot,
  23478. offset,
  23479. format
  23480. } );
  23481. }
  23482. return Array.from( vertexBuffers.values() );
  23483. }
  23484. destroyAttribute( attribute ) {
  23485. const backend = this.backend;
  23486. const data = backend.get( this._getBufferAttribute( attribute ) );
  23487. data.buffer.destroy();
  23488. backend.delete( attribute );
  23489. }
  23490. async getArrayBufferAsync( attribute ) {
  23491. const backend = this.backend;
  23492. const device = backend.device;
  23493. const data = backend.get( this._getBufferAttribute( attribute ) );
  23494. const bufferGPU = data.buffer;
  23495. const size = bufferGPU.size;
  23496. const readBufferGPU = device.createBuffer( {
  23497. label: attribute.name,
  23498. size,
  23499. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  23500. } );
  23501. const cmdEncoder = device.createCommandEncoder( {} );
  23502. cmdEncoder.copyBufferToBuffer(
  23503. bufferGPU,
  23504. 0,
  23505. readBufferGPU,
  23506. 0,
  23507. size
  23508. );
  23509. readBufferGPU.unmap();
  23510. const gpuCommands = cmdEncoder.finish();
  23511. device.queue.submit( [ gpuCommands ] );
  23512. await readBufferGPU.mapAsync( GPUMapMode.READ );
  23513. const arrayBuffer = readBufferGPU.getMappedRange();
  23514. return arrayBuffer;
  23515. }
  23516. _getVertexFormat( geometryAttribute ) {
  23517. const { itemSize, normalized } = geometryAttribute;
  23518. const ArrayType = geometryAttribute.array.constructor;
  23519. const AttributeType = geometryAttribute.constructor;
  23520. let format;
  23521. if ( itemSize == 1 ) {
  23522. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  23523. } else {
  23524. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  23525. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  23526. if ( prefix ) {
  23527. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  23528. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  23529. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  23530. if ( paddedItemSize % 1 ) {
  23531. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  23532. }
  23533. format = `${prefix}x${paddedItemSize}`;
  23534. }
  23535. }
  23536. if ( ! format ) {
  23537. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  23538. }
  23539. return format;
  23540. }
  23541. _isTypedArray( array ) {
  23542. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  23543. }
  23544. _getBufferAttribute( attribute ) {
  23545. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  23546. return attribute;
  23547. }
  23548. }
  23549. class WebGPUBindingUtils {
  23550. constructor( backend ) {
  23551. this.backend = backend;
  23552. this.bindGroupLayoutCache = new WeakMap();
  23553. }
  23554. createBindingsLayout( bindGroup ) {
  23555. const backend = this.backend;
  23556. const device = backend.device;
  23557. const entries = [];
  23558. let index = 0;
  23559. for ( const binding of bindGroup.bindings ) {
  23560. const bindingGPU = {
  23561. binding: index ++,
  23562. visibility: binding.visibility
  23563. };
  23564. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  23565. const buffer = {}; // GPUBufferBindingLayout
  23566. if ( binding.isStorageBuffer ) {
  23567. if ( binding.visibility & 4 ) {
  23568. // compute
  23569. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  23570. buffer.type = GPUBufferBindingType.Storage;
  23571. } else {
  23572. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  23573. }
  23574. } else {
  23575. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  23576. }
  23577. }
  23578. bindingGPU.buffer = buffer;
  23579. } else if ( binding.isSampler ) {
  23580. const sampler = {}; // GPUSamplerBindingLayout
  23581. if ( binding.texture.isDepthTexture ) {
  23582. if ( binding.texture.compareFunction !== null ) {
  23583. sampler.type = 'comparison';
  23584. }
  23585. }
  23586. bindingGPU.sampler = sampler;
  23587. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  23588. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  23589. } else if ( binding.isSampledTexture && binding.store ) {
  23590. const storageTexture = {}; // GPUStorageTextureBindingLayout
  23591. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  23592. const access = binding.access;
  23593. if ( access === NodeAccess.READ_WRITE ) {
  23594. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  23595. } else if ( access === NodeAccess.WRITE_ONLY ) {
  23596. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  23597. } else {
  23598. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  23599. }
  23600. bindingGPU.storageTexture = storageTexture;
  23601. } else if ( binding.isSampledTexture ) {
  23602. const texture = {}; // GPUTextureBindingLayout
  23603. if ( binding.texture.isMultisampleRenderTargetTexture === true ) {
  23604. texture.multisampled = true;
  23605. }
  23606. if ( binding.texture.isDepthTexture ) {
  23607. texture.sampleType = GPUTextureSampleType.Depth;
  23608. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  23609. const type = binding.texture.type;
  23610. if ( type === IntType ) {
  23611. texture.sampleType = GPUTextureSampleType.SInt;
  23612. } else if ( type === UnsignedIntType ) {
  23613. texture.sampleType = GPUTextureSampleType.UInt;
  23614. } else if ( type === FloatType ) {
  23615. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  23616. texture.sampleType = GPUTextureSampleType.Float;
  23617. } else {
  23618. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  23619. }
  23620. }
  23621. }
  23622. if ( binding.isSampledCubeTexture ) {
  23623. texture.viewDimension = GPUTextureViewDimension.Cube;
  23624. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  23625. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  23626. } else if ( binding.isSampledTexture3D ) {
  23627. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  23628. }
  23629. bindingGPU.texture = texture;
  23630. } else {
  23631. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  23632. }
  23633. entries.push( bindingGPU );
  23634. }
  23635. return device.createBindGroupLayout( { entries } );
  23636. }
  23637. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  23638. const { backend, bindGroupLayoutCache } = this;
  23639. const bindingsData = backend.get( bindGroup );
  23640. // setup (static) binding layout and (dynamic) binding group
  23641. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  23642. if ( bindLayoutGPU === undefined ) {
  23643. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  23644. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  23645. }
  23646. let bindGroupGPU;
  23647. if ( cacheIndex > 0 ) {
  23648. if ( bindingsData.groups === undefined ) {
  23649. bindingsData.groups = [];
  23650. bindingsData.versions = [];
  23651. }
  23652. if ( bindingsData.versions[ cacheIndex ] === version ) {
  23653. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  23654. }
  23655. }
  23656. if ( bindGroupGPU === undefined ) {
  23657. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  23658. if ( cacheIndex > 0 ) {
  23659. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  23660. bindingsData.versions[ cacheIndex ] = version;
  23661. }
  23662. }
  23663. bindingsData.group = bindGroupGPU;
  23664. bindingsData.layout = bindLayoutGPU;
  23665. }
  23666. updateBinding( binding ) {
  23667. const backend = this.backend;
  23668. const device = backend.device;
  23669. const buffer = binding.buffer;
  23670. const bufferGPU = backend.get( binding ).buffer;
  23671. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  23672. }
  23673. createBindGroup( bindGroup, layoutGPU ) {
  23674. const backend = this.backend;
  23675. const device = backend.device;
  23676. let bindingPoint = 0;
  23677. const entriesGPU = [];
  23678. for ( const binding of bindGroup.bindings ) {
  23679. if ( binding.isUniformBuffer ) {
  23680. const bindingData = backend.get( binding );
  23681. if ( bindingData.buffer === undefined ) {
  23682. const byteLength = binding.byteLength;
  23683. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  23684. const bufferGPU = device.createBuffer( {
  23685. label: 'bindingBuffer_' + binding.name,
  23686. size: byteLength,
  23687. usage: usage
  23688. } );
  23689. bindingData.buffer = bufferGPU;
  23690. }
  23691. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  23692. } else if ( binding.isStorageBuffer ) {
  23693. const bindingData = backend.get( binding );
  23694. if ( bindingData.buffer === undefined ) {
  23695. const attribute = binding.attribute;
  23696. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  23697. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  23698. bindingData.buffer = backend.get( attribute ).buffer;
  23699. }
  23700. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  23701. } else if ( binding.isSampler ) {
  23702. const textureGPU = backend.get( binding.texture );
  23703. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  23704. } else if ( binding.isSampledTexture ) {
  23705. const textureData = backend.get( binding.texture );
  23706. let resourceGPU;
  23707. if ( textureData.externalTexture !== undefined ) {
  23708. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  23709. } else {
  23710. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  23711. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  23712. resourceGPU = textureData[ propertyName ];
  23713. if ( resourceGPU === undefined ) {
  23714. const aspectGPU = GPUTextureAspect.All;
  23715. let dimensionViewGPU;
  23716. if ( binding.isSampledCubeTexture ) {
  23717. dimensionViewGPU = GPUTextureViewDimension.Cube;
  23718. } else if ( binding.isSampledTexture3D ) {
  23719. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  23720. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  23721. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  23722. } else {
  23723. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  23724. }
  23725. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  23726. }
  23727. }
  23728. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  23729. }
  23730. bindingPoint ++;
  23731. }
  23732. return device.createBindGroup( {
  23733. label: 'bindGroup_' + bindGroup.name,
  23734. layout: layoutGPU,
  23735. entries: entriesGPU
  23736. } );
  23737. }
  23738. }
  23739. class WebGPUPipelineUtils {
  23740. constructor( backend ) {
  23741. this.backend = backend;
  23742. }
  23743. _getSampleCount( renderObjectContext ) {
  23744. return this.backend.utils.getSampleCountRenderContext( renderObjectContext );
  23745. }
  23746. createRenderPipeline( renderObject, promises ) {
  23747. const { object, material, geometry, pipeline } = renderObject;
  23748. const { vertexProgram, fragmentProgram } = pipeline;
  23749. const backend = this.backend;
  23750. const device = backend.device;
  23751. const utils = backend.utils;
  23752. const pipelineData = backend.get( pipeline );
  23753. // bind group layouts
  23754. const bindGroupLayouts = [];
  23755. for ( const bindGroup of renderObject.getBindings() ) {
  23756. const bindingsData = backend.get( bindGroup );
  23757. bindGroupLayouts.push( bindingsData.layout );
  23758. }
  23759. // vertex buffers
  23760. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  23761. // blending
  23762. let blending;
  23763. if ( material.transparent === true && material.blending !== NoBlending ) {
  23764. blending = this._getBlending( material );
  23765. }
  23766. // stencil
  23767. let stencilFront = {};
  23768. if ( material.stencilWrite === true ) {
  23769. stencilFront = {
  23770. compare: this._getStencilCompare( material ),
  23771. failOp: this._getStencilOperation( material.stencilFail ),
  23772. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  23773. passOp: this._getStencilOperation( material.stencilZPass )
  23774. };
  23775. }
  23776. const colorWriteMask = this._getColorWriteMask( material );
  23777. const targets = [];
  23778. if ( renderObject.context.textures !== null ) {
  23779. const textures = renderObject.context.textures;
  23780. for ( let i = 0; i < textures.length; i ++ ) {
  23781. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  23782. targets.push( {
  23783. format: colorFormat,
  23784. blend: blending,
  23785. writeMask: colorWriteMask
  23786. } );
  23787. }
  23788. } else {
  23789. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  23790. targets.push( {
  23791. format: colorFormat,
  23792. blend: blending,
  23793. writeMask: colorWriteMask
  23794. } );
  23795. }
  23796. const vertexModule = backend.get( vertexProgram ).module;
  23797. const fragmentModule = backend.get( fragmentProgram ).module;
  23798. const primitiveState = this._getPrimitiveState( object, geometry, material );
  23799. const depthCompare = this._getDepthCompare( material );
  23800. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  23801. const sampleCount = this._getSampleCount( renderObject.context );
  23802. const pipelineDescriptor = {
  23803. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  23804. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  23805. fragment: Object.assign( {}, fragmentModule, { targets } ),
  23806. primitive: primitiveState,
  23807. multisample: {
  23808. count: sampleCount,
  23809. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  23810. },
  23811. layout: device.createPipelineLayout( {
  23812. bindGroupLayouts
  23813. } )
  23814. };
  23815. const depthStencil = {};
  23816. const renderDepth = renderObject.context.depth;
  23817. const renderStencil = renderObject.context.stencil;
  23818. if ( renderDepth === true || renderStencil === true ) {
  23819. if ( renderDepth === true ) {
  23820. depthStencil.format = depthStencilFormat;
  23821. depthStencil.depthWriteEnabled = material.depthWrite;
  23822. depthStencil.depthCompare = depthCompare;
  23823. }
  23824. if ( renderStencil === true ) {
  23825. depthStencil.stencilFront = stencilFront;
  23826. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  23827. depthStencil.stencilReadMask = material.stencilFuncMask;
  23828. depthStencil.stencilWriteMask = material.stencilWriteMask;
  23829. }
  23830. pipelineDescriptor.depthStencil = depthStencil;
  23831. }
  23832. if ( promises === null ) {
  23833. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  23834. } else {
  23835. const p = new Promise( ( resolve /*, reject*/ ) => {
  23836. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  23837. pipelineData.pipeline = pipeline;
  23838. resolve();
  23839. } );
  23840. } );
  23841. promises.push( p );
  23842. }
  23843. }
  23844. createBundleEncoder( renderContext ) {
  23845. const backend = this.backend;
  23846. const { utils, device } = backend;
  23847. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  23848. const colorFormat = utils.getCurrentColorFormat( renderContext );
  23849. const sampleCount = this._getSampleCount( renderContext );
  23850. const descriptor = {
  23851. label: 'renderBundleEncoder',
  23852. colorFormats: [ colorFormat ],
  23853. depthStencilFormat,
  23854. sampleCount
  23855. };
  23856. return device.createRenderBundleEncoder( descriptor );
  23857. }
  23858. createComputePipeline( pipeline, bindings ) {
  23859. const backend = this.backend;
  23860. const device = backend.device;
  23861. const computeProgram = backend.get( pipeline.computeProgram ).module;
  23862. const pipelineGPU = backend.get( pipeline );
  23863. // bind group layouts
  23864. const bindGroupLayouts = [];
  23865. for ( const bindingsGroup of bindings ) {
  23866. const bindingsData = backend.get( bindingsGroup );
  23867. bindGroupLayouts.push( bindingsData.layout );
  23868. }
  23869. pipelineGPU.pipeline = device.createComputePipeline( {
  23870. compute: computeProgram,
  23871. layout: device.createPipelineLayout( {
  23872. bindGroupLayouts
  23873. } )
  23874. } );
  23875. }
  23876. _getBlending( material ) {
  23877. let color, alpha;
  23878. const blending = material.blending;
  23879. const blendSrc = material.blendSrc;
  23880. const blendDst = material.blendDst;
  23881. const blendEquation = material.blendEquation;
  23882. if ( blending === CustomBlending ) {
  23883. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  23884. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  23885. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  23886. color = {
  23887. srcFactor: this._getBlendFactor( blendSrc ),
  23888. dstFactor: this._getBlendFactor( blendDst ),
  23889. operation: this._getBlendOperation( blendEquation )
  23890. };
  23891. alpha = {
  23892. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  23893. dstFactor: this._getBlendFactor( blendDstAlpha ),
  23894. operation: this._getBlendOperation( blendEquationAlpha )
  23895. };
  23896. } else {
  23897. const premultipliedAlpha = material.premultipliedAlpha;
  23898. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  23899. color = {
  23900. srcFactor: srcRGB,
  23901. dstFactor: dstRGB,
  23902. operation: GPUBlendOperation.Add
  23903. };
  23904. alpha = {
  23905. srcFactor: srcAlpha,
  23906. dstFactor: dstAlpha,
  23907. operation: GPUBlendOperation.Add
  23908. };
  23909. };
  23910. if ( premultipliedAlpha ) {
  23911. switch ( blending ) {
  23912. case NormalBlending:
  23913. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  23914. break;
  23915. case AdditiveBlending:
  23916. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  23917. break;
  23918. case SubtractiveBlending:
  23919. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  23920. break;
  23921. case MultiplyBlending:
  23922. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  23923. break;
  23924. }
  23925. } else {
  23926. switch ( blending ) {
  23927. case NormalBlending:
  23928. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  23929. break;
  23930. case AdditiveBlending:
  23931. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  23932. break;
  23933. case SubtractiveBlending:
  23934. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  23935. break;
  23936. case MultiplyBlending:
  23937. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  23938. break;
  23939. }
  23940. }
  23941. }
  23942. if ( color !== undefined && alpha !== undefined ) {
  23943. return { color, alpha };
  23944. } else {
  23945. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  23946. }
  23947. }
  23948. _getBlendFactor( blend ) {
  23949. let blendFactor;
  23950. switch ( blend ) {
  23951. case ZeroFactor:
  23952. blendFactor = GPUBlendFactor.Zero;
  23953. break;
  23954. case OneFactor:
  23955. blendFactor = GPUBlendFactor.One;
  23956. break;
  23957. case SrcColorFactor:
  23958. blendFactor = GPUBlendFactor.Src;
  23959. break;
  23960. case OneMinusSrcColorFactor:
  23961. blendFactor = GPUBlendFactor.OneMinusSrc;
  23962. break;
  23963. case SrcAlphaFactor:
  23964. blendFactor = GPUBlendFactor.SrcAlpha;
  23965. break;
  23966. case OneMinusSrcAlphaFactor:
  23967. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  23968. break;
  23969. case DstColorFactor:
  23970. blendFactor = GPUBlendFactor.Dst;
  23971. break;
  23972. case OneMinusDstColorFactor:
  23973. blendFactor = GPUBlendFactor.OneMinusDstColor;
  23974. break;
  23975. case DstAlphaFactor:
  23976. blendFactor = GPUBlendFactor.DstAlpha;
  23977. break;
  23978. case OneMinusDstAlphaFactor:
  23979. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  23980. break;
  23981. case SrcAlphaSaturateFactor:
  23982. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  23983. break;
  23984. case BlendColorFactor:
  23985. blendFactor = GPUBlendFactor.Constant;
  23986. break;
  23987. case OneMinusBlendColorFactor:
  23988. blendFactor = GPUBlendFactor.OneMinusConstant;
  23989. break;
  23990. default:
  23991. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  23992. }
  23993. return blendFactor;
  23994. }
  23995. _getStencilCompare( material ) {
  23996. let stencilCompare;
  23997. const stencilFunc = material.stencilFunc;
  23998. switch ( stencilFunc ) {
  23999. case NeverStencilFunc:
  24000. stencilCompare = GPUCompareFunction.Never;
  24001. break;
  24002. case AlwaysStencilFunc:
  24003. stencilCompare = GPUCompareFunction.Always;
  24004. break;
  24005. case LessStencilFunc:
  24006. stencilCompare = GPUCompareFunction.Less;
  24007. break;
  24008. case LessEqualStencilFunc:
  24009. stencilCompare = GPUCompareFunction.LessEqual;
  24010. break;
  24011. case EqualStencilFunc:
  24012. stencilCompare = GPUCompareFunction.Equal;
  24013. break;
  24014. case GreaterEqualStencilFunc:
  24015. stencilCompare = GPUCompareFunction.GreaterEqual;
  24016. break;
  24017. case GreaterStencilFunc:
  24018. stencilCompare = GPUCompareFunction.Greater;
  24019. break;
  24020. case NotEqualStencilFunc:
  24021. stencilCompare = GPUCompareFunction.NotEqual;
  24022. break;
  24023. default:
  24024. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  24025. }
  24026. return stencilCompare;
  24027. }
  24028. _getStencilOperation( op ) {
  24029. let stencilOperation;
  24030. switch ( op ) {
  24031. case KeepStencilOp:
  24032. stencilOperation = GPUStencilOperation.Keep;
  24033. break;
  24034. case ZeroStencilOp:
  24035. stencilOperation = GPUStencilOperation.Zero;
  24036. break;
  24037. case ReplaceStencilOp:
  24038. stencilOperation = GPUStencilOperation.Replace;
  24039. break;
  24040. case InvertStencilOp:
  24041. stencilOperation = GPUStencilOperation.Invert;
  24042. break;
  24043. case IncrementStencilOp:
  24044. stencilOperation = GPUStencilOperation.IncrementClamp;
  24045. break;
  24046. case DecrementStencilOp:
  24047. stencilOperation = GPUStencilOperation.DecrementClamp;
  24048. break;
  24049. case IncrementWrapStencilOp:
  24050. stencilOperation = GPUStencilOperation.IncrementWrap;
  24051. break;
  24052. case DecrementWrapStencilOp:
  24053. stencilOperation = GPUStencilOperation.DecrementWrap;
  24054. break;
  24055. default:
  24056. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  24057. }
  24058. return stencilOperation;
  24059. }
  24060. _getBlendOperation( blendEquation ) {
  24061. let blendOperation;
  24062. switch ( blendEquation ) {
  24063. case AddEquation:
  24064. blendOperation = GPUBlendOperation.Add;
  24065. break;
  24066. case SubtractEquation:
  24067. blendOperation = GPUBlendOperation.Subtract;
  24068. break;
  24069. case ReverseSubtractEquation:
  24070. blendOperation = GPUBlendOperation.ReverseSubtract;
  24071. break;
  24072. case MinEquation:
  24073. blendOperation = GPUBlendOperation.Min;
  24074. break;
  24075. case MaxEquation:
  24076. blendOperation = GPUBlendOperation.Max;
  24077. break;
  24078. default:
  24079. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  24080. }
  24081. return blendOperation;
  24082. }
  24083. _getPrimitiveState( object, geometry, material ) {
  24084. const descriptor = {};
  24085. const utils = this.backend.utils;
  24086. descriptor.topology = utils.getPrimitiveTopology( object, material );
  24087. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  24088. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  24089. }
  24090. switch ( material.side ) {
  24091. case FrontSide:
  24092. descriptor.frontFace = GPUFrontFace.CCW;
  24093. descriptor.cullMode = GPUCullMode.Back;
  24094. break;
  24095. case BackSide:
  24096. descriptor.frontFace = GPUFrontFace.CCW;
  24097. descriptor.cullMode = GPUCullMode.Front;
  24098. break;
  24099. case DoubleSide:
  24100. descriptor.frontFace = GPUFrontFace.CCW;
  24101. descriptor.cullMode = GPUCullMode.None;
  24102. break;
  24103. default:
  24104. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  24105. break;
  24106. }
  24107. return descriptor;
  24108. }
  24109. _getColorWriteMask( material ) {
  24110. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  24111. }
  24112. _getDepthCompare( material ) {
  24113. let depthCompare;
  24114. if ( material.depthTest === false ) {
  24115. depthCompare = GPUCompareFunction.Always;
  24116. } else {
  24117. const depthFunc = material.depthFunc;
  24118. switch ( depthFunc ) {
  24119. case NeverDepth:
  24120. depthCompare = GPUCompareFunction.Never;
  24121. break;
  24122. case AlwaysDepth:
  24123. depthCompare = GPUCompareFunction.Always;
  24124. break;
  24125. case LessDepth:
  24126. depthCompare = GPUCompareFunction.Less;
  24127. break;
  24128. case LessEqualDepth:
  24129. depthCompare = GPUCompareFunction.LessEqual;
  24130. break;
  24131. case EqualDepth:
  24132. depthCompare = GPUCompareFunction.Equal;
  24133. break;
  24134. case GreaterEqualDepth:
  24135. depthCompare = GPUCompareFunction.GreaterEqual;
  24136. break;
  24137. case GreaterDepth:
  24138. depthCompare = GPUCompareFunction.Greater;
  24139. break;
  24140. case NotEqualDepth:
  24141. depthCompare = GPUCompareFunction.NotEqual;
  24142. break;
  24143. default:
  24144. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  24145. }
  24146. }
  24147. return depthCompare;
  24148. }
  24149. }
  24150. /*// debugger tools
  24151. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  24152. //*/
  24153. //
  24154. class WebGPUBackend extends Backend {
  24155. constructor( parameters = {} ) {
  24156. super( parameters );
  24157. this.isWebGPUBackend = true;
  24158. // some parameters require default values other than "undefined"
  24159. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  24160. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  24161. this.trackTimestamp = ( parameters.trackTimestamp === true );
  24162. this.device = null;
  24163. this.context = null;
  24164. this.colorBuffer = null;
  24165. this.defaultRenderPassdescriptor = null;
  24166. this.utils = new WebGPUUtils( this );
  24167. this.attributeUtils = new WebGPUAttributeUtils( this );
  24168. this.bindingUtils = new WebGPUBindingUtils( this );
  24169. this.pipelineUtils = new WebGPUPipelineUtils( this );
  24170. this.textureUtils = new WebGPUTextureUtils( this );
  24171. this.occludedResolveCache = new Map();
  24172. }
  24173. async init( renderer ) {
  24174. await super.init( renderer );
  24175. //
  24176. const parameters = this.parameters;
  24177. // create the device if it is not passed with parameters
  24178. let device;
  24179. if ( parameters.device === undefined ) {
  24180. const adapterOptions = {
  24181. powerPreference: parameters.powerPreference
  24182. };
  24183. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  24184. if ( adapter === null ) {
  24185. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  24186. }
  24187. // feature support
  24188. const features = Object.values( GPUFeatureName );
  24189. const supportedFeatures = [];
  24190. for ( const name of features ) {
  24191. if ( adapter.features.has( name ) ) {
  24192. supportedFeatures.push( name );
  24193. }
  24194. }
  24195. const deviceDescriptor = {
  24196. requiredFeatures: supportedFeatures,
  24197. requiredLimits: parameters.requiredLimits
  24198. };
  24199. device = await adapter.requestDevice( deviceDescriptor );
  24200. } else {
  24201. device = parameters.device;
  24202. }
  24203. device.lost.then( ( info ) => {
  24204. const deviceLossInfo = {
  24205. api: 'WebGPU',
  24206. message: info.message || 'Unknown reason',
  24207. reason: info.reason || null,
  24208. originalEvent: info
  24209. };
  24210. renderer.onDeviceLost( deviceLossInfo );
  24211. } );
  24212. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  24213. this.device = device;
  24214. this.context = context;
  24215. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  24216. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  24217. this.context.configure( {
  24218. device: this.device,
  24219. format: this.utils.getPreferredCanvasFormat(),
  24220. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  24221. alphaMode: alphaMode
  24222. } );
  24223. this.updateSize();
  24224. }
  24225. get coordinateSystem() {
  24226. return WebGPUCoordinateSystem;
  24227. }
  24228. async getArrayBufferAsync( attribute ) {
  24229. return await this.attributeUtils.getArrayBufferAsync( attribute );
  24230. }
  24231. getContext() {
  24232. return this.context;
  24233. }
  24234. _getDefaultRenderPassDescriptor() {
  24235. let descriptor = this.defaultRenderPassdescriptor;
  24236. if ( descriptor === null ) {
  24237. const renderer = this.renderer;
  24238. descriptor = {
  24239. colorAttachments: [ {
  24240. view: null
  24241. } ],
  24242. };
  24243. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  24244. descriptor.depthStencilAttachment = {
  24245. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  24246. };
  24247. }
  24248. const colorAttachment = descriptor.colorAttachments[ 0 ];
  24249. if ( this.renderer.samples > 0 ) {
  24250. colorAttachment.view = this.colorBuffer.createView();
  24251. } else {
  24252. colorAttachment.resolveTarget = undefined;
  24253. }
  24254. this.defaultRenderPassdescriptor = descriptor;
  24255. }
  24256. const colorAttachment = descriptor.colorAttachments[ 0 ];
  24257. if ( this.renderer.samples > 0 ) {
  24258. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  24259. } else {
  24260. colorAttachment.view = this.context.getCurrentTexture().createView();
  24261. }
  24262. return descriptor;
  24263. }
  24264. _getRenderPassDescriptor( renderContext ) {
  24265. const renderTarget = renderContext.renderTarget;
  24266. const renderTargetData = this.get( renderTarget );
  24267. let descriptors = renderTargetData.descriptors;
  24268. if ( descriptors === undefined ||
  24269. renderTargetData.width !== renderTarget.width ||
  24270. renderTargetData.height !== renderTarget.height ||
  24271. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  24272. renderTargetData.samples !== renderTarget.samples
  24273. ) {
  24274. descriptors = {};
  24275. renderTargetData.descriptors = descriptors;
  24276. // dispose
  24277. const onDispose = () => {
  24278. renderTarget.removeEventListener( 'dispose', onDispose );
  24279. this.delete( renderTarget );
  24280. };
  24281. renderTarget.addEventListener( 'dispose', onDispose );
  24282. }
  24283. const cacheKey = renderContext.getCacheKey();
  24284. let descriptor = descriptors[ cacheKey ];
  24285. if ( descriptor === undefined ) {
  24286. const textures = renderContext.textures;
  24287. const colorAttachments = [];
  24288. for ( let i = 0; i < textures.length; i ++ ) {
  24289. const textureData = this.get( textures[ i ] );
  24290. const textureView = textureData.texture.createView( {
  24291. baseMipLevel: renderContext.activeMipmapLevel,
  24292. mipLevelCount: 1,
  24293. baseArrayLayer: renderContext.activeCubeFace,
  24294. dimension: GPUTextureViewDimension.TwoD
  24295. } );
  24296. let view, resolveTarget;
  24297. if ( textureData.msaaTexture !== undefined ) {
  24298. view = textureData.msaaTexture.createView();
  24299. resolveTarget = textureView;
  24300. } else {
  24301. view = textureView;
  24302. resolveTarget = undefined;
  24303. }
  24304. colorAttachments.push( {
  24305. view,
  24306. resolveTarget,
  24307. loadOp: GPULoadOp.Load,
  24308. storeOp: GPUStoreOp.Store
  24309. } );
  24310. }
  24311. descriptor = {
  24312. colorAttachments,
  24313. };
  24314. if ( renderContext.depth ) {
  24315. const depthTextureData = this.get( renderContext.depthTexture );
  24316. const depthStencilAttachment = {
  24317. view: depthTextureData.texture.createView()
  24318. };
  24319. descriptor.depthStencilAttachment = depthStencilAttachment;
  24320. }
  24321. descriptors[ cacheKey ] = descriptor;
  24322. renderTargetData.width = renderTarget.width;
  24323. renderTargetData.height = renderTarget.height;
  24324. renderTargetData.samples = renderTarget.samples;
  24325. renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel;
  24326. }
  24327. return descriptor;
  24328. }
  24329. beginRender( renderContext ) {
  24330. const renderContextData = this.get( renderContext );
  24331. const device = this.device;
  24332. const occlusionQueryCount = renderContext.occlusionQueryCount;
  24333. let occlusionQuerySet;
  24334. if ( occlusionQueryCount > 0 ) {
  24335. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  24336. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  24337. // Get a reference to the array of objects with queries. The renderContextData property
  24338. // can be changed by another render pass before the buffer.mapAsyc() completes.
  24339. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  24340. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  24341. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  24342. //
  24343. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  24344. renderContextData.occlusionQuerySet = occlusionQuerySet;
  24345. renderContextData.occlusionQueryIndex = 0;
  24346. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  24347. renderContextData.lastOcclusionObject = null;
  24348. }
  24349. let descriptor;
  24350. if ( renderContext.textures === null ) {
  24351. descriptor = this._getDefaultRenderPassDescriptor();
  24352. } else {
  24353. descriptor = this._getRenderPassDescriptor( renderContext );
  24354. }
  24355. this.initTimestampQuery( renderContext, descriptor );
  24356. descriptor.occlusionQuerySet = occlusionQuerySet;
  24357. const depthStencilAttachment = descriptor.depthStencilAttachment;
  24358. if ( renderContext.textures !== null ) {
  24359. const colorAttachments = descriptor.colorAttachments;
  24360. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  24361. const colorAttachment = colorAttachments[ i ];
  24362. if ( renderContext.clearColor ) {
  24363. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  24364. colorAttachment.loadOp = GPULoadOp.Clear;
  24365. colorAttachment.storeOp = GPUStoreOp.Store;
  24366. } else {
  24367. colorAttachment.loadOp = GPULoadOp.Load;
  24368. colorAttachment.storeOp = GPUStoreOp.Store;
  24369. }
  24370. }
  24371. } else {
  24372. const colorAttachment = descriptor.colorAttachments[ 0 ];
  24373. if ( renderContext.clearColor ) {
  24374. colorAttachment.clearValue = renderContext.clearColorValue;
  24375. colorAttachment.loadOp = GPULoadOp.Clear;
  24376. colorAttachment.storeOp = GPUStoreOp.Store;
  24377. } else {
  24378. colorAttachment.loadOp = GPULoadOp.Load;
  24379. colorAttachment.storeOp = GPUStoreOp.Store;
  24380. }
  24381. }
  24382. //
  24383. if ( renderContext.depth ) {
  24384. if ( renderContext.clearDepth ) {
  24385. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  24386. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  24387. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  24388. } else {
  24389. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  24390. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  24391. }
  24392. }
  24393. if ( renderContext.stencil ) {
  24394. if ( renderContext.clearStencil ) {
  24395. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  24396. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  24397. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  24398. } else {
  24399. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  24400. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  24401. }
  24402. }
  24403. //
  24404. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  24405. const currentPass = encoder.beginRenderPass( descriptor );
  24406. //
  24407. renderContextData.descriptor = descriptor;
  24408. renderContextData.encoder = encoder;
  24409. renderContextData.currentPass = currentPass;
  24410. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  24411. renderContextData.renderBundles = [];
  24412. //
  24413. if ( renderContext.viewport ) {
  24414. this.updateViewport( renderContext );
  24415. }
  24416. if ( renderContext.scissor ) {
  24417. const { x, y, width, height } = renderContext.scissorValue;
  24418. currentPass.setScissorRect( x, y, width, height );
  24419. }
  24420. }
  24421. finishRender( renderContext ) {
  24422. const renderContextData = this.get( renderContext );
  24423. const occlusionQueryCount = renderContext.occlusionQueryCount;
  24424. if ( renderContextData.renderBundles.length > 0 ) {
  24425. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  24426. }
  24427. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  24428. renderContextData.currentPass.endOcclusionQuery();
  24429. }
  24430. renderContextData.currentPass.end();
  24431. if ( occlusionQueryCount > 0 ) {
  24432. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  24433. //
  24434. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  24435. if ( queryResolveBuffer === undefined ) {
  24436. queryResolveBuffer = this.device.createBuffer(
  24437. {
  24438. size: bufferSize,
  24439. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  24440. }
  24441. );
  24442. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  24443. }
  24444. //
  24445. const readBuffer = this.device.createBuffer(
  24446. {
  24447. size: bufferSize,
  24448. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  24449. }
  24450. );
  24451. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  24452. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  24453. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  24454. renderContextData.occlusionQueryBuffer = readBuffer;
  24455. //
  24456. this.resolveOccludedAsync( renderContext );
  24457. }
  24458. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  24459. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  24460. //
  24461. if ( renderContext.textures !== null ) {
  24462. const textures = renderContext.textures;
  24463. for ( let i = 0; i < textures.length; i ++ ) {
  24464. const texture = textures[ i ];
  24465. if ( texture.generateMipmaps === true ) {
  24466. this.textureUtils.generateMipmaps( texture );
  24467. }
  24468. }
  24469. }
  24470. }
  24471. isOccluded( renderContext, object ) {
  24472. const renderContextData = this.get( renderContext );
  24473. return renderContextData.occluded && renderContextData.occluded.has( object );
  24474. }
  24475. async resolveOccludedAsync( renderContext ) {
  24476. const renderContextData = this.get( renderContext );
  24477. // handle occlusion query results
  24478. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  24479. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  24480. const occluded = new WeakSet();
  24481. renderContextData.currentOcclusionQueryObjects = null;
  24482. renderContextData.currentOcclusionQueryBuffer = null;
  24483. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  24484. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  24485. const results = new BigUint64Array( buffer );
  24486. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  24487. if ( results[ i ] !== BigInt( 0 ) ) {
  24488. occluded.add( currentOcclusionQueryObjects[ i ] );
  24489. }
  24490. }
  24491. currentOcclusionQueryBuffer.destroy();
  24492. renderContextData.occluded = occluded;
  24493. }
  24494. }
  24495. updateViewport( renderContext ) {
  24496. const { currentPass } = this.get( renderContext );
  24497. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  24498. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  24499. }
  24500. clear( color, depth, stencil, renderTargetData = null ) {
  24501. const device = this.device;
  24502. const renderer = this.renderer;
  24503. let colorAttachments = [];
  24504. let depthStencilAttachment;
  24505. let clearValue;
  24506. let supportsDepth;
  24507. let supportsStencil;
  24508. if ( color ) {
  24509. const clearColor = this.getClearColor();
  24510. if ( this.renderer.alpha === true ) {
  24511. // premultiply alpha
  24512. const a = clearColor.a;
  24513. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  24514. } else {
  24515. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  24516. }
  24517. }
  24518. if ( renderTargetData === null ) {
  24519. supportsDepth = renderer.depth;
  24520. supportsStencil = renderer.stencil;
  24521. const descriptor = this._getDefaultRenderPassDescriptor();
  24522. if ( color ) {
  24523. colorAttachments = descriptor.colorAttachments;
  24524. const colorAttachment = colorAttachments[ 0 ];
  24525. colorAttachment.clearValue = clearValue;
  24526. colorAttachment.loadOp = GPULoadOp.Clear;
  24527. colorAttachment.storeOp = GPUStoreOp.Store;
  24528. }
  24529. if ( supportsDepth || supportsStencil ) {
  24530. depthStencilAttachment = descriptor.depthStencilAttachment;
  24531. }
  24532. } else {
  24533. supportsDepth = renderTargetData.depth;
  24534. supportsStencil = renderTargetData.stencil;
  24535. if ( color ) {
  24536. for ( const texture of renderTargetData.textures ) {
  24537. const textureData = this.get( texture );
  24538. const textureView = textureData.texture.createView();
  24539. let view, resolveTarget;
  24540. if ( textureData.msaaTexture !== undefined ) {
  24541. view = textureData.msaaTexture.createView();
  24542. resolveTarget = textureView;
  24543. } else {
  24544. view = textureView;
  24545. resolveTarget = undefined;
  24546. }
  24547. colorAttachments.push( {
  24548. view,
  24549. resolveTarget,
  24550. clearValue,
  24551. loadOp: GPULoadOp.Clear,
  24552. storeOp: GPUStoreOp.Store
  24553. } );
  24554. }
  24555. }
  24556. if ( supportsDepth || supportsStencil ) {
  24557. const depthTextureData = this.get( renderTargetData.depthTexture );
  24558. depthStencilAttachment = {
  24559. view: depthTextureData.texture.createView()
  24560. };
  24561. }
  24562. }
  24563. //
  24564. if ( supportsDepth ) {
  24565. if ( depth ) {
  24566. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  24567. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  24568. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  24569. } else {
  24570. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  24571. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  24572. }
  24573. }
  24574. //
  24575. if ( supportsStencil ) {
  24576. if ( stencil ) {
  24577. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  24578. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  24579. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  24580. } else {
  24581. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  24582. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  24583. }
  24584. }
  24585. //
  24586. const encoder = device.createCommandEncoder( {} );
  24587. const currentPass = encoder.beginRenderPass( {
  24588. colorAttachments,
  24589. depthStencilAttachment
  24590. } );
  24591. currentPass.end();
  24592. device.queue.submit( [ encoder.finish() ] );
  24593. }
  24594. // compute
  24595. beginCompute( computeGroup ) {
  24596. const groupGPU = this.get( computeGroup );
  24597. const descriptor = {};
  24598. this.initTimestampQuery( computeGroup, descriptor );
  24599. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  24600. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  24601. }
  24602. compute( computeGroup, computeNode, bindings, pipeline ) {
  24603. const { passEncoderGPU } = this.get( computeGroup );
  24604. // pipeline
  24605. const pipelineGPU = this.get( pipeline ).pipeline;
  24606. passEncoderGPU.setPipeline( pipelineGPU );
  24607. // bind groups
  24608. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  24609. const bindGroup = bindings[ i ];
  24610. const bindingsData = this.get( bindGroup );
  24611. passEncoderGPU.setBindGroup( i, bindingsData.group );
  24612. }
  24613. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  24614. const computeNodeData = this.get( computeNode );
  24615. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  24616. const { dispatchSize } = computeNodeData;
  24617. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  24618. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  24619. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  24620. } else {
  24621. dispatchSize.x = computeNode.dispatchCount;
  24622. }
  24623. passEncoderGPU.dispatchWorkgroups(
  24624. dispatchSize.x,
  24625. dispatchSize.y,
  24626. dispatchSize.z
  24627. );
  24628. }
  24629. finishCompute( computeGroup ) {
  24630. const groupData = this.get( computeGroup );
  24631. groupData.passEncoderGPU.end();
  24632. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  24633. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  24634. }
  24635. async waitForGPU() {
  24636. await this.device.queue.onSubmittedWorkDone();
  24637. }
  24638. // render object
  24639. draw( renderObject, info ) {
  24640. const { object, context, pipeline } = renderObject;
  24641. const bindings = renderObject.getBindings();
  24642. const renderContextData = this.get( context );
  24643. const pipelineGPU = this.get( pipeline ).pipeline;
  24644. const currentSets = renderContextData.currentSets;
  24645. const passEncoderGPU = renderContextData.currentPass;
  24646. const drawParams = renderObject.getDrawParameters();
  24647. if ( drawParams === null ) return;
  24648. // pipeline
  24649. if ( currentSets.pipeline !== pipelineGPU ) {
  24650. passEncoderGPU.setPipeline( pipelineGPU );
  24651. currentSets.pipeline = pipelineGPU;
  24652. }
  24653. // bind groups
  24654. const currentBindingGroups = currentSets.bindingGroups;
  24655. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  24656. const bindGroup = bindings[ i ];
  24657. const bindingsData = this.get( bindGroup );
  24658. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  24659. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  24660. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  24661. }
  24662. }
  24663. // attributes
  24664. const index = renderObject.getIndex();
  24665. const hasIndex = ( index !== null );
  24666. // index
  24667. if ( hasIndex === true ) {
  24668. if ( currentSets.index !== index ) {
  24669. const buffer = this.get( index ).buffer;
  24670. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  24671. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  24672. currentSets.index = index;
  24673. }
  24674. }
  24675. // vertex buffers
  24676. const vertexBuffers = renderObject.getVertexBuffers();
  24677. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  24678. const vertexBuffer = vertexBuffers[ i ];
  24679. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  24680. const buffer = this.get( vertexBuffer ).buffer;
  24681. passEncoderGPU.setVertexBuffer( i, buffer );
  24682. currentSets.attributes[ i ] = vertexBuffer;
  24683. }
  24684. }
  24685. // occlusion queries - handle multiple consecutive draw calls for an object
  24686. if ( renderContextData.occlusionQuerySet !== undefined ) {
  24687. const lastObject = renderContextData.lastOcclusionObject;
  24688. if ( lastObject !== object ) {
  24689. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  24690. passEncoderGPU.endOcclusionQuery();
  24691. renderContextData.occlusionQueryIndex ++;
  24692. }
  24693. if ( object.occlusionTest === true ) {
  24694. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  24695. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  24696. }
  24697. renderContextData.lastOcclusionObject = object;
  24698. }
  24699. }
  24700. // draw
  24701. if ( object.isBatchedMesh === true ) {
  24702. const starts = object._multiDrawStarts;
  24703. const counts = object._multiDrawCounts;
  24704. const drawCount = object._multiDrawCount;
  24705. const drawInstances = object._multiDrawInstances;
  24706. const bytesPerElement = hasIndex ? index.array.BYTES_PER_ELEMENT : 1;
  24707. for ( let i = 0; i < drawCount; i ++ ) {
  24708. const count = drawInstances ? drawInstances[ i ] : 1;
  24709. const firstInstance = count > 1 ? 0 : i;
  24710. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / bytesPerElement, 0, firstInstance );
  24711. }
  24712. } else if ( hasIndex === true ) {
  24713. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  24714. const indirect = renderObject.getIndirect();
  24715. if ( indirect !== null ) {
  24716. const buffer = this.get( indirect ).buffer;
  24717. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  24718. } else {
  24719. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  24720. }
  24721. info.update( object, indexCount, instanceCount );
  24722. } else {
  24723. const { vertexCount, instanceCount, firstVertex } = drawParams;
  24724. const indirect = renderObject.getIndirect();
  24725. if ( indirect !== null ) {
  24726. const buffer = this.get( indirect ).buffer;
  24727. passEncoderGPU.drawIndirect( buffer, 0 );
  24728. } else {
  24729. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  24730. }
  24731. info.update( object, vertexCount, instanceCount );
  24732. }
  24733. }
  24734. // cache key
  24735. needsRenderUpdate( renderObject ) {
  24736. const data = this.get( renderObject );
  24737. const { object, material } = renderObject;
  24738. const utils = this.utils;
  24739. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  24740. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  24741. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  24742. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  24743. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  24744. let needsUpdate = false;
  24745. if ( data.material !== material || data.materialVersion !== material.version ||
  24746. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  24747. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  24748. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  24749. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  24750. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  24751. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  24752. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  24753. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  24754. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  24755. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  24756. data.primitiveTopology !== primitiveTopology ||
  24757. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  24758. ) {
  24759. data.material = material; data.materialVersion = material.version;
  24760. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  24761. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  24762. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  24763. data.colorWrite = material.colorWrite;
  24764. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  24765. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  24766. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  24767. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  24768. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  24769. data.sampleCount = sampleCount;
  24770. data.colorSpace = colorSpace;
  24771. data.colorFormat = colorFormat;
  24772. data.depthStencilFormat = depthStencilFormat;
  24773. data.primitiveTopology = primitiveTopology;
  24774. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  24775. needsUpdate = true;
  24776. }
  24777. return needsUpdate;
  24778. }
  24779. getRenderCacheKey( renderObject ) {
  24780. const { object, material } = renderObject;
  24781. const utils = this.utils;
  24782. const renderContext = renderObject.context;
  24783. return [
  24784. material.transparent, material.blending, material.premultipliedAlpha,
  24785. material.blendSrc, material.blendDst, material.blendEquation,
  24786. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  24787. material.colorWrite,
  24788. material.depthWrite, material.depthTest, material.depthFunc,
  24789. material.stencilWrite, material.stencilFunc,
  24790. material.stencilFail, material.stencilZFail, material.stencilZPass,
  24791. material.stencilFuncMask, material.stencilWriteMask,
  24792. material.side,
  24793. utils.getSampleCountRenderContext( renderContext ),
  24794. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  24795. utils.getPrimitiveTopology( object, material ),
  24796. renderObject.getGeometryCacheKey(),
  24797. renderObject.clippingContextCacheKey
  24798. ].join();
  24799. }
  24800. // textures
  24801. createSampler( texture ) {
  24802. this.textureUtils.createSampler( texture );
  24803. }
  24804. destroySampler( texture ) {
  24805. this.textureUtils.destroySampler( texture );
  24806. }
  24807. createDefaultTexture( texture ) {
  24808. this.textureUtils.createDefaultTexture( texture );
  24809. }
  24810. createTexture( texture, options ) {
  24811. this.textureUtils.createTexture( texture, options );
  24812. }
  24813. updateTexture( texture, options ) {
  24814. this.textureUtils.updateTexture( texture, options );
  24815. }
  24816. generateMipmaps( texture ) {
  24817. this.textureUtils.generateMipmaps( texture );
  24818. }
  24819. destroyTexture( texture ) {
  24820. this.textureUtils.destroyTexture( texture );
  24821. }
  24822. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  24823. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  24824. }
  24825. initTimestampQuery( renderContext, descriptor ) {
  24826. if ( ! this.trackTimestamp ) return;
  24827. const renderContextData = this.get( renderContext );
  24828. if ( ! renderContextData.timeStampQuerySet ) {
  24829. const type = renderContext.isComputeNode ? 'compute' : 'render';
  24830. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2, label: `timestamp_${type}_${renderContext.id}` } );
  24831. const timestampWrites = {
  24832. querySet: timeStampQuerySet,
  24833. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  24834. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  24835. };
  24836. Object.assign( descriptor, { timestampWrites } );
  24837. renderContextData.timeStampQuerySet = timeStampQuerySet;
  24838. }
  24839. }
  24840. // timestamp utils
  24841. prepareTimestampBuffer( renderContext, encoder ) {
  24842. if ( ! this.trackTimestamp ) return;
  24843. const renderContextData = this.get( renderContext );
  24844. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  24845. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  24846. renderContextData.currentTimestampQueryBuffers = {
  24847. resolveBuffer: this.device.createBuffer( {
  24848. label: 'timestamp resolve buffer',
  24849. size: size,
  24850. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  24851. } ),
  24852. resultBuffer: this.device.createBuffer( {
  24853. label: 'timestamp result buffer',
  24854. size: size,
  24855. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  24856. } )
  24857. };
  24858. }
  24859. const { resolveBuffer, resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  24860. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  24861. if ( resultBuffer.mapState === 'unmapped' ) {
  24862. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  24863. }
  24864. }
  24865. async resolveTimestampAsync( renderContext, type = 'render' ) {
  24866. if ( ! this.trackTimestamp ) return;
  24867. const renderContextData = this.get( renderContext );
  24868. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  24869. const { resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  24870. await this.device.queue.onSubmittedWorkDone();
  24871. if ( resultBuffer.mapState === 'unmapped' ) {
  24872. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  24873. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  24874. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  24875. this.renderer.info.updateTimestamp( type, duration );
  24876. resultBuffer.unmap();
  24877. } );
  24878. }
  24879. }
  24880. // node builder
  24881. createNodeBuilder( object, renderer ) {
  24882. return new WGSLNodeBuilder( object, renderer );
  24883. }
  24884. // program
  24885. createProgram( program ) {
  24886. const programGPU = this.get( program );
  24887. programGPU.module = {
  24888. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  24889. entryPoint: 'main'
  24890. };
  24891. }
  24892. destroyProgram( program ) {
  24893. this.delete( program );
  24894. }
  24895. // pipelines
  24896. createRenderPipeline( renderObject, promises ) {
  24897. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  24898. }
  24899. createComputePipeline( computePipeline, bindings ) {
  24900. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  24901. }
  24902. beginBundle( renderContext ) {
  24903. const renderContextData = this.get( renderContext );
  24904. renderContextData._currentPass = renderContextData.currentPass;
  24905. renderContextData._currentSets = renderContextData.currentSets;
  24906. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  24907. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  24908. }
  24909. finishBundle( renderContext, bundle ) {
  24910. const renderContextData = this.get( renderContext );
  24911. const bundleEncoder = renderContextData.currentPass;
  24912. const bundleGPU = bundleEncoder.finish();
  24913. this.get( bundle ).bundleGPU = bundleGPU;
  24914. // restore render pass state
  24915. renderContextData.currentSets = renderContextData._currentSets;
  24916. renderContextData.currentPass = renderContextData._currentPass;
  24917. }
  24918. addBundle( renderContext, bundle ) {
  24919. const renderContextData = this.get( renderContext );
  24920. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  24921. }
  24922. // bindings
  24923. createBindings( bindGroup, bindings, cacheIndex, version ) {
  24924. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  24925. }
  24926. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  24927. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  24928. }
  24929. updateBinding( binding ) {
  24930. this.bindingUtils.updateBinding( binding );
  24931. }
  24932. // attributes
  24933. createIndexAttribute( attribute ) {
  24934. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  24935. }
  24936. createAttribute( attribute ) {
  24937. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  24938. }
  24939. createStorageAttribute( attribute ) {
  24940. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  24941. }
  24942. createIndirectStorageAttribute( attribute ) {
  24943. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  24944. }
  24945. updateAttribute( attribute ) {
  24946. this.attributeUtils.updateAttribute( attribute );
  24947. }
  24948. destroyAttribute( attribute ) {
  24949. this.attributeUtils.destroyAttribute( attribute );
  24950. }
  24951. // canvas
  24952. updateSize() {
  24953. this.colorBuffer = this.textureUtils.getColorBuffer();
  24954. this.defaultRenderPassdescriptor = null;
  24955. }
  24956. // utils public
  24957. getMaxAnisotropy() {
  24958. return 16;
  24959. }
  24960. hasFeature( name ) {
  24961. return this.device.features.has( name );
  24962. }
  24963. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  24964. let dstX = 0;
  24965. let dstY = 0;
  24966. let dstLayer = 0;
  24967. let srcX = 0;
  24968. let srcY = 0;
  24969. let srcLayer = 0;
  24970. let srcWidth = srcTexture.image.width;
  24971. let srcHeight = srcTexture.image.height;
  24972. if ( srcRegion !== null ) {
  24973. srcX = srcRegion.x;
  24974. srcY = srcRegion.y;
  24975. srcLayer = srcRegion.z || 0;
  24976. srcWidth = srcRegion.width;
  24977. srcHeight = srcRegion.height;
  24978. }
  24979. if ( dstPosition !== null ) {
  24980. dstX = dstPosition.x;
  24981. dstY = dstPosition.y;
  24982. dstLayer = dstPosition.z || 0;
  24983. }
  24984. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  24985. const sourceGPU = this.get( srcTexture ).texture;
  24986. const destinationGPU = this.get( dstTexture ).texture;
  24987. encoder.copyTextureToTexture(
  24988. {
  24989. texture: sourceGPU,
  24990. mipLevel: level,
  24991. origin: { x: srcX, y: srcY, z: srcLayer }
  24992. },
  24993. {
  24994. texture: destinationGPU,
  24995. mipLevel: level,
  24996. origin: { x: dstX, y: dstY, z: dstLayer }
  24997. },
  24998. [
  24999. srcWidth,
  25000. srcHeight,
  25001. 1
  25002. ]
  25003. );
  25004. this.device.queue.submit( [ encoder.finish() ] );
  25005. }
  25006. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  25007. const renderContextData = this.get( renderContext );
  25008. let sourceGPU = null;
  25009. if ( renderContext.renderTarget ) {
  25010. if ( texture.isDepthTexture ) {
  25011. sourceGPU = this.get( renderContext.depthTexture ).texture;
  25012. } else {
  25013. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  25014. }
  25015. } else {
  25016. if ( texture.isDepthTexture ) {
  25017. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  25018. } else {
  25019. sourceGPU = this.context.getCurrentTexture();
  25020. }
  25021. }
  25022. const destinationGPU = this.get( texture ).texture;
  25023. if ( sourceGPU.format !== destinationGPU.format ) {
  25024. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  25025. return;
  25026. }
  25027. let encoder;
  25028. if ( renderContextData.currentPass ) {
  25029. renderContextData.currentPass.end();
  25030. encoder = renderContextData.encoder;
  25031. } else {
  25032. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  25033. }
  25034. encoder.copyTextureToTexture(
  25035. {
  25036. texture: sourceGPU,
  25037. origin: [ rectangle.x, rectangle.y, 0 ],
  25038. },
  25039. {
  25040. texture: destinationGPU
  25041. },
  25042. [
  25043. rectangle.z,
  25044. rectangle.w
  25045. ]
  25046. );
  25047. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  25048. if ( renderContextData.currentPass ) {
  25049. const { descriptor } = renderContextData;
  25050. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  25051. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  25052. }
  25053. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  25054. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  25055. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  25056. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  25057. if ( renderContext.viewport ) {
  25058. this.updateViewport( renderContext );
  25059. }
  25060. if ( renderContext.scissor ) {
  25061. const { x, y, width, height } = renderContext.scissorValue;
  25062. renderContextData.currentPass.setScissorRect( x, y, width, height );
  25063. }
  25064. } else {
  25065. this.device.queue.submit( [ encoder.finish() ] );
  25066. }
  25067. }
  25068. }
  25069. class IESSpotLight extends SpotLight {
  25070. constructor( color, intensity, distance, angle, penumbra, decay ) {
  25071. super( color, intensity, distance, angle, penumbra, decay );
  25072. this.iesMap = null;
  25073. }
  25074. copy( source, recursive ) {
  25075. super.copy( source, recursive );
  25076. this.iesMap = source.iesMap;
  25077. return this;
  25078. }
  25079. }
  25080. class BasicNodeLibrary extends NodeLibrary {
  25081. constructor() {
  25082. super();
  25083. this.addLight( PointLightNode, PointLight );
  25084. this.addLight( DirectionalLightNode, DirectionalLight );
  25085. this.addLight( RectAreaLightNode, RectAreaLight );
  25086. this.addLight( SpotLightNode, SpotLight );
  25087. this.addLight( AmbientLightNode, AmbientLight );
  25088. this.addLight( HemisphereLightNode, HemisphereLight );
  25089. this.addLight( LightProbeNode, LightProbe );
  25090. this.addLight( IESSpotLightNode, IESSpotLight );
  25091. this.addToneMapping( linearToneMapping, LinearToneMapping );
  25092. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  25093. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  25094. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  25095. this.addToneMapping( agxToneMapping, AgXToneMapping );
  25096. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  25097. }
  25098. }
  25099. class WebGPURenderer extends Renderer {
  25100. constructor( parameters = {} ) {
  25101. let BackendClass;
  25102. if ( parameters.forceWebGL ) {
  25103. BackendClass = WebGLBackend;
  25104. } else {
  25105. BackendClass = WebGPUBackend;
  25106. parameters.getFallback = () => {
  25107. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  25108. return new WebGLBackend( parameters );
  25109. };
  25110. }
  25111. const backend = new BackendClass( parameters );
  25112. super( backend, parameters );
  25113. this.library = new BasicNodeLibrary();
  25114. this.isWebGPURenderer = true;
  25115. }
  25116. }
  25117. class BundleGroup extends Group {
  25118. constructor() {
  25119. super();
  25120. this.isBundleGroup = true;
  25121. this.type = 'BundleGroup';
  25122. this.static = true;
  25123. this.version = 0;
  25124. }
  25125. set needsUpdate( value ) {
  25126. if ( value === true ) this.version ++;
  25127. }
  25128. }
  25129. const _material = /*@__PURE__*/ new NodeMaterial();
  25130. const _quadMesh = /*@__PURE__*/ new QuadMesh( _material );
  25131. class PostProcessing {
  25132. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  25133. this.renderer = renderer;
  25134. this.outputNode = outputNode;
  25135. this.outputColorTransform = true;
  25136. this.needsUpdate = true;
  25137. _material.name = 'PostProcessing';
  25138. }
  25139. render() {
  25140. this.update();
  25141. const renderer = this.renderer;
  25142. const toneMapping = renderer.toneMapping;
  25143. const outputColorSpace = renderer.outputColorSpace;
  25144. renderer.toneMapping = NoToneMapping;
  25145. renderer.outputColorSpace = LinearSRGBColorSpace;
  25146. //
  25147. _quadMesh.render( renderer );
  25148. //
  25149. renderer.toneMapping = toneMapping;
  25150. renderer.outputColorSpace = outputColorSpace;
  25151. }
  25152. update() {
  25153. if ( this.needsUpdate === true ) {
  25154. const renderer = this.renderer;
  25155. const toneMapping = renderer.toneMapping;
  25156. const outputColorSpace = renderer.outputColorSpace;
  25157. _quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  25158. _quadMesh.material.needsUpdate = true;
  25159. this.needsUpdate = false;
  25160. }
  25161. }
  25162. async renderAsync() {
  25163. this.update();
  25164. const renderer = this.renderer;
  25165. const toneMapping = renderer.toneMapping;
  25166. const outputColorSpace = renderer.outputColorSpace;
  25167. renderer.toneMapping = NoToneMapping;
  25168. renderer.outputColorSpace = LinearSRGBColorSpace;
  25169. //
  25170. await _quadMesh.renderAsync( renderer );
  25171. //
  25172. renderer.toneMapping = toneMapping;
  25173. renderer.outputColorSpace = outputColorSpace;
  25174. }
  25175. }
  25176. // renderer state
  25177. function saveRendererState( renderer, state = {} ) {
  25178. state.toneMapping = renderer.toneMapping;
  25179. state.toneMappingExposure = renderer.toneMappingExposure;
  25180. state.outputColorSpace = renderer.outputColorSpace;
  25181. state.renderTarget = renderer.getRenderTarget();
  25182. state.activeCubeFace = renderer.getActiveCubeFace();
  25183. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  25184. state.renderObjectFunction = renderer.getRenderObjectFunction();
  25185. state.pixelRatio = renderer.getPixelRatio();
  25186. state.mrt = renderer.getMRT();
  25187. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  25188. state.clearAlpha = renderer.getClearAlpha();
  25189. state.autoClear = renderer.autoClear;
  25190. state.scissorTest = renderer.getScissorTest();
  25191. return state;
  25192. }
  25193. function resetRendererState( renderer, state ) {
  25194. state = saveRendererState( renderer, state );
  25195. renderer.setMRT( null );
  25196. renderer.setRenderObjectFunction( null );
  25197. renderer.setClearColor( 0x000000, 1 );
  25198. renderer.autoClear = true;
  25199. return state;
  25200. }
  25201. function restoreRendererState( renderer, state ) {
  25202. renderer.toneMapping = state.toneMapping;
  25203. renderer.toneMappingExposure = state.toneMappingExposure;
  25204. renderer.outputColorSpace = state.outputColorSpace;
  25205. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  25206. renderer.setRenderObjectFunction( state.renderObjectFunction );
  25207. renderer.setPixelRatio( state.pixelRatio );
  25208. renderer.setMRT( state.mrt );
  25209. renderer.setClearColor( state.clearColor, state.clearAlpha );
  25210. renderer.autoClear = state.autoClear;
  25211. renderer.setScissorTest( state.scissorTest );
  25212. }
  25213. // renderer and scene state
  25214. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  25215. state = saveRendererState( renderer, state );
  25216. state.background = scene.background;
  25217. state.backgroundNode = scene.backgroundNode;
  25218. state.overrideMaterial = scene.overrideMaterial;
  25219. return state;
  25220. }
  25221. function resetRendererAndSceneState( renderer, scene, state ) {
  25222. state = saveRendererAndSceneState( renderer, scene, state );
  25223. scene.background = null;
  25224. scene.backgroundNode = null;
  25225. scene.overrideMaterial = null;
  25226. return state;
  25227. }
  25228. function restoreRendererAndSceneState( renderer, scene, state ) {
  25229. restoreRendererState( renderer, state );
  25230. scene.background = state.background;
  25231. scene.backgroundNode = state.backgroundNode;
  25232. scene.overrideMaterial = state.overrideMaterial;
  25233. }
  25234. var PostProcessingUtils = /*#__PURE__*/Object.freeze({
  25235. __proto__: null,
  25236. resetRendererAndSceneState: resetRendererAndSceneState,
  25237. resetRendererState: resetRendererState,
  25238. restoreRendererAndSceneState: restoreRendererAndSceneState,
  25239. restoreRendererState: restoreRendererState,
  25240. saveRendererAndSceneState: saveRendererAndSceneState,
  25241. saveRendererState: saveRendererState
  25242. });
  25243. class StorageTexture extends Texture {
  25244. constructor( width = 1, height = 1 ) {
  25245. super();
  25246. this.image = { width, height };
  25247. this.magFilter = LinearFilter;
  25248. this.minFilter = LinearFilter;
  25249. this.isStorageTexture = true;
  25250. }
  25251. }
  25252. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  25253. constructor( array, itemSize ) {
  25254. super( array, itemSize, Uint32Array );
  25255. this.isIndirectStorageBufferAttribute = true;
  25256. }
  25257. }
  25258. class NodeLoader extends Loader {
  25259. constructor( manager ) {
  25260. super( manager );
  25261. this.textures = {};
  25262. this.nodes = {};
  25263. }
  25264. load( url, onLoad, onProgress, onError ) {
  25265. const loader = new FileLoader( this.manager );
  25266. loader.setPath( this.path );
  25267. loader.setRequestHeader( this.requestHeader );
  25268. loader.setWithCredentials( this.withCredentials );
  25269. loader.load( url, ( text ) => {
  25270. try {
  25271. onLoad( this.parse( JSON.parse( text ) ) );
  25272. } catch ( e ) {
  25273. if ( onError ) {
  25274. onError( e );
  25275. } else {
  25276. console.error( e );
  25277. }
  25278. this.manager.itemError( url );
  25279. }
  25280. }, onProgress, onError );
  25281. }
  25282. parseNodes( json ) {
  25283. const nodes = {};
  25284. if ( json !== undefined ) {
  25285. for ( const nodeJSON of json ) {
  25286. const { uuid, type } = nodeJSON;
  25287. nodes[ uuid ] = this.createNodeFromType( type );
  25288. nodes[ uuid ].uuid = uuid;
  25289. }
  25290. const meta = { nodes, textures: this.textures };
  25291. for ( const nodeJSON of json ) {
  25292. nodeJSON.meta = meta;
  25293. const node = nodes[ nodeJSON.uuid ];
  25294. node.deserialize( nodeJSON );
  25295. delete nodeJSON.meta;
  25296. }
  25297. }
  25298. return nodes;
  25299. }
  25300. parse( json ) {
  25301. const node = this.createNodeFromType( json.type );
  25302. node.uuid = json.uuid;
  25303. const nodes = this.parseNodes( json.nodes );
  25304. const meta = { nodes, textures: this.textures };
  25305. json.meta = meta;
  25306. node.deserialize( json );
  25307. delete json.meta;
  25308. return node;
  25309. }
  25310. setTextures( value ) {
  25311. this.textures = value;
  25312. return this;
  25313. }
  25314. setNodes( value ) {
  25315. this.nodes = value;
  25316. return this;
  25317. }
  25318. createNodeFromType( type ) {
  25319. if ( this.nodes[ type ] === undefined ) {
  25320. console.error( 'THREE.NodeLoader: Node type not found:', type );
  25321. return float();
  25322. }
  25323. return nodeObject( new this.nodes[ type ]() );
  25324. }
  25325. }
  25326. class NodeMaterialLoader extends MaterialLoader {
  25327. constructor( manager ) {
  25328. super( manager );
  25329. this.nodes = {};
  25330. this.nodeMaterials = {};
  25331. }
  25332. parse( json ) {
  25333. const material = super.parse( json );
  25334. const nodes = this.nodes;
  25335. const inputNodes = json.inputNodes;
  25336. for ( const property in inputNodes ) {
  25337. const uuid = inputNodes[ property ];
  25338. material[ property ] = nodes[ uuid ];
  25339. }
  25340. return material;
  25341. }
  25342. setNodes( value ) {
  25343. this.nodes = value;
  25344. return this;
  25345. }
  25346. setNodeMaterials( value ) {
  25347. this.nodeMaterials = value;
  25348. return this;
  25349. }
  25350. createMaterialFromType( type ) {
  25351. const materialClass = this.nodeMaterials[ type ];
  25352. if ( materialClass !== undefined ) {
  25353. return new materialClass();
  25354. }
  25355. return super.createMaterialFromType( type );
  25356. }
  25357. }
  25358. class NodeObjectLoader extends ObjectLoader {
  25359. constructor( manager ) {
  25360. super( manager );
  25361. this.nodes = {};
  25362. this.nodeMaterials = {};
  25363. this._nodesJSON = null;
  25364. }
  25365. setNodes( value ) {
  25366. this.nodes = value;
  25367. return this;
  25368. }
  25369. setNodeMaterials( value ) {
  25370. this.nodeMaterials = value;
  25371. return this;
  25372. }
  25373. parse( json, onLoad ) {
  25374. this._nodesJSON = json.nodes;
  25375. const data = super.parse( json, onLoad );
  25376. this._nodesJSON = null; // dispose
  25377. return data;
  25378. }
  25379. parseNodes( json, textures ) {
  25380. if ( json !== undefined ) {
  25381. const loader = new NodeLoader();
  25382. loader.setNodes( this.nodes );
  25383. loader.setTextures( textures );
  25384. return loader.parseNodes( json );
  25385. }
  25386. return {};
  25387. }
  25388. parseMaterials( json, textures ) {
  25389. const materials = {};
  25390. if ( json !== undefined ) {
  25391. const nodes = this.parseNodes( this._nodesJSON, textures );
  25392. const loader = new NodeMaterialLoader();
  25393. loader.setTextures( textures );
  25394. loader.setNodes( nodes );
  25395. loader.setNodeMaterials( this.nodeMaterials );
  25396. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25397. const data = json[ i ];
  25398. materials[ data.uuid ] = loader.parse( data );
  25399. }
  25400. }
  25401. return materials;
  25402. }
  25403. }
  25404. class ClippingGroup extends Group {
  25405. constructor() {
  25406. super();
  25407. this.isClippingGroup = true;
  25408. this.clippingPlanes = [];
  25409. this.enabled = true;
  25410. this.clipIntersection = false;
  25411. this.clipShadows = false;
  25412. }
  25413. }
  25414. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayElementNode, AssignNode, AttributeNode, BackSide, BasicEnvironmentNode, BasicShadowMap, BatchNode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, CacheNode, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, CodeNode, Color, ColorManagement, ColorSpaceNode, ComputeNode, ConstNode, ContextNode, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, DataArrayTexture, DataTexture, DecrementStencilOp, DecrementWrapStencilOp, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, FogExp2Node, FogNode, FogRangeNode, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, Group, HalfFloatType, HemisphereLight, HemisphereLightNode, IESSpotLight, IESSpotLightNode, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InstanceNode, InstancedBufferAttribute, InstancedInterleavedBuffer, InstancedMeshNode, InstancedPointsNodeMaterial, IntType, InterleavedBuffer, InterleavedBufferAttribute, InvertStencilOp, IrradianceNode, JoinNode, KeepStencilOp, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, LightProbe, LightProbeNode, Lighting, LightingContextNode, LightingModel, LightingNode, LightsNode, Line2NodeMaterial, LineBasicMaterial, LineBasicNodeMaterial, LineDashedMaterial, LineDashedNodeMaterial, LinearFilter, LinearMipMapLinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, Loader, LoopNode, LuminanceAlphaFormat, LuminanceFormat, MRTNode, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, ModelViewProjectionNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAccess, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap, PMREMGenerator, PMREMNode, ParameterNode, PassNode, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PointLight, PointLightNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, PostProcessingUtils, PosterizeNode, PropertyNode, QuadMesh, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBFormat, RGBIntegerFormat, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, ShortType, SkinningNode, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticDrawUsage, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TriplanarTexturesNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, shaderStages, vectorComponents };
粤ICP备19079148号