three.webgpu.js 957 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417
  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 lightPosition( light ) {
  11630. const data = getLightData( light );
  11631. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  11632. }
  11633. function lightTargetPosition( light ) {
  11634. const data = getLightData( light );
  11635. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  11636. }
  11637. function lightViewPosition( light ) {
  11638. const data = getLightData( light );
  11639. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  11640. self.value = self.value || new Vector3();
  11641. self.value.setFromMatrixPosition( light.matrixWorld );
  11642. self.value.applyMatrix4( camera.matrixWorldInverse );
  11643. } ) );
  11644. }
  11645. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  11646. const sortLights = ( lights ) => {
  11647. return lights.sort( ( a, b ) => a.id - b.id );
  11648. };
  11649. const getLightNodeById = ( id, lightNodes ) => {
  11650. for ( const lightNode of lightNodes ) {
  11651. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  11652. return lightNode;
  11653. }
  11654. }
  11655. return null;
  11656. };
  11657. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  11658. class LightsNode extends Node {
  11659. static get type() {
  11660. return 'LightsNode';
  11661. }
  11662. constructor() {
  11663. super( 'vec3' );
  11664. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  11665. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  11666. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  11667. this._lights = [];
  11668. this._lightNodes = null;
  11669. this._lightNodesHash = null;
  11670. this.global = true;
  11671. }
  11672. getHash( builder ) {
  11673. if ( this._lightNodesHash === null ) {
  11674. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  11675. const hash = [];
  11676. for ( const lightNode of this._lightNodes ) {
  11677. hash.push( lightNode.getSelf().getHash() );
  11678. }
  11679. this._lightNodesHash = 'lights-' + hash.join( ',' );
  11680. }
  11681. return this._lightNodesHash;
  11682. }
  11683. analyze( builder ) {
  11684. const properties = builder.getDataFromNode( this );
  11685. for ( const node of properties.nodes ) {
  11686. node.build( builder );
  11687. }
  11688. }
  11689. setupLightsNode( builder ) {
  11690. const lightNodes = [];
  11691. const previousLightNodes = this._lightNodes;
  11692. const lights = sortLights( this._lights );
  11693. const nodeLibrary = builder.renderer.library;
  11694. for ( const light of lights ) {
  11695. if ( light.isNode ) {
  11696. lightNodes.push( nodeObject( light ) );
  11697. } else {
  11698. let lightNode = null;
  11699. if ( previousLightNodes !== null ) {
  11700. lightNode = getLightNodeById( light.id, previousLightNodes ); // resuse existing light node
  11701. }
  11702. if ( lightNode === null ) {
  11703. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  11704. if ( lightNodeClass === null ) {
  11705. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  11706. continue;
  11707. }
  11708. let lightNode = null;
  11709. if ( ! _lightsNodeRef.has( light ) ) {
  11710. lightNode = nodeObject( new lightNodeClass( light ) );
  11711. _lightsNodeRef.set( light, lightNode );
  11712. } else {
  11713. lightNode = _lightsNodeRef.get( light );
  11714. }
  11715. lightNodes.push( lightNode );
  11716. }
  11717. }
  11718. }
  11719. this._lightNodes = lightNodes;
  11720. }
  11721. setupLights( builder, lightNodes ) {
  11722. for ( const lightNode of lightNodes ) {
  11723. lightNode.build( builder );
  11724. }
  11725. }
  11726. setup( builder ) {
  11727. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  11728. const context = builder.context;
  11729. const lightingModel = context.lightingModel;
  11730. let outgoingLightNode = this.outgoingLightNode;
  11731. if ( lightingModel ) {
  11732. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  11733. context.outgoingLight = outgoingLightNode;
  11734. const stack = builder.addStack();
  11735. //
  11736. const properties = builder.getDataFromNode( this );
  11737. properties.nodes = stack.nodes;
  11738. //
  11739. lightingModel.start( context, stack, builder );
  11740. // lights
  11741. this.setupLights( builder, _lightNodes );
  11742. //
  11743. lightingModel.indirect( context, stack, builder );
  11744. //
  11745. const { backdrop, backdropAlpha } = context;
  11746. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  11747. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  11748. if ( backdrop !== null ) {
  11749. if ( backdropAlpha !== null ) {
  11750. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  11751. } else {
  11752. totalDiffuse = vec3( backdrop );
  11753. }
  11754. context.material.transparent = true;
  11755. }
  11756. totalDiffuseNode.assign( totalDiffuse );
  11757. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  11758. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  11759. //
  11760. lightingModel.finish( context, stack, builder );
  11761. //
  11762. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  11763. }
  11764. return outgoingLightNode;
  11765. }
  11766. setLights( lights ) {
  11767. this._lights = lights;
  11768. this._lightNodes = null;
  11769. this._lightNodesHash = null;
  11770. return this;
  11771. }
  11772. getLights() {
  11773. return this._lights;
  11774. }
  11775. get hasLights() {
  11776. return this._lights.length > 0;
  11777. }
  11778. }
  11779. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  11780. const shadowWorldPosition = /*@__PURE__*/ vec3().toVar( 'shadowWorldPosition' );
  11781. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  11782. let dist = positionWorld.sub( position ).length();
  11783. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  11784. dist = dist.saturate(); // clamp to [ 0, 1 ]
  11785. return dist;
  11786. } );
  11787. const linearShadowDistance = ( light ) => {
  11788. const camera = light.shadow.camera;
  11789. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  11790. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  11791. const referencePosition = objectPosition( light );
  11792. return linearDistance( referencePosition, nearDistance, farDistance );
  11793. };
  11794. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  11795. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  11796. } );
  11797. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  11798. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  11799. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  11800. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  11801. const texelSize = vec2( 1 ).div( mapSize );
  11802. const dx0 = texelSize.x.negate().mul( radius );
  11803. const dy0 = texelSize.y.negate().mul( radius );
  11804. const dx1 = texelSize.x.mul( radius );
  11805. const dy1 = texelSize.y.mul( radius );
  11806. const dx2 = dx0.div( 2 );
  11807. const dy2 = dy0.div( 2 );
  11808. const dx3 = dx1.div( 2 );
  11809. const dy3 = dy1.div( 2 );
  11810. return add(
  11811. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  11812. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  11813. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  11814. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  11815. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  11816. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  11817. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  11818. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  11819. depthCompare( shadowCoord.xy, shadowCoord.z ),
  11820. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  11821. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  11822. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  11823. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  11824. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  11825. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  11826. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  11827. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  11828. ).mul( 1 / 17 );
  11829. } );
  11830. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  11831. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  11832. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  11833. const texelSize = vec2( 1 ).div( mapSize );
  11834. const dx = texelSize.x;
  11835. const dy = texelSize.y;
  11836. const uv = shadowCoord.xy;
  11837. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  11838. uv.subAssign( f.mul( texelSize ) );
  11839. return add(
  11840. depthCompare( uv, shadowCoord.z ),
  11841. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  11842. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  11843. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  11844. mix(
  11845. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  11846. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  11847. f.x
  11848. ),
  11849. mix(
  11850. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  11851. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  11852. f.x
  11853. ),
  11854. mix(
  11855. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  11856. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  11857. f.y
  11858. ),
  11859. mix(
  11860. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  11861. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  11862. f.y
  11863. ),
  11864. mix(
  11865. mix(
  11866. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  11867. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  11868. f.x
  11869. ),
  11870. mix(
  11871. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  11872. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  11873. f.x
  11874. ),
  11875. f.y
  11876. )
  11877. ).mul( 1 / 9 );
  11878. } );
  11879. // VSM
  11880. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  11881. const occlusion = float( 1 ).toVar();
  11882. const distribution = texture( depthTexture ).uv( shadowCoord.xy ).rg;
  11883. const hardShadow = step( shadowCoord.z, distribution.x );
  11884. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  11885. const distance = shadowCoord.z.sub( distribution.x );
  11886. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  11887. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  11888. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  11889. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  11890. } );
  11891. return occlusion;
  11892. } );
  11893. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  11894. const mean = float( 0 ).toVar();
  11895. const squaredMean = float( 0 ).toVar();
  11896. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  11897. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  11898. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  11899. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  11900. const depth = shadowPass.uv( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  11901. mean.addAssign( depth );
  11902. squaredMean.addAssign( depth.mul( depth ) );
  11903. } );
  11904. mean.divAssign( samples );
  11905. squaredMean.divAssign( samples );
  11906. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  11907. return vec2( mean, std_dev );
  11908. } );
  11909. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  11910. const mean = float( 0 ).toVar();
  11911. const squaredMean = float( 0 ).toVar();
  11912. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  11913. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  11914. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  11915. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  11916. const distribution = shadowPass.uv( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  11917. mean.addAssign( distribution.x );
  11918. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  11919. } );
  11920. mean.divAssign( samples );
  11921. squaredMean.divAssign( samples );
  11922. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  11923. return vec2( mean, std_dev );
  11924. } );
  11925. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  11926. //
  11927. let _overrideMaterial = null;
  11928. const _quadMesh$1 = /*@__PURE__*/ new QuadMesh();
  11929. class ShadowNode extends Node {
  11930. static get type() {
  11931. return 'ShadowNode';
  11932. }
  11933. constructor( light, shadow = null ) {
  11934. super();
  11935. this.light = light;
  11936. this.shadow = shadow || light.shadow;
  11937. this.shadowMap = null;
  11938. this.vsmShadowMapVertical = null;
  11939. this.vsmShadowMapHorizontal = null;
  11940. this.vsmMaterialVertical = null;
  11941. this.vsmMaterialHorizontal = null;
  11942. this.updateBeforeType = NodeUpdateType.RENDER;
  11943. this._node = null;
  11944. this.isShadowNode = true;
  11945. }
  11946. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  11947. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  11948. .and( shadowCoord.x.lessThanEqual( 1 ) )
  11949. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  11950. .and( shadowCoord.y.lessThanEqual( 1 ) )
  11951. .and( shadowCoord.z.lessThanEqual( 1 ) );
  11952. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow } );
  11953. return frustumTest.select( shadowNode, float( 1 ) );
  11954. }
  11955. setupShadowCoord( builder, shadowPosition ) {
  11956. const { shadow } = this;
  11957. const { renderer } = builder;
  11958. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  11959. let shadowCoord = shadowPosition;
  11960. let coordZ;
  11961. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  11962. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  11963. coordZ = shadowCoord.z;
  11964. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  11965. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  11966. }
  11967. } else {
  11968. const w = shadowCoord.w;
  11969. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  11970. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  11971. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  11972. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  11973. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  11974. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  11975. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  11976. }
  11977. shadowCoord = vec3(
  11978. shadowCoord.x,
  11979. shadowCoord.y.oneMinus(), // follow webgpu standards
  11980. coordZ.add( bias )
  11981. );
  11982. return shadowCoord;
  11983. }
  11984. getShadowFilterFn( type ) {
  11985. return _shadowFilterLib[ type ];
  11986. }
  11987. setupShadow( builder ) {
  11988. const { renderer } = builder;
  11989. const { light, shadow } = this;
  11990. const shadowMapType = renderer.shadowMap.type;
  11991. if ( _overrideMaterial === null ) {
  11992. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  11993. _overrideMaterial = new NodeMaterial();
  11994. _overrideMaterial.fragmentNode = vec4( 0, 0, 0, 1 );
  11995. _overrideMaterial.depthNode = depthNode;
  11996. _overrideMaterial.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.fragmentNode unintentionally when using material.shadowNode
  11997. _overrideMaterial.name = 'ShadowMaterial';
  11998. }
  11999. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  12000. depthTexture.compareFunction = LessCompare;
  12001. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  12002. shadowMap.depthTexture = depthTexture;
  12003. shadow.camera.updateProjectionMatrix();
  12004. // VSM
  12005. if ( shadowMapType === VSMShadowMap ) {
  12006. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  12007. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  12008. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  12009. const shadowPassVertical = texture( depthTexture );
  12010. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  12011. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  12012. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  12013. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  12014. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  12015. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  12016. material.name = 'VSMVertical';
  12017. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  12018. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  12019. material.name = 'VSMHorizontal';
  12020. }
  12021. //
  12022. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  12023. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  12024. const shadowPosition = uniform( shadow.matrix ).setGroup( renderGroup ).mul( shadowWorldPosition.add( transformedNormalWorld.mul( normalBias ) ) );
  12025. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  12026. //
  12027. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  12028. if ( filterFn === null ) {
  12029. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  12030. }
  12031. const shadowDepthTexture = ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  12032. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow } );
  12033. const shadowColor = texture( shadowMap.texture, shadowCoord );
  12034. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  12035. this.shadowMap = shadowMap;
  12036. this.shadow.map = shadowMap;
  12037. return shadowOutput;
  12038. }
  12039. setup( builder ) {
  12040. if ( builder.renderer.shadowMap.enabled === false ) return;
  12041. return Fn( ( { material } ) => {
  12042. shadowWorldPosition.assign( material.shadowPositionNode || positionWorld );
  12043. let node = this._node;
  12044. if ( node === null ) {
  12045. this._node = node = this.setupShadow( builder );
  12046. }
  12047. if ( builder.material.shadowNode ) { // @deprecated, r171
  12048. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  12049. }
  12050. if ( builder.material.receivedShadowNode ) {
  12051. node = builder.material.receivedShadowNode( node );
  12052. }
  12053. return node;
  12054. } )();
  12055. }
  12056. renderShadow( frame ) {
  12057. const { shadow, shadowMap, light } = this;
  12058. const { renderer, scene } = frame;
  12059. shadow.updateMatrices( light );
  12060. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  12061. renderer.render( scene, shadow.camera );
  12062. }
  12063. updateShadow( frame ) {
  12064. const { shadowMap, light, shadow } = this;
  12065. const { renderer, scene, camera } = frame;
  12066. const shadowType = renderer.shadowMap.type;
  12067. const depthVersion = shadowMap.depthTexture.version;
  12068. this._depthVersionCached = depthVersion;
  12069. const currentOverrideMaterial = scene.overrideMaterial;
  12070. scene.overrideMaterial = _overrideMaterial;
  12071. shadow.camera.layers.mask = camera.layers.mask;
  12072. const currentRenderTarget = renderer.getRenderTarget();
  12073. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  12074. renderer.setRenderObjectFunction( ( object, ...params ) => {
  12075. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  12076. renderer.renderObject( object, ...params );
  12077. }
  12078. } );
  12079. renderer.setRenderTarget( shadowMap );
  12080. this.renderShadow( frame );
  12081. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  12082. // vsm blur pass
  12083. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  12084. this.vsmPass( renderer );
  12085. }
  12086. renderer.setRenderTarget( currentRenderTarget );
  12087. scene.overrideMaterial = currentOverrideMaterial;
  12088. }
  12089. vsmPass( renderer ) {
  12090. const { shadow } = this;
  12091. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  12092. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  12093. renderer.setRenderTarget( this.vsmShadowMapVertical );
  12094. _quadMesh$1.material = this.vsmMaterialVertical;
  12095. _quadMesh$1.render( renderer );
  12096. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  12097. _quadMesh$1.material = this.vsmMaterialHorizontal;
  12098. _quadMesh$1.render( renderer );
  12099. }
  12100. dispose() {
  12101. this.shadowMap.dispose();
  12102. this.shadowMap = null;
  12103. if ( this.vsmShadowMapVertical !== null ) {
  12104. this.vsmShadowMapVertical.dispose();
  12105. this.vsmShadowMapVertical = null;
  12106. this.vsmMaterialVertical.dispose();
  12107. this.vsmMaterialVertical = null;
  12108. }
  12109. if ( this.vsmShadowMapHorizontal !== null ) {
  12110. this.vsmShadowMapHorizontal.dispose();
  12111. this.vsmShadowMapHorizontal = null;
  12112. this.vsmMaterialHorizontal.dispose();
  12113. this.vsmMaterialHorizontal = null;
  12114. }
  12115. this.updateBeforeType = NodeUpdateType.NONE;
  12116. }
  12117. updateBefore( frame ) {
  12118. const { shadow } = this;
  12119. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  12120. if ( needsUpdate ) {
  12121. this.updateShadow( frame );
  12122. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  12123. shadow.needsUpdate = false;
  12124. }
  12125. }
  12126. }
  12127. }
  12128. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  12129. class AnalyticLightNode extends LightingNode {
  12130. static get type() {
  12131. return 'AnalyticLightNode';
  12132. }
  12133. constructor( light = null ) {
  12134. super();
  12135. this.updateType = NodeUpdateType.FRAME;
  12136. this.light = light;
  12137. this.color = new Color();
  12138. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  12139. this.baseColorNode = null;
  12140. this.shadowNode = null;
  12141. this.shadowColorNode = null;
  12142. this.isAnalyticLightNode = true;
  12143. }
  12144. getCacheKey() {
  12145. return hash$1( super.getCacheKey(), this.light.id, this.light.castShadow ? 1 : 0 );
  12146. }
  12147. getHash() {
  12148. return this.light.uuid;
  12149. }
  12150. setupShadowNode() {
  12151. return shadow( this.light );
  12152. }
  12153. setupShadow( builder ) {
  12154. const { renderer } = builder;
  12155. if ( renderer.shadowMap.enabled === false ) return;
  12156. let shadowColorNode = this.shadowColorNode;
  12157. if ( shadowColorNode === null ) {
  12158. const customShadowNode = this.light.shadow.shadowNode;
  12159. let shadowNode;
  12160. if ( customShadowNode !== undefined ) {
  12161. shadowNode = nodeObject( customShadowNode );
  12162. } else {
  12163. shadowNode = this.setupShadowNode( builder );
  12164. }
  12165. this.shadowNode = shadowNode;
  12166. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  12167. this.baseColorNode = this.colorNode;
  12168. }
  12169. //
  12170. this.colorNode = shadowColorNode;
  12171. }
  12172. setup( builder ) {
  12173. this.colorNode = this.baseColorNode || this.colorNode;
  12174. if ( this.light.castShadow ) {
  12175. if ( builder.object.receiveShadow ) {
  12176. this.setupShadow( builder );
  12177. }
  12178. } else if ( this.shadowNode !== null ) {
  12179. this.shadowNode.dispose();
  12180. this.shadowNode = null;
  12181. this.shadowColorNode = null;
  12182. }
  12183. }
  12184. update( /*frame*/ ) {
  12185. const { light } = this;
  12186. this.color.copy( light.color ).multiplyScalar( light.intensity );
  12187. }
  12188. }
  12189. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  12190. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  12191. // based upon Frostbite 3 Moving to Physically-based Rendering
  12192. // page 32, equation 26: E[window1]
  12193. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  12194. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  12195. return cutoffDistance.greaterThan( 0 ).select(
  12196. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  12197. distanceFalloff
  12198. );
  12199. } ); // validated
  12200. const _clearColor$2 = /*@__PURE__*/ new Color();
  12201. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  12202. // vector suitable for 2D texture mapping. This code uses the following layout for the
  12203. // 2D texture:
  12204. //
  12205. // xzXZ
  12206. // y Y
  12207. //
  12208. // Y - Positive y direction
  12209. // y - Negative y direction
  12210. // X - Positive x direction
  12211. // x - Negative x direction
  12212. // Z - Positive z direction
  12213. // z - Negative z direction
  12214. //
  12215. // Source and test bed:
  12216. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  12217. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  12218. const v = pos.toVar();
  12219. // Number of texels to avoid at the edge of each square
  12220. const absV = abs( v );
  12221. // Intersect unit cube
  12222. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  12223. absV.mulAssign( scaleToCube );
  12224. // Apply scale to avoid seams
  12225. // two texels less per square (one texel will do for NEAREST)
  12226. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  12227. // Unwrap
  12228. // space: -1 ... 1 range for each square
  12229. //
  12230. // #X## dim := ( 4 , 2 )
  12231. // # # center := ( 1 , 1 )
  12232. const planar = vec2( v.xy ).toVar();
  12233. const almostATexel = texelSizeY.mul( 1.5 );
  12234. const almostOne = almostATexel.oneMinus();
  12235. If( absV.z.greaterThanEqual( almostOne ), () => {
  12236. If( v.z.greaterThan( 0.0 ), () => {
  12237. planar.x.assign( sub( 4.0, v.x ) );
  12238. } );
  12239. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  12240. const signX = sign( v.x );
  12241. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  12242. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  12243. const signY = sign( v.y );
  12244. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  12245. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  12246. } );
  12247. // Transform to UV space
  12248. // scale := 0.5 / dim
  12249. // translate := ( center + 0.5 ) / dim
  12250. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  12251. } ).setLayout( {
  12252. name: 'cubeToUV',
  12253. type: 'vec2',
  12254. inputs: [
  12255. { name: 'pos', type: 'vec3' },
  12256. { name: 'texelSizeY', type: 'float' }
  12257. ]
  12258. } );
  12259. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  12260. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  12261. } );
  12262. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  12263. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  12264. const offset = vec2( - 1.0, 1.0 ).mul( radius ).mul( texelSize.y );
  12265. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  12266. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  12267. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  12268. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  12269. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  12270. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  12271. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  12272. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  12273. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  12274. .mul( 1.0 / 9.0 );
  12275. } );
  12276. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  12277. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  12278. // the vector from the light to the world-space position of the fragment.
  12279. const lightToPosition = shadowCoord.xyz.toVar();
  12280. const lightToPositionLength = lightToPosition.length();
  12281. const cameraNearLocal = uniform( 'float' ).onRenderUpdate( () => shadow.camera.near );
  12282. const cameraFarLocal = uniform( 'float' ).onRenderUpdate( () => shadow.camera.far );
  12283. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  12284. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  12285. const result = float( 1.0 ).toVar();
  12286. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  12287. // dp = normalized distance from light to fragment position
  12288. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  12289. dp.addAssign( bias );
  12290. // bd3D = base direction 3D
  12291. const bd3D = lightToPosition.normalize();
  12292. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  12293. // percentage-closer filtering
  12294. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  12295. } );
  12296. return result;
  12297. } );
  12298. const _viewport = /*@__PURE__*/ new Vector4();
  12299. const _viewportSize = /*@__PURE__*/ new Vector2();
  12300. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  12301. //
  12302. class PointShadowNode extends ShadowNode {
  12303. static get type() {
  12304. return 'PointShadowNode';
  12305. }
  12306. constructor( light, shadow = null ) {
  12307. super( light, shadow );
  12308. }
  12309. getShadowFilterFn( type ) {
  12310. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  12311. }
  12312. setupShadowCoord( builder, shadowPosition ) {
  12313. return shadowPosition;
  12314. }
  12315. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  12316. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  12317. }
  12318. renderShadow( frame ) {
  12319. const { shadow, shadowMap, light } = this;
  12320. const { renderer, scene } = frame;
  12321. const shadowFrameExtents = shadow.getFrameExtents();
  12322. _shadowMapSize.copy( shadow.mapSize );
  12323. _shadowMapSize.multiply( shadowFrameExtents );
  12324. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  12325. _viewportSize.copy( shadow.mapSize );
  12326. //
  12327. const previousAutoClear = renderer.autoClear;
  12328. const previousClearColor = renderer.getClearColor( _clearColor$2 );
  12329. const previousClearAlpha = renderer.getClearAlpha();
  12330. renderer.autoClear = false;
  12331. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  12332. renderer.clear();
  12333. const viewportCount = shadow.getViewportCount();
  12334. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  12335. const viewport = shadow.getViewport( vp );
  12336. const x = _viewportSize.x * viewport.x;
  12337. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  12338. _viewport.set(
  12339. x,
  12340. y,
  12341. _viewportSize.x * viewport.z,
  12342. _viewportSize.y * viewport.w
  12343. );
  12344. shadowMap.viewport.copy( _viewport );
  12345. shadow.updateMatrices( light, vp );
  12346. renderer.render( scene, shadow.camera );
  12347. }
  12348. //
  12349. renderer.autoClear = previousAutoClear;
  12350. renderer.setClearColor( previousClearColor, previousClearAlpha );
  12351. }
  12352. }
  12353. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  12354. const directPointLight = Fn( ( { color, lightViewPosition, cutoffDistance, decayExponent }, builder ) => {
  12355. const lightingModel = builder.context.lightingModel;
  12356. const lVector = lightViewPosition.sub( positionView ); // @TODO: Add it into LightNode
  12357. const lightDirection = lVector.normalize();
  12358. const lightDistance = lVector.length();
  12359. const lightAttenuation = getDistanceAttenuation( {
  12360. lightDistance,
  12361. cutoffDistance,
  12362. decayExponent
  12363. } );
  12364. const lightColor = color.mul( lightAttenuation );
  12365. const reflectedLight = builder.context.reflectedLight;
  12366. lightingModel.direct( {
  12367. lightDirection,
  12368. lightColor,
  12369. reflectedLight
  12370. }, builder.stack, builder );
  12371. } );
  12372. class PointLightNode extends AnalyticLightNode {
  12373. static get type() {
  12374. return 'PointLightNode';
  12375. }
  12376. constructor( light = null ) {
  12377. super( light );
  12378. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  12379. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  12380. }
  12381. update( frame ) {
  12382. const { light } = this;
  12383. super.update( frame );
  12384. this.cutoffDistanceNode.value = light.distance;
  12385. this.decayExponentNode.value = light.decay;
  12386. }
  12387. setupShadowNode() {
  12388. return pointShadow( this.light );
  12389. }
  12390. setup( builder ) {
  12391. super.setup( builder );
  12392. directPointLight( {
  12393. color: this.colorNode,
  12394. lightViewPosition: lightViewPosition( this.light ),
  12395. cutoffDistance: this.cutoffDistanceNode,
  12396. decayExponent: this.decayExponentNode
  12397. } ).append();
  12398. }
  12399. }
  12400. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  12401. const uv = coord.mul( 2.0 );
  12402. const cx = uv.x.floor();
  12403. const cy = uv.y.floor();
  12404. const result = cx.add( cy ).mod( 2.0 );
  12405. return result.sign();
  12406. } );
  12407. // Three.js Transpiler
  12408. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  12409. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  12410. const f = float( f_immutable ).toVar();
  12411. const t = float( t_immutable ).toVar();
  12412. const b = bool( b_immutable ).toVar();
  12413. return select( b, t, f );
  12414. } ).setLayout( {
  12415. name: 'mx_select',
  12416. type: 'float',
  12417. inputs: [
  12418. { name: 'b', type: 'bool' },
  12419. { name: 't', type: 'float' },
  12420. { name: 'f', type: 'float' }
  12421. ]
  12422. } );
  12423. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  12424. const b = bool( b_immutable ).toVar();
  12425. const val = float( val_immutable ).toVar();
  12426. return select( b, val.negate(), val );
  12427. } ).setLayout( {
  12428. name: 'mx_negate_if',
  12429. type: 'float',
  12430. inputs: [
  12431. { name: 'val', type: 'float' },
  12432. { name: 'b', type: 'bool' }
  12433. ]
  12434. } );
  12435. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  12436. const x = float( x_immutable ).toVar();
  12437. return int( floor( x ) );
  12438. } ).setLayout( {
  12439. name: 'mx_floor',
  12440. type: 'int',
  12441. inputs: [
  12442. { name: 'x', type: 'float' }
  12443. ]
  12444. } );
  12445. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  12446. const x = float( x_immutable ).toVar();
  12447. i.assign( mx_floor( x ) );
  12448. return x.sub( float( i ) );
  12449. } );
  12450. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  12451. const t = float( t_immutable ).toVar();
  12452. const s = float( s_immutable ).toVar();
  12453. const v3 = float( v3_immutable ).toVar();
  12454. const v2 = float( v2_immutable ).toVar();
  12455. const v1 = float( v1_immutable ).toVar();
  12456. const v0 = float( v0_immutable ).toVar();
  12457. const s1 = float( sub( 1.0, s ) ).toVar();
  12458. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  12459. } ).setLayout( {
  12460. name: 'mx_bilerp_0',
  12461. type: 'float',
  12462. inputs: [
  12463. { name: 'v0', type: 'float' },
  12464. { name: 'v1', type: 'float' },
  12465. { name: 'v2', type: 'float' },
  12466. { name: 'v3', type: 'float' },
  12467. { name: 's', type: 'float' },
  12468. { name: 't', type: 'float' }
  12469. ]
  12470. } );
  12471. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  12472. const t = float( t_immutable ).toVar();
  12473. const s = float( s_immutable ).toVar();
  12474. const v3 = vec3( v3_immutable ).toVar();
  12475. const v2 = vec3( v2_immutable ).toVar();
  12476. const v1 = vec3( v1_immutable ).toVar();
  12477. const v0 = vec3( v0_immutable ).toVar();
  12478. const s1 = float( sub( 1.0, s ) ).toVar();
  12479. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  12480. } ).setLayout( {
  12481. name: 'mx_bilerp_1',
  12482. type: 'vec3',
  12483. inputs: [
  12484. { name: 'v0', type: 'vec3' },
  12485. { name: 'v1', type: 'vec3' },
  12486. { name: 'v2', type: 'vec3' },
  12487. { name: 'v3', type: 'vec3' },
  12488. { name: 's', type: 'float' },
  12489. { name: 't', type: 'float' }
  12490. ]
  12491. } );
  12492. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  12493. 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 ] ) => {
  12494. const r = float( r_immutable ).toVar();
  12495. const t = float( t_immutable ).toVar();
  12496. const s = float( s_immutable ).toVar();
  12497. const v7 = float( v7_immutable ).toVar();
  12498. const v6 = float( v6_immutable ).toVar();
  12499. const v5 = float( v5_immutable ).toVar();
  12500. const v4 = float( v4_immutable ).toVar();
  12501. const v3 = float( v3_immutable ).toVar();
  12502. const v2 = float( v2_immutable ).toVar();
  12503. const v1 = float( v1_immutable ).toVar();
  12504. const v0 = float( v0_immutable ).toVar();
  12505. const s1 = float( sub( 1.0, s ) ).toVar();
  12506. const t1 = float( sub( 1.0, t ) ).toVar();
  12507. const r1 = float( sub( 1.0, r ) ).toVar();
  12508. 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 ) ) ) ) ) );
  12509. } ).setLayout( {
  12510. name: 'mx_trilerp_0',
  12511. type: 'float',
  12512. inputs: [
  12513. { name: 'v0', type: 'float' },
  12514. { name: 'v1', type: 'float' },
  12515. { name: 'v2', type: 'float' },
  12516. { name: 'v3', type: 'float' },
  12517. { name: 'v4', type: 'float' },
  12518. { name: 'v5', type: 'float' },
  12519. { name: 'v6', type: 'float' },
  12520. { name: 'v7', type: 'float' },
  12521. { name: 's', type: 'float' },
  12522. { name: 't', type: 'float' },
  12523. { name: 'r', type: 'float' }
  12524. ]
  12525. } );
  12526. 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 ] ) => {
  12527. const r = float( r_immutable ).toVar();
  12528. const t = float( t_immutable ).toVar();
  12529. const s = float( s_immutable ).toVar();
  12530. const v7 = vec3( v7_immutable ).toVar();
  12531. const v6 = vec3( v6_immutable ).toVar();
  12532. const v5 = vec3( v5_immutable ).toVar();
  12533. const v4 = vec3( v4_immutable ).toVar();
  12534. const v3 = vec3( v3_immutable ).toVar();
  12535. const v2 = vec3( v2_immutable ).toVar();
  12536. const v1 = vec3( v1_immutable ).toVar();
  12537. const v0 = vec3( v0_immutable ).toVar();
  12538. const s1 = float( sub( 1.0, s ) ).toVar();
  12539. const t1 = float( sub( 1.0, t ) ).toVar();
  12540. const r1 = float( sub( 1.0, r ) ).toVar();
  12541. 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 ) ) ) ) ) );
  12542. } ).setLayout( {
  12543. name: 'mx_trilerp_1',
  12544. type: 'vec3',
  12545. inputs: [
  12546. { name: 'v0', type: 'vec3' },
  12547. { name: 'v1', type: 'vec3' },
  12548. { name: 'v2', type: 'vec3' },
  12549. { name: 'v3', type: 'vec3' },
  12550. { name: 'v4', type: 'vec3' },
  12551. { name: 'v5', type: 'vec3' },
  12552. { name: 'v6', type: 'vec3' },
  12553. { name: 'v7', type: 'vec3' },
  12554. { name: 's', type: 'float' },
  12555. { name: 't', type: 'float' },
  12556. { name: 'r', type: 'float' }
  12557. ]
  12558. } );
  12559. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  12560. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  12561. const y = float( y_immutable ).toVar();
  12562. const x = float( x_immutable ).toVar();
  12563. const hash = uint( hash_immutable ).toVar();
  12564. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  12565. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  12566. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  12567. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  12568. } ).setLayout( {
  12569. name: 'mx_gradient_float_0',
  12570. type: 'float',
  12571. inputs: [
  12572. { name: 'hash', type: 'uint' },
  12573. { name: 'x', type: 'float' },
  12574. { name: 'y', type: 'float' }
  12575. ]
  12576. } );
  12577. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  12578. const z = float( z_immutable ).toVar();
  12579. const y = float( y_immutable ).toVar();
  12580. const x = float( x_immutable ).toVar();
  12581. const hash = uint( hash_immutable ).toVar();
  12582. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  12583. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  12584. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  12585. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  12586. } ).setLayout( {
  12587. name: 'mx_gradient_float_1',
  12588. type: 'float',
  12589. inputs: [
  12590. { name: 'hash', type: 'uint' },
  12591. { name: 'x', type: 'float' },
  12592. { name: 'y', type: 'float' },
  12593. { name: 'z', type: 'float' }
  12594. ]
  12595. } );
  12596. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  12597. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  12598. const y = float( y_immutable ).toVar();
  12599. const x = float( x_immutable ).toVar();
  12600. const hash = uvec3( hash_immutable ).toVar();
  12601. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  12602. } ).setLayout( {
  12603. name: 'mx_gradient_vec3_0',
  12604. type: 'vec3',
  12605. inputs: [
  12606. { name: 'hash', type: 'uvec3' },
  12607. { name: 'x', type: 'float' },
  12608. { name: 'y', type: 'float' }
  12609. ]
  12610. } );
  12611. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  12612. const z = float( z_immutable ).toVar();
  12613. const y = float( y_immutable ).toVar();
  12614. const x = float( x_immutable ).toVar();
  12615. const hash = uvec3( hash_immutable ).toVar();
  12616. 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 ) );
  12617. } ).setLayout( {
  12618. name: 'mx_gradient_vec3_1',
  12619. type: 'vec3',
  12620. inputs: [
  12621. { name: 'hash', type: 'uvec3' },
  12622. { name: 'x', type: 'float' },
  12623. { name: 'y', type: 'float' },
  12624. { name: 'z', type: 'float' }
  12625. ]
  12626. } );
  12627. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  12628. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  12629. const v = float( v_immutable ).toVar();
  12630. return mul( 0.6616, v );
  12631. } ).setLayout( {
  12632. name: 'mx_gradient_scale2d_0',
  12633. type: 'float',
  12634. inputs: [
  12635. { name: 'v', type: 'float' }
  12636. ]
  12637. } );
  12638. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  12639. const v = float( v_immutable ).toVar();
  12640. return mul( 0.9820, v );
  12641. } ).setLayout( {
  12642. name: 'mx_gradient_scale3d_0',
  12643. type: 'float',
  12644. inputs: [
  12645. { name: 'v', type: 'float' }
  12646. ]
  12647. } );
  12648. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  12649. const v = vec3( v_immutable ).toVar();
  12650. return mul( 0.6616, v );
  12651. } ).setLayout( {
  12652. name: 'mx_gradient_scale2d_1',
  12653. type: 'vec3',
  12654. inputs: [
  12655. { name: 'v', type: 'vec3' }
  12656. ]
  12657. } );
  12658. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  12659. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  12660. const v = vec3( v_immutable ).toVar();
  12661. return mul( 0.9820, v );
  12662. } ).setLayout( {
  12663. name: 'mx_gradient_scale3d_1',
  12664. type: 'vec3',
  12665. inputs: [
  12666. { name: 'v', type: 'vec3' }
  12667. ]
  12668. } );
  12669. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  12670. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  12671. const k = int( k_immutable ).toVar();
  12672. const x = uint( x_immutable ).toVar();
  12673. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  12674. } ).setLayout( {
  12675. name: 'mx_rotl32',
  12676. type: 'uint',
  12677. inputs: [
  12678. { name: 'x', type: 'uint' },
  12679. { name: 'k', type: 'int' }
  12680. ]
  12681. } );
  12682. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  12683. a.subAssign( c );
  12684. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  12685. c.addAssign( b );
  12686. b.subAssign( a );
  12687. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  12688. a.addAssign( c );
  12689. c.subAssign( b );
  12690. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  12691. b.addAssign( a );
  12692. a.subAssign( c );
  12693. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  12694. c.addAssign( b );
  12695. b.subAssign( a );
  12696. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  12697. a.addAssign( c );
  12698. c.subAssign( b );
  12699. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  12700. b.addAssign( a );
  12701. } );
  12702. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  12703. const c = uint( c_immutable ).toVar();
  12704. const b = uint( b_immutable ).toVar();
  12705. const a = uint( a_immutable ).toVar();
  12706. c.bitXorAssign( b );
  12707. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  12708. a.bitXorAssign( c );
  12709. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  12710. b.bitXorAssign( a );
  12711. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  12712. c.bitXorAssign( b );
  12713. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  12714. a.bitXorAssign( c );
  12715. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  12716. b.bitXorAssign( a );
  12717. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  12718. c.bitXorAssign( b );
  12719. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  12720. return c;
  12721. } ).setLayout( {
  12722. name: 'mx_bjfinal',
  12723. type: 'uint',
  12724. inputs: [
  12725. { name: 'a', type: 'uint' },
  12726. { name: 'b', type: 'uint' },
  12727. { name: 'c', type: 'uint' }
  12728. ]
  12729. } );
  12730. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  12731. const bits = uint( bits_immutable ).toVar();
  12732. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  12733. } ).setLayout( {
  12734. name: 'mx_bits_to_01',
  12735. type: 'float',
  12736. inputs: [
  12737. { name: 'bits', type: 'uint' }
  12738. ]
  12739. } );
  12740. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  12741. const t = float( t_immutable ).toVar();
  12742. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  12743. } ).setLayout( {
  12744. name: 'mx_fade',
  12745. type: 'float',
  12746. inputs: [
  12747. { name: 't', type: 'float' }
  12748. ]
  12749. } );
  12750. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  12751. const x = int( x_immutable ).toVar();
  12752. const len = uint( uint( 1 ) ).toVar();
  12753. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  12754. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  12755. } ).setLayout( {
  12756. name: 'mx_hash_int_0',
  12757. type: 'uint',
  12758. inputs: [
  12759. { name: 'x', type: 'int' }
  12760. ]
  12761. } );
  12762. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  12763. const y = int( y_immutable ).toVar();
  12764. const x = int( x_immutable ).toVar();
  12765. const len = uint( uint( 2 ) ).toVar();
  12766. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  12767. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  12768. a.addAssign( uint( x ) );
  12769. b.addAssign( uint( y ) );
  12770. return mx_bjfinal( a, b, c );
  12771. } ).setLayout( {
  12772. name: 'mx_hash_int_1',
  12773. type: 'uint',
  12774. inputs: [
  12775. { name: 'x', type: 'int' },
  12776. { name: 'y', type: 'int' }
  12777. ]
  12778. } );
  12779. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  12780. const z = int( z_immutable ).toVar();
  12781. const y = int( y_immutable ).toVar();
  12782. const x = int( x_immutable ).toVar();
  12783. const len = uint( uint( 3 ) ).toVar();
  12784. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  12785. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  12786. a.addAssign( uint( x ) );
  12787. b.addAssign( uint( y ) );
  12788. c.addAssign( uint( z ) );
  12789. return mx_bjfinal( a, b, c );
  12790. } ).setLayout( {
  12791. name: 'mx_hash_int_2',
  12792. type: 'uint',
  12793. inputs: [
  12794. { name: 'x', type: 'int' },
  12795. { name: 'y', type: 'int' },
  12796. { name: 'z', type: 'int' }
  12797. ]
  12798. } );
  12799. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  12800. const xx = int( xx_immutable ).toVar();
  12801. const z = int( z_immutable ).toVar();
  12802. const y = int( y_immutable ).toVar();
  12803. const x = int( x_immutable ).toVar();
  12804. const len = uint( uint( 4 ) ).toVar();
  12805. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  12806. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  12807. a.addAssign( uint( x ) );
  12808. b.addAssign( uint( y ) );
  12809. c.addAssign( uint( z ) );
  12810. mx_bjmix( a, b, c );
  12811. a.addAssign( uint( xx ) );
  12812. return mx_bjfinal( a, b, c );
  12813. } ).setLayout( {
  12814. name: 'mx_hash_int_3',
  12815. type: 'uint',
  12816. inputs: [
  12817. { name: 'x', type: 'int' },
  12818. { name: 'y', type: 'int' },
  12819. { name: 'z', type: 'int' },
  12820. { name: 'xx', type: 'int' }
  12821. ]
  12822. } );
  12823. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  12824. const yy = int( yy_immutable ).toVar();
  12825. const xx = int( xx_immutable ).toVar();
  12826. const z = int( z_immutable ).toVar();
  12827. const y = int( y_immutable ).toVar();
  12828. const x = int( x_immutable ).toVar();
  12829. const len = uint( uint( 5 ) ).toVar();
  12830. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  12831. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  12832. a.addAssign( uint( x ) );
  12833. b.addAssign( uint( y ) );
  12834. c.addAssign( uint( z ) );
  12835. mx_bjmix( a, b, c );
  12836. a.addAssign( uint( xx ) );
  12837. b.addAssign( uint( yy ) );
  12838. return mx_bjfinal( a, b, c );
  12839. } ).setLayout( {
  12840. name: 'mx_hash_int_4',
  12841. type: 'uint',
  12842. inputs: [
  12843. { name: 'x', type: 'int' },
  12844. { name: 'y', type: 'int' },
  12845. { name: 'z', type: 'int' },
  12846. { name: 'xx', type: 'int' },
  12847. { name: 'yy', type: 'int' }
  12848. ]
  12849. } );
  12850. 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 ] );
  12851. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  12852. const y = int( y_immutable ).toVar();
  12853. const x = int( x_immutable ).toVar();
  12854. const h = uint( mx_hash_int( x, y ) ).toVar();
  12855. const result = uvec3().toVar();
  12856. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  12857. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  12858. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  12859. return result;
  12860. } ).setLayout( {
  12861. name: 'mx_hash_vec3_0',
  12862. type: 'uvec3',
  12863. inputs: [
  12864. { name: 'x', type: 'int' },
  12865. { name: 'y', type: 'int' }
  12866. ]
  12867. } );
  12868. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  12869. const z = int( z_immutable ).toVar();
  12870. const y = int( y_immutable ).toVar();
  12871. const x = int( x_immutable ).toVar();
  12872. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  12873. const result = uvec3().toVar();
  12874. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  12875. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  12876. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  12877. return result;
  12878. } ).setLayout( {
  12879. name: 'mx_hash_vec3_1',
  12880. type: 'uvec3',
  12881. inputs: [
  12882. { name: 'x', type: 'int' },
  12883. { name: 'y', type: 'int' },
  12884. { name: 'z', type: 'int' }
  12885. ]
  12886. } );
  12887. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  12888. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12889. const p = vec2( p_immutable ).toVar();
  12890. const X = int().toVar(), Y = int().toVar();
  12891. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  12892. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  12893. const u = float( mx_fade( fx ) ).toVar();
  12894. const v = float( mx_fade( fy ) ).toVar();
  12895. 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();
  12896. return mx_gradient_scale2d( result );
  12897. } ).setLayout( {
  12898. name: 'mx_perlin_noise_float_0',
  12899. type: 'float',
  12900. inputs: [
  12901. { name: 'p', type: 'vec2' }
  12902. ]
  12903. } );
  12904. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12905. const p = vec3( p_immutable ).toVar();
  12906. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  12907. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  12908. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  12909. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  12910. const u = float( mx_fade( fx ) ).toVar();
  12911. const v = float( mx_fade( fy ) ).toVar();
  12912. const w = float( mx_fade( fz ) ).toVar();
  12913. 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();
  12914. return mx_gradient_scale3d( result );
  12915. } ).setLayout( {
  12916. name: 'mx_perlin_noise_float_1',
  12917. type: 'float',
  12918. inputs: [
  12919. { name: 'p', type: 'vec3' }
  12920. ]
  12921. } );
  12922. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  12923. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12924. const p = vec2( p_immutable ).toVar();
  12925. const X = int().toVar(), Y = int().toVar();
  12926. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  12927. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  12928. const u = float( mx_fade( fx ) ).toVar();
  12929. const v = float( mx_fade( fy ) ).toVar();
  12930. 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();
  12931. return mx_gradient_scale2d( result );
  12932. } ).setLayout( {
  12933. name: 'mx_perlin_noise_vec3_0',
  12934. type: 'vec3',
  12935. inputs: [
  12936. { name: 'p', type: 'vec2' }
  12937. ]
  12938. } );
  12939. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12940. const p = vec3( p_immutable ).toVar();
  12941. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  12942. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  12943. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  12944. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  12945. const u = float( mx_fade( fx ) ).toVar();
  12946. const v = float( mx_fade( fy ) ).toVar();
  12947. const w = float( mx_fade( fz ) ).toVar();
  12948. 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();
  12949. return mx_gradient_scale3d( result );
  12950. } ).setLayout( {
  12951. name: 'mx_perlin_noise_vec3_1',
  12952. type: 'vec3',
  12953. inputs: [
  12954. { name: 'p', type: 'vec3' }
  12955. ]
  12956. } );
  12957. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  12958. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12959. const p = float( p_immutable ).toVar();
  12960. const ix = int( mx_floor( p ) ).toVar();
  12961. return mx_bits_to_01( mx_hash_int( ix ) );
  12962. } ).setLayout( {
  12963. name: 'mx_cell_noise_float_0',
  12964. type: 'float',
  12965. inputs: [
  12966. { name: 'p', type: 'float' }
  12967. ]
  12968. } );
  12969. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12970. const p = vec2( p_immutable ).toVar();
  12971. const ix = int( mx_floor( p.x ) ).toVar();
  12972. const iy = int( mx_floor( p.y ) ).toVar();
  12973. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  12974. } ).setLayout( {
  12975. name: 'mx_cell_noise_float_1',
  12976. type: 'float',
  12977. inputs: [
  12978. { name: 'p', type: 'vec2' }
  12979. ]
  12980. } );
  12981. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12982. const p = vec3( p_immutable ).toVar();
  12983. const ix = int( mx_floor( p.x ) ).toVar();
  12984. const iy = int( mx_floor( p.y ) ).toVar();
  12985. const iz = int( mx_floor( p.z ) ).toVar();
  12986. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  12987. } ).setLayout( {
  12988. name: 'mx_cell_noise_float_2',
  12989. type: 'float',
  12990. inputs: [
  12991. { name: 'p', type: 'vec3' }
  12992. ]
  12993. } );
  12994. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12995. const p = vec4( p_immutable ).toVar();
  12996. const ix = int( mx_floor( p.x ) ).toVar();
  12997. const iy = int( mx_floor( p.y ) ).toVar();
  12998. const iz = int( mx_floor( p.z ) ).toVar();
  12999. const iw = int( mx_floor( p.w ) ).toVar();
  13000. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  13001. } ).setLayout( {
  13002. name: 'mx_cell_noise_float_3',
  13003. type: 'float',
  13004. inputs: [
  13005. { name: 'p', type: 'vec4' }
  13006. ]
  13007. } );
  13008. 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 ] );
  13009. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13010. const p = float( p_immutable ).toVar();
  13011. const ix = int( mx_floor( p ) ).toVar();
  13012. 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 ) ) ) );
  13013. } ).setLayout( {
  13014. name: 'mx_cell_noise_vec3_0',
  13015. type: 'vec3',
  13016. inputs: [
  13017. { name: 'p', type: 'float' }
  13018. ]
  13019. } );
  13020. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13021. const p = vec2( p_immutable ).toVar();
  13022. const ix = int( mx_floor( p.x ) ).toVar();
  13023. const iy = int( mx_floor( p.y ) ).toVar();
  13024. 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 ) ) ) );
  13025. } ).setLayout( {
  13026. name: 'mx_cell_noise_vec3_1',
  13027. type: 'vec3',
  13028. inputs: [
  13029. { name: 'p', type: 'vec2' }
  13030. ]
  13031. } );
  13032. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13033. const p = vec3( p_immutable ).toVar();
  13034. const ix = int( mx_floor( p.x ) ).toVar();
  13035. const iy = int( mx_floor( p.y ) ).toVar();
  13036. const iz = int( mx_floor( p.z ) ).toVar();
  13037. 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 ) ) ) );
  13038. } ).setLayout( {
  13039. name: 'mx_cell_noise_vec3_2',
  13040. type: 'vec3',
  13041. inputs: [
  13042. { name: 'p', type: 'vec3' }
  13043. ]
  13044. } );
  13045. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  13046. const p = vec4( p_immutable ).toVar();
  13047. const ix = int( mx_floor( p.x ) ).toVar();
  13048. const iy = int( mx_floor( p.y ) ).toVar();
  13049. const iz = int( mx_floor( p.z ) ).toVar();
  13050. const iw = int( mx_floor( p.w ) ).toVar();
  13051. 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 ) ) ) );
  13052. } ).setLayout( {
  13053. name: 'mx_cell_noise_vec3_3',
  13054. type: 'vec3',
  13055. inputs: [
  13056. { name: 'p', type: 'vec4' }
  13057. ]
  13058. } );
  13059. 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 ] );
  13060. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  13061. const diminish = float( diminish_immutable ).toVar();
  13062. const lacunarity = float( lacunarity_immutable ).toVar();
  13063. const octaves = int( octaves_immutable ).toVar();
  13064. const p = vec3( p_immutable ).toVar();
  13065. const result = float( 0.0 ).toVar();
  13066. const amplitude = float( 1.0 ).toVar();
  13067. Loop( octaves, () => {
  13068. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  13069. amplitude.mulAssign( diminish );
  13070. p.mulAssign( lacunarity );
  13071. } );
  13072. return result;
  13073. } ).setLayout( {
  13074. name: 'mx_fractal_noise_float',
  13075. type: 'float',
  13076. inputs: [
  13077. { name: 'p', type: 'vec3' },
  13078. { name: 'octaves', type: 'int' },
  13079. { name: 'lacunarity', type: 'float' },
  13080. { name: 'diminish', type: 'float' }
  13081. ]
  13082. } );
  13083. const mx_fractal_noise_vec3$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 = vec3( 0.0 ).toVar();
  13089. const amplitude = float( 1.0 ).toVar();
  13090. Loop( octaves, () => {
  13091. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  13092. amplitude.mulAssign( diminish );
  13093. p.mulAssign( lacunarity );
  13094. } );
  13095. return result;
  13096. } ).setLayout( {
  13097. name: 'mx_fractal_noise_vec3',
  13098. type: 'vec3',
  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_vec2$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. 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 ) );
  13112. } ).setLayout( {
  13113. name: 'mx_fractal_noise_vec2',
  13114. type: 'vec2',
  13115. inputs: [
  13116. { name: 'p', type: 'vec3' },
  13117. { name: 'octaves', type: 'int' },
  13118. { name: 'lacunarity', type: 'float' },
  13119. { name: 'diminish', type: 'float' }
  13120. ]
  13121. } );
  13122. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  13123. const diminish = float( diminish_immutable ).toVar();
  13124. const lacunarity = float( lacunarity_immutable ).toVar();
  13125. const octaves = int( octaves_immutable ).toVar();
  13126. const p = vec3( p_immutable ).toVar();
  13127. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  13128. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  13129. return vec4( c, f );
  13130. } ).setLayout( {
  13131. name: 'mx_fractal_noise_vec4',
  13132. type: 'vec4',
  13133. inputs: [
  13134. { name: 'p', type: 'vec3' },
  13135. { name: 'octaves', type: 'int' },
  13136. { name: 'lacunarity', type: 'float' },
  13137. { name: 'diminish', type: 'float' }
  13138. ]
  13139. } );
  13140. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  13141. const metric = int( metric_immutable ).toVar();
  13142. const jitter = float( jitter_immutable ).toVar();
  13143. const yoff = int( yoff_immutable ).toVar();
  13144. const xoff = int( xoff_immutable ).toVar();
  13145. const y = int( y_immutable ).toVar();
  13146. const x = int( x_immutable ).toVar();
  13147. const p = vec2( p_immutable ).toVar();
  13148. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  13149. const off = vec2( tmp.x, tmp.y ).toVar();
  13150. off.subAssign( 0.5 );
  13151. off.mulAssign( jitter );
  13152. off.addAssign( 0.5 );
  13153. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  13154. const diff = vec2( cellpos.sub( p ) ).toVar();
  13155. If( metric.equal( int( 2 ) ), () => {
  13156. return abs( diff.x ).add( abs( diff.y ) );
  13157. } );
  13158. If( metric.equal( int( 3 ) ), () => {
  13159. return max$1( abs( diff.x ), abs( diff.y ) );
  13160. } );
  13161. return dot( diff, diff );
  13162. } ).setLayout( {
  13163. name: 'mx_worley_distance_0',
  13164. type: 'float',
  13165. inputs: [
  13166. { name: 'p', type: 'vec2' },
  13167. { name: 'x', type: 'int' },
  13168. { name: 'y', type: 'int' },
  13169. { name: 'xoff', type: 'int' },
  13170. { name: 'yoff', type: 'int' },
  13171. { name: 'jitter', type: 'float' },
  13172. { name: 'metric', type: 'int' }
  13173. ]
  13174. } );
  13175. 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 ] ) => {
  13176. const metric = int( metric_immutable ).toVar();
  13177. const jitter = float( jitter_immutable ).toVar();
  13178. const zoff = int( zoff_immutable ).toVar();
  13179. const yoff = int( yoff_immutable ).toVar();
  13180. const xoff = int( xoff_immutable ).toVar();
  13181. const z = int( z_immutable ).toVar();
  13182. const y = int( y_immutable ).toVar();
  13183. const x = int( x_immutable ).toVar();
  13184. const p = vec3( p_immutable ).toVar();
  13185. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  13186. off.subAssign( 0.5 );
  13187. off.mulAssign( jitter );
  13188. off.addAssign( 0.5 );
  13189. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  13190. const diff = vec3( cellpos.sub( p ) ).toVar();
  13191. If( metric.equal( int( 2 ) ), () => {
  13192. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  13193. } );
  13194. If( metric.equal( int( 3 ) ), () => {
  13195. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  13196. } );
  13197. return dot( diff, diff );
  13198. } ).setLayout( {
  13199. name: 'mx_worley_distance_1',
  13200. type: 'float',
  13201. inputs: [
  13202. { name: 'p', type: 'vec3' },
  13203. { name: 'x', type: 'int' },
  13204. { name: 'y', type: 'int' },
  13205. { name: 'z', type: 'int' },
  13206. { name: 'xoff', type: 'int' },
  13207. { name: 'yoff', type: 'int' },
  13208. { name: 'zoff', type: 'int' },
  13209. { name: 'jitter', type: 'float' },
  13210. { name: 'metric', type: 'int' }
  13211. ]
  13212. } );
  13213. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  13214. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13215. const metric = int( metric_immutable ).toVar();
  13216. const jitter = float( jitter_immutable ).toVar();
  13217. const p = vec2( p_immutable ).toVar();
  13218. const X = int().toVar(), Y = int().toVar();
  13219. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  13220. const sqdist = float( 1e6 ).toVar();
  13221. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13222. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13223. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  13224. sqdist.assign( min$1( sqdist, dist ) );
  13225. } );
  13226. } );
  13227. If( metric.equal( int( 0 ) ), () => {
  13228. sqdist.assign( sqrt( sqdist ) );
  13229. } );
  13230. return sqdist;
  13231. } ).setLayout( {
  13232. name: 'mx_worley_noise_float_0',
  13233. type: 'float',
  13234. inputs: [
  13235. { name: 'p', type: 'vec2' },
  13236. { name: 'jitter', type: 'float' },
  13237. { name: 'metric', type: 'int' }
  13238. ]
  13239. } );
  13240. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13241. const metric = int( metric_immutable ).toVar();
  13242. const jitter = float( jitter_immutable ).toVar();
  13243. const p = vec2( p_immutable ).toVar();
  13244. const X = int().toVar(), Y = int().toVar();
  13245. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  13246. const sqdist = vec2( 1e6, 1e6 ).toVar();
  13247. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13248. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13249. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  13250. If( dist.lessThan( sqdist.x ), () => {
  13251. sqdist.y.assign( sqdist.x );
  13252. sqdist.x.assign( dist );
  13253. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  13254. sqdist.y.assign( dist );
  13255. } );
  13256. } );
  13257. } );
  13258. If( metric.equal( int( 0 ) ), () => {
  13259. sqdist.assign( sqrt( sqdist ) );
  13260. } );
  13261. return sqdist;
  13262. } ).setLayout( {
  13263. name: 'mx_worley_noise_vec2_0',
  13264. type: 'vec2',
  13265. inputs: [
  13266. { name: 'p', type: 'vec2' },
  13267. { name: 'jitter', type: 'float' },
  13268. { name: 'metric', type: 'int' }
  13269. ]
  13270. } );
  13271. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13272. const metric = int( metric_immutable ).toVar();
  13273. const jitter = float( jitter_immutable ).toVar();
  13274. const p = vec2( p_immutable ).toVar();
  13275. const X = int().toVar(), Y = int().toVar();
  13276. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  13277. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  13278. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13279. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13280. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  13281. If( dist.lessThan( sqdist.x ), () => {
  13282. sqdist.z.assign( sqdist.y );
  13283. sqdist.y.assign( sqdist.x );
  13284. sqdist.x.assign( dist );
  13285. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  13286. sqdist.z.assign( sqdist.y );
  13287. sqdist.y.assign( dist );
  13288. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  13289. sqdist.z.assign( dist );
  13290. } );
  13291. } );
  13292. } );
  13293. If( metric.equal( int( 0 ) ), () => {
  13294. sqdist.assign( sqrt( sqdist ) );
  13295. } );
  13296. return sqdist;
  13297. } ).setLayout( {
  13298. name: 'mx_worley_noise_vec3_0',
  13299. type: 'vec3',
  13300. inputs: [
  13301. { name: 'p', type: 'vec2' },
  13302. { name: 'jitter', type: 'float' },
  13303. { name: 'metric', type: 'int' }
  13304. ]
  13305. } );
  13306. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13307. const metric = int( metric_immutable ).toVar();
  13308. const jitter = float( jitter_immutable ).toVar();
  13309. const p = vec3( p_immutable ).toVar();
  13310. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  13311. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  13312. const sqdist = float( 1e6 ).toVar();
  13313. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13314. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13315. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  13316. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  13317. sqdist.assign( min$1( sqdist, dist ) );
  13318. } );
  13319. } );
  13320. } );
  13321. If( metric.equal( int( 0 ) ), () => {
  13322. sqdist.assign( sqrt( sqdist ) );
  13323. } );
  13324. return sqdist;
  13325. } ).setLayout( {
  13326. name: 'mx_worley_noise_float_1',
  13327. type: 'float',
  13328. inputs: [
  13329. { name: 'p', type: 'vec3' },
  13330. { name: 'jitter', type: 'float' },
  13331. { name: 'metric', type: 'int' }
  13332. ]
  13333. } );
  13334. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  13335. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13336. const metric = int( metric_immutable ).toVar();
  13337. const jitter = float( jitter_immutable ).toVar();
  13338. const p = vec3( p_immutable ).toVar();
  13339. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  13340. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  13341. const sqdist = vec2( 1e6, 1e6 ).toVar();
  13342. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13343. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13344. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  13345. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  13346. If( dist.lessThan( sqdist.x ), () => {
  13347. sqdist.y.assign( sqdist.x );
  13348. sqdist.x.assign( dist );
  13349. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  13350. sqdist.y.assign( dist );
  13351. } );
  13352. } );
  13353. } );
  13354. } );
  13355. If( metric.equal( int( 0 ) ), () => {
  13356. sqdist.assign( sqrt( sqdist ) );
  13357. } );
  13358. return sqdist;
  13359. } ).setLayout( {
  13360. name: 'mx_worley_noise_vec2_1',
  13361. type: 'vec2',
  13362. inputs: [
  13363. { name: 'p', type: 'vec3' },
  13364. { name: 'jitter', type: 'float' },
  13365. { name: 'metric', type: 'int' }
  13366. ]
  13367. } );
  13368. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  13369. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13370. const metric = int( metric_immutable ).toVar();
  13371. const jitter = float( jitter_immutable ).toVar();
  13372. const p = vec3( p_immutable ).toVar();
  13373. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  13374. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  13375. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  13376. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13377. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13378. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  13379. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  13380. If( dist.lessThan( sqdist.x ), () => {
  13381. sqdist.z.assign( sqdist.y );
  13382. sqdist.y.assign( sqdist.x );
  13383. sqdist.x.assign( dist );
  13384. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  13385. sqdist.z.assign( sqdist.y );
  13386. sqdist.y.assign( dist );
  13387. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  13388. sqdist.z.assign( dist );
  13389. } );
  13390. } );
  13391. } );
  13392. } );
  13393. If( metric.equal( int( 0 ) ), () => {
  13394. sqdist.assign( sqrt( sqdist ) );
  13395. } );
  13396. return sqdist;
  13397. } ).setLayout( {
  13398. name: 'mx_worley_noise_vec3_1',
  13399. type: 'vec3',
  13400. inputs: [
  13401. { name: 'p', type: 'vec3' },
  13402. { name: 'jitter', type: 'float' },
  13403. { name: 'metric', type: 'int' }
  13404. ]
  13405. } );
  13406. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  13407. // Three.js Transpiler
  13408. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  13409. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  13410. const s = hsv.y;
  13411. const v = hsv.z;
  13412. const result = vec3().toVar();
  13413. If( s.lessThan( 0.0001 ), () => {
  13414. result.assign( vec3( v, v, v ) );
  13415. } ).Else( () => {
  13416. let h = hsv.x;
  13417. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  13418. const hi = int( trunc( h ) );
  13419. const f = h.sub( float( hi ) );
  13420. const p = v.mul( s.oneMinus() );
  13421. const q = v.mul( s.mul( f ).oneMinus() );
  13422. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  13423. If( hi.equal( int( 0 ) ), () => {
  13424. result.assign( vec3( v, t, p ) );
  13425. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  13426. result.assign( vec3( q, v, p ) );
  13427. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  13428. result.assign( vec3( p, v, t ) );
  13429. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  13430. result.assign( vec3( p, q, v ) );
  13431. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  13432. result.assign( vec3( t, p, v ) );
  13433. } ).Else( () => {
  13434. result.assign( vec3( v, p, q ) );
  13435. } );
  13436. } );
  13437. return result;
  13438. } ).setLayout( {
  13439. name: 'mx_hsvtorgb',
  13440. type: 'vec3',
  13441. inputs: [
  13442. { name: 'hsv', type: 'vec3' }
  13443. ]
  13444. } );
  13445. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  13446. const c = vec3( c_immutable ).toVar();
  13447. const r = float( c.x ).toVar();
  13448. const g = float( c.y ).toVar();
  13449. const b = float( c.z ).toVar();
  13450. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  13451. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  13452. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  13453. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  13454. v.assign( maxcomp );
  13455. If( maxcomp.greaterThan( 0.0 ), () => {
  13456. s.assign( delta.div( maxcomp ) );
  13457. } ).Else( () => {
  13458. s.assign( 0.0 );
  13459. } );
  13460. If( s.lessThanEqual( 0.0 ), () => {
  13461. h.assign( 0.0 );
  13462. } ).Else( () => {
  13463. If( r.greaterThanEqual( maxcomp ), () => {
  13464. h.assign( g.sub( b ).div( delta ) );
  13465. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  13466. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  13467. } ).Else( () => {
  13468. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  13469. } );
  13470. h.mulAssign( 1.0 / 6.0 );
  13471. If( h.lessThan( 0.0 ), () => {
  13472. h.addAssign( 1.0 );
  13473. } );
  13474. } );
  13475. return vec3( h, s, v );
  13476. } ).setLayout( {
  13477. name: 'mx_rgbtohsv',
  13478. type: 'vec3',
  13479. inputs: [
  13480. { name: 'c', type: 'vec3' }
  13481. ]
  13482. } );
  13483. // Three.js Transpiler
  13484. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  13485. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  13486. const color = vec3( color_immutable ).toVar();
  13487. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  13488. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  13489. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  13490. return mix( linSeg, powSeg, isAbove );
  13491. } ).setLayout( {
  13492. name: 'mx_srgb_texture_to_lin_rec709',
  13493. type: 'vec3',
  13494. inputs: [
  13495. { name: 'color', type: 'vec3' }
  13496. ]
  13497. } );
  13498. const mx_aastep = ( threshold, value ) => {
  13499. threshold = float( threshold );
  13500. value = float( value );
  13501. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  13502. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  13503. };
  13504. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  13505. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  13506. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  13507. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  13508. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  13509. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  13510. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  13511. const mx_safepower = ( in1, in2 = 1 ) => {
  13512. in1 = float( in1 );
  13513. return in1.abs().pow( in2 ).mul( in1.sign() );
  13514. };
  13515. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  13516. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  13517. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  13518. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  13519. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  13520. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  13521. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  13522. return noise_vec4.mul( amplitude ).add( pivot );
  13523. };
  13524. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  13525. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  13526. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  13527. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  13528. 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 );
  13529. 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 );
  13530. 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 );
  13531. 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 );
  13532. // https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html
  13533. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  13534. const nDir = normalize( normal ).toVar( 'nDir' );
  13535. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmax' );
  13536. const rbmin = sub( float( - 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmin' );
  13537. const rbminmax = vec3().toVar( 'rbminmax' );
  13538. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  13539. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  13540. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  13541. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar( 'correction' );
  13542. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar( 'boxIntersection' );
  13543. return boxIntersection.sub( cubePos );
  13544. } );
  13545. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  13546. // normal is assumed to have unit length
  13547. const x = normal.x, y = normal.y, z = normal.z;
  13548. // band 0
  13549. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  13550. // band 1
  13551. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  13552. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  13553. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  13554. // band 2
  13555. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  13556. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  13557. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  13558. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  13559. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  13560. return result;
  13561. } );
  13562. // constants
  13563. var TSL = /*#__PURE__*/Object.freeze({
  13564. __proto__: null,
  13565. BRDF_GGX: BRDF_GGX,
  13566. BRDF_Lambert: BRDF_Lambert,
  13567. BasicShadowFilter: BasicShadowFilter,
  13568. Break: Break,
  13569. Continue: Continue,
  13570. DFGApprox: DFGApprox,
  13571. D_GGX: D_GGX,
  13572. Discard: Discard,
  13573. EPSILON: EPSILON,
  13574. F_Schlick: F_Schlick,
  13575. Fn: Fn,
  13576. INFINITY: INFINITY,
  13577. If: If,
  13578. Loop: Loop,
  13579. NodeAccess: NodeAccess,
  13580. NodeShaderStage: NodeShaderStage,
  13581. NodeType: NodeType,
  13582. NodeUpdateType: NodeUpdateType,
  13583. PCFShadowFilter: PCFShadowFilter,
  13584. PCFSoftShadowFilter: PCFSoftShadowFilter,
  13585. PI: PI,
  13586. PI2: PI2,
  13587. Return: Return,
  13588. Schlick_to_F0: Schlick_to_F0,
  13589. ScriptableNodeResources: ScriptableNodeResources,
  13590. ShaderNode: ShaderNode,
  13591. TBNViewMatrix: TBNViewMatrix,
  13592. VSMShadowFilter: VSMShadowFilter,
  13593. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  13594. abs: abs,
  13595. acesFilmicToneMapping: acesFilmicToneMapping,
  13596. acos: acos,
  13597. add: add,
  13598. addMethodChaining: addMethodChaining,
  13599. addNodeElement: addNodeElement,
  13600. agxToneMapping: agxToneMapping,
  13601. all: all,
  13602. alphaT: alphaT,
  13603. and: and,
  13604. anisotropy: anisotropy,
  13605. anisotropyB: anisotropyB,
  13606. anisotropyT: anisotropyT,
  13607. any: any,
  13608. append: append,
  13609. arrayBuffer: arrayBuffer,
  13610. asin: asin,
  13611. assign: assign,
  13612. atan: atan,
  13613. atan2: atan2,
  13614. atomicAdd: atomicAdd,
  13615. atomicAnd: atomicAnd,
  13616. atomicFunc: atomicFunc,
  13617. atomicMax: atomicMax,
  13618. atomicMin: atomicMin,
  13619. atomicOr: atomicOr,
  13620. atomicStore: atomicStore,
  13621. atomicSub: atomicSub,
  13622. atomicXor: atomicXor,
  13623. attenuationColor: attenuationColor,
  13624. attenuationDistance: attenuationDistance,
  13625. attribute: attribute,
  13626. attributeArray: attributeArray,
  13627. backgroundBlurriness: backgroundBlurriness,
  13628. backgroundIntensity: backgroundIntensity,
  13629. backgroundRotation: backgroundRotation,
  13630. batch: batch,
  13631. billboarding: billboarding,
  13632. bitAnd: bitAnd,
  13633. bitNot: bitNot,
  13634. bitOr: bitOr,
  13635. bitXor: bitXor,
  13636. bitangentGeometry: bitangentGeometry,
  13637. bitangentLocal: bitangentLocal,
  13638. bitangentView: bitangentView,
  13639. bitangentWorld: bitangentWorld,
  13640. bitcast: bitcast,
  13641. blendBurn: blendBurn,
  13642. blendColor: blendColor,
  13643. blendDodge: blendDodge,
  13644. blendOverlay: blendOverlay,
  13645. blendScreen: blendScreen,
  13646. blur: blur,
  13647. bool: bool,
  13648. buffer: buffer,
  13649. bufferAttribute: bufferAttribute,
  13650. bumpMap: bumpMap,
  13651. burn: burn,
  13652. bvec2: bvec2,
  13653. bvec3: bvec3,
  13654. bvec4: bvec4,
  13655. bypass: bypass,
  13656. cache: cache,
  13657. call: call,
  13658. cameraFar: cameraFar,
  13659. cameraNear: cameraNear,
  13660. cameraNormalMatrix: cameraNormalMatrix,
  13661. cameraPosition: cameraPosition,
  13662. cameraProjectionMatrix: cameraProjectionMatrix,
  13663. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  13664. cameraViewMatrix: cameraViewMatrix,
  13665. cameraWorldMatrix: cameraWorldMatrix,
  13666. cbrt: cbrt,
  13667. cdl: cdl,
  13668. ceil: ceil,
  13669. checker: checker,
  13670. cineonToneMapping: cineonToneMapping,
  13671. clamp: clamp,
  13672. clearcoat: clearcoat,
  13673. clearcoatRoughness: clearcoatRoughness,
  13674. code: code,
  13675. color: color,
  13676. colorSpaceToWorking: colorSpaceToWorking,
  13677. colorToDirection: colorToDirection,
  13678. compute: compute,
  13679. cond: cond,
  13680. context: context,
  13681. convert: convert,
  13682. convertColorSpace: convertColorSpace,
  13683. convertToTexture: convertToTexture,
  13684. cos: cos,
  13685. cross: cross,
  13686. cubeTexture: cubeTexture,
  13687. dFdx: dFdx,
  13688. dFdy: dFdy,
  13689. dashSize: dashSize,
  13690. defaultBuildStages: defaultBuildStages,
  13691. defaultShaderStages: defaultShaderStages,
  13692. defined: defined,
  13693. degrees: degrees,
  13694. deltaTime: deltaTime,
  13695. densityFog: densityFog,
  13696. depth: depth,
  13697. depthPass: depthPass,
  13698. difference: difference,
  13699. diffuseColor: diffuseColor,
  13700. directPointLight: directPointLight,
  13701. directionToColor: directionToColor,
  13702. dispersion: dispersion,
  13703. distance: distance,
  13704. div: div,
  13705. dodge: dodge,
  13706. dot: dot,
  13707. drawIndex: drawIndex,
  13708. dynamicBufferAttribute: dynamicBufferAttribute,
  13709. element: element,
  13710. emissive: emissive,
  13711. equal: equal,
  13712. equals: equals,
  13713. equirectUV: equirectUV,
  13714. exp: exp,
  13715. exp2: exp2,
  13716. expression: expression,
  13717. faceDirection: faceDirection,
  13718. faceForward: faceForward,
  13719. float: float,
  13720. floor: floor,
  13721. fog: fog,
  13722. fract: fract,
  13723. frameGroup: frameGroup,
  13724. frameId: frameId,
  13725. frontFacing: frontFacing,
  13726. fwidth: fwidth,
  13727. gain: gain,
  13728. gapSize: gapSize,
  13729. getConstNodeType: getConstNodeType,
  13730. getCurrentStack: getCurrentStack,
  13731. getDirection: getDirection,
  13732. getDistanceAttenuation: getDistanceAttenuation,
  13733. getGeometryRoughness: getGeometryRoughness,
  13734. getNormalFromDepth: getNormalFromDepth,
  13735. getParallaxCorrectNormal: getParallaxCorrectNormal,
  13736. getRoughness: getRoughness,
  13737. getScreenPosition: getScreenPosition,
  13738. getShIrradianceAt: getShIrradianceAt,
  13739. getTextureIndex: getTextureIndex,
  13740. getViewPosition: getViewPosition,
  13741. glsl: glsl,
  13742. glslFn: glslFn,
  13743. grayscale: grayscale,
  13744. greaterThan: greaterThan,
  13745. greaterThanEqual: greaterThanEqual,
  13746. hash: hash,
  13747. highPrecisionModelNormalViewMatrix: highPrecisionModelNormalViewMatrix,
  13748. highPrecisionModelViewMatrix: highPrecisionModelViewMatrix,
  13749. hue: hue,
  13750. instance: instance,
  13751. instanceIndex: instanceIndex,
  13752. instancedArray: instancedArray,
  13753. instancedBufferAttribute: instancedBufferAttribute,
  13754. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  13755. instancedMesh: instancedMesh,
  13756. int: int,
  13757. inverseSqrt: inverseSqrt,
  13758. invocationLocalIndex: invocationLocalIndex,
  13759. invocationSubgroupIndex: invocationSubgroupIndex,
  13760. ior: ior,
  13761. iridescence: iridescence,
  13762. iridescenceIOR: iridescenceIOR,
  13763. iridescenceThickness: iridescenceThickness,
  13764. ivec2: ivec2,
  13765. ivec3: ivec3,
  13766. ivec4: ivec4,
  13767. js: js,
  13768. label: label,
  13769. length: length,
  13770. lengthSq: lengthSq,
  13771. lessThan: lessThan,
  13772. lessThanEqual: lessThanEqual,
  13773. lightPosition: lightPosition,
  13774. lightTargetDirection: lightTargetDirection,
  13775. lightTargetPosition: lightTargetPosition,
  13776. lightViewPosition: lightViewPosition,
  13777. lightingContext: lightingContext,
  13778. lights: lights,
  13779. linearDepth: linearDepth,
  13780. linearToneMapping: linearToneMapping,
  13781. localId: localId,
  13782. log: log,
  13783. log2: log2,
  13784. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  13785. loop: loop,
  13786. luminance: luminance,
  13787. mat2: mat2,
  13788. mat3: mat3,
  13789. mat4: mat4,
  13790. matcapUV: matcapUV,
  13791. materialAOMap: materialAOMap,
  13792. materialAlphaTest: materialAlphaTest,
  13793. materialAnisotropy: materialAnisotropy,
  13794. materialAnisotropyVector: materialAnisotropyVector,
  13795. materialAttenuationColor: materialAttenuationColor,
  13796. materialAttenuationDistance: materialAttenuationDistance,
  13797. materialClearcoat: materialClearcoat,
  13798. materialClearcoatNormal: materialClearcoatNormal,
  13799. materialClearcoatRoughness: materialClearcoatRoughness,
  13800. materialColor: materialColor,
  13801. materialDispersion: materialDispersion,
  13802. materialEmissive: materialEmissive,
  13803. materialIOR: materialIOR,
  13804. materialIridescence: materialIridescence,
  13805. materialIridescenceIOR: materialIridescenceIOR,
  13806. materialIridescenceThickness: materialIridescenceThickness,
  13807. materialLightMap: materialLightMap,
  13808. materialLineDashOffset: materialLineDashOffset,
  13809. materialLineDashSize: materialLineDashSize,
  13810. materialLineGapSize: materialLineGapSize,
  13811. materialLineScale: materialLineScale,
  13812. materialLineWidth: materialLineWidth,
  13813. materialMetalness: materialMetalness,
  13814. materialNormal: materialNormal,
  13815. materialOpacity: materialOpacity,
  13816. materialPointWidth: materialPointWidth,
  13817. materialReference: materialReference,
  13818. materialReflectivity: materialReflectivity,
  13819. materialRefractionRatio: materialRefractionRatio,
  13820. materialRotation: materialRotation,
  13821. materialRoughness: materialRoughness,
  13822. materialSheen: materialSheen,
  13823. materialSheenRoughness: materialSheenRoughness,
  13824. materialShininess: materialShininess,
  13825. materialSpecular: materialSpecular,
  13826. materialSpecularColor: materialSpecularColor,
  13827. materialSpecularIntensity: materialSpecularIntensity,
  13828. materialSpecularStrength: materialSpecularStrength,
  13829. materialThickness: materialThickness,
  13830. materialTransmission: materialTransmission,
  13831. max: max$1,
  13832. maxMipLevel: maxMipLevel,
  13833. metalness: metalness,
  13834. min: min$1,
  13835. mix: mix,
  13836. mixElement: mixElement,
  13837. mod: mod,
  13838. modInt: modInt,
  13839. modelDirection: modelDirection,
  13840. modelNormalMatrix: modelNormalMatrix,
  13841. modelPosition: modelPosition,
  13842. modelScale: modelScale,
  13843. modelViewMatrix: modelViewMatrix,
  13844. modelViewPosition: modelViewPosition,
  13845. modelViewProjection: modelViewProjection,
  13846. modelWorldMatrix: modelWorldMatrix,
  13847. modelWorldMatrixInverse: modelWorldMatrixInverse,
  13848. morphReference: morphReference,
  13849. mrt: mrt,
  13850. mul: mul,
  13851. mx_aastep: mx_aastep,
  13852. mx_cell_noise_float: mx_cell_noise_float,
  13853. mx_contrast: mx_contrast,
  13854. mx_fractal_noise_float: mx_fractal_noise_float,
  13855. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  13856. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  13857. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  13858. mx_hsvtorgb: mx_hsvtorgb,
  13859. mx_noise_float: mx_noise_float,
  13860. mx_noise_vec3: mx_noise_vec3,
  13861. mx_noise_vec4: mx_noise_vec4,
  13862. mx_ramplr: mx_ramplr,
  13863. mx_ramptb: mx_ramptb,
  13864. mx_rgbtohsv: mx_rgbtohsv,
  13865. mx_safepower: mx_safepower,
  13866. mx_splitlr: mx_splitlr,
  13867. mx_splittb: mx_splittb,
  13868. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  13869. mx_transform_uv: mx_transform_uv,
  13870. mx_worley_noise_float: mx_worley_noise_float,
  13871. mx_worley_noise_vec2: mx_worley_noise_vec2,
  13872. mx_worley_noise_vec3: mx_worley_noise_vec3,
  13873. negate: negate,
  13874. neutralToneMapping: neutralToneMapping,
  13875. nodeArray: nodeArray,
  13876. nodeImmutable: nodeImmutable,
  13877. nodeObject: nodeObject,
  13878. nodeObjects: nodeObjects,
  13879. nodeProxy: nodeProxy,
  13880. normalFlat: normalFlat,
  13881. normalGeometry: normalGeometry,
  13882. normalLocal: normalLocal,
  13883. normalMap: normalMap,
  13884. normalView: normalView,
  13885. normalWorld: normalWorld,
  13886. normalize: normalize,
  13887. not: not,
  13888. notEqual: notEqual,
  13889. numWorkgroups: numWorkgroups,
  13890. objectDirection: objectDirection,
  13891. objectGroup: objectGroup,
  13892. objectPosition: objectPosition,
  13893. objectScale: objectScale,
  13894. objectViewPosition: objectViewPosition,
  13895. objectWorldMatrix: objectWorldMatrix,
  13896. oneMinus: oneMinus,
  13897. or: or,
  13898. orthographicDepthToViewZ: orthographicDepthToViewZ,
  13899. oscSawtooth: oscSawtooth,
  13900. oscSine: oscSine,
  13901. oscSquare: oscSquare,
  13902. oscTriangle: oscTriangle,
  13903. output: output,
  13904. outputStruct: outputStruct,
  13905. overlay: overlay,
  13906. overloadingFn: overloadingFn,
  13907. parabola: parabola,
  13908. parallaxDirection: parallaxDirection,
  13909. parallaxUV: parallaxUV,
  13910. parameter: parameter,
  13911. pass: pass,
  13912. passTexture: passTexture,
  13913. pcurve: pcurve,
  13914. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  13915. pmremTexture: pmremTexture,
  13916. pointUV: pointUV,
  13917. pointWidth: pointWidth,
  13918. positionGeometry: positionGeometry,
  13919. positionLocal: positionLocal,
  13920. positionPrevious: positionPrevious,
  13921. positionView: positionView,
  13922. positionViewDirection: positionViewDirection,
  13923. positionWorld: positionWorld,
  13924. positionWorldDirection: positionWorldDirection,
  13925. posterize: posterize,
  13926. pow: pow,
  13927. pow2: pow2,
  13928. pow3: pow3,
  13929. pow4: pow4,
  13930. property: property,
  13931. radians: radians,
  13932. rand: rand,
  13933. range: range,
  13934. rangeFog: rangeFog,
  13935. reciprocal: reciprocal,
  13936. reference: reference,
  13937. referenceBuffer: referenceBuffer,
  13938. reflect: reflect,
  13939. reflectVector: reflectVector,
  13940. reflectView: reflectView,
  13941. reflector: reflector,
  13942. refract: refract,
  13943. refractVector: refractVector,
  13944. refractView: refractView,
  13945. reinhardToneMapping: reinhardToneMapping,
  13946. remainder: remainder,
  13947. remap: remap,
  13948. remapClamp: remapClamp,
  13949. renderGroup: renderGroup,
  13950. renderOutput: renderOutput,
  13951. rendererReference: rendererReference,
  13952. rotate: rotate,
  13953. rotateUV: rotateUV,
  13954. roughness: roughness,
  13955. round: round,
  13956. rtt: rtt,
  13957. sRGBTransferEOTF: sRGBTransferEOTF,
  13958. sRGBTransferOETF: sRGBTransferOETF,
  13959. sampler: sampler,
  13960. saturate: saturate,
  13961. saturation: saturation,
  13962. screen: screen,
  13963. screenCoordinate: screenCoordinate,
  13964. screenSize: screenSize,
  13965. screenUV: screenUV,
  13966. scriptable: scriptable,
  13967. scriptableValue: scriptableValue,
  13968. select: select,
  13969. setCurrentStack: setCurrentStack,
  13970. shaderStages: shaderStages,
  13971. shadow: shadow,
  13972. sharedUniformGroup: sharedUniformGroup,
  13973. sheen: sheen,
  13974. sheenRoughness: sheenRoughness,
  13975. shiftLeft: shiftLeft,
  13976. shiftRight: shiftRight,
  13977. shininess: shininess,
  13978. sign: sign,
  13979. sin: sin,
  13980. sinc: sinc,
  13981. skinning: skinning,
  13982. skinningReference: skinningReference,
  13983. smoothstep: smoothstep,
  13984. smoothstepElement: smoothstepElement,
  13985. specularColor: specularColor,
  13986. specularF90: specularF90,
  13987. spherizeUV: spherizeUV,
  13988. split: split,
  13989. spritesheetUV: spritesheetUV,
  13990. sqrt: sqrt,
  13991. stack: stack,
  13992. step: step,
  13993. storage: storage,
  13994. storageBarrier: storageBarrier,
  13995. storageObject: storageObject,
  13996. storageTexture: storageTexture,
  13997. string: string,
  13998. sub: sub,
  13999. subgroupIndex: subgroupIndex,
  14000. subgroupSize: subgroupSize,
  14001. tan: tan,
  14002. tangentGeometry: tangentGeometry,
  14003. tangentLocal: tangentLocal,
  14004. tangentView: tangentView,
  14005. tangentWorld: tangentWorld,
  14006. temp: temp,
  14007. texture: texture,
  14008. texture3D: texture3D,
  14009. textureBarrier: textureBarrier,
  14010. textureBicubic: textureBicubic,
  14011. textureCubeUV: textureCubeUV,
  14012. textureLoad: textureLoad,
  14013. textureSize: textureSize,
  14014. textureStore: textureStore,
  14015. thickness: thickness,
  14016. threshold: threshold,
  14017. time: time,
  14018. timerDelta: timerDelta,
  14019. timerGlobal: timerGlobal,
  14020. timerLocal: timerLocal,
  14021. toOutputColorSpace: toOutputColorSpace,
  14022. toWorkingColorSpace: toWorkingColorSpace,
  14023. toneMapping: toneMapping,
  14024. toneMappingExposure: toneMappingExposure,
  14025. toonOutlinePass: toonOutlinePass,
  14026. transformDirection: transformDirection,
  14027. transformNormal: transformNormal,
  14028. transformNormalToView: transformNormalToView,
  14029. transformedBentNormalView: transformedBentNormalView,
  14030. transformedBitangentView: transformedBitangentView,
  14031. transformedBitangentWorld: transformedBitangentWorld,
  14032. transformedClearcoatNormalView: transformedClearcoatNormalView,
  14033. transformedNormalView: transformedNormalView,
  14034. transformedNormalWorld: transformedNormalWorld,
  14035. transformedTangentView: transformedTangentView,
  14036. transformedTangentWorld: transformedTangentWorld,
  14037. transmission: transmission,
  14038. transpose: transpose,
  14039. tri: tri,
  14040. tri3: tri3,
  14041. triNoise3D: triNoise3D,
  14042. triplanarTexture: triplanarTexture,
  14043. triplanarTextures: triplanarTextures,
  14044. trunc: trunc,
  14045. tslFn: tslFn,
  14046. uint: uint,
  14047. uniform: uniform,
  14048. uniformArray: uniformArray,
  14049. uniformGroup: uniformGroup,
  14050. uniforms: uniforms,
  14051. userData: userData,
  14052. uv: uv,
  14053. uvec2: uvec2,
  14054. uvec3: uvec3,
  14055. uvec4: uvec4,
  14056. varying: varying,
  14057. varyingProperty: varyingProperty,
  14058. vec2: vec2,
  14059. vec3: vec3,
  14060. vec4: vec4,
  14061. vectorComponents: vectorComponents,
  14062. velocity: velocity,
  14063. vertexColor: vertexColor,
  14064. vertexIndex: vertexIndex,
  14065. vibrance: vibrance,
  14066. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  14067. viewZToOrthographicDepth: viewZToOrthographicDepth,
  14068. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  14069. viewport: viewport,
  14070. viewportBottomLeft: viewportBottomLeft,
  14071. viewportCoordinate: viewportCoordinate,
  14072. viewportDepthTexture: viewportDepthTexture,
  14073. viewportLinearDepth: viewportLinearDepth,
  14074. viewportMipTexture: viewportMipTexture,
  14075. viewportResolution: viewportResolution,
  14076. viewportSafeUV: viewportSafeUV,
  14077. viewportSharedTexture: viewportSharedTexture,
  14078. viewportSize: viewportSize,
  14079. viewportTexture: viewportTexture,
  14080. viewportTopLeft: viewportTopLeft,
  14081. viewportUV: viewportUV,
  14082. wgsl: wgsl,
  14083. wgslFn: wgslFn,
  14084. workgroupArray: workgroupArray,
  14085. workgroupBarrier: workgroupBarrier,
  14086. workgroupId: workgroupId,
  14087. workingToColorSpace: workingToColorSpace,
  14088. xor: xor
  14089. });
  14090. const _clearColor$1 = /*@__PURE__*/ new Color4();
  14091. class Background extends DataMap {
  14092. constructor( renderer, nodes ) {
  14093. super();
  14094. this.renderer = renderer;
  14095. this.nodes = nodes;
  14096. }
  14097. update( scene, renderList, renderContext ) {
  14098. const renderer = this.renderer;
  14099. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  14100. let forceClear = false;
  14101. if ( background === null ) {
  14102. // no background settings, use clear color configuration from the renderer
  14103. renderer._clearColor.getRGB( _clearColor$1, LinearSRGBColorSpace );
  14104. _clearColor$1.a = renderer._clearColor.a;
  14105. } else if ( background.isColor === true ) {
  14106. // background is an opaque color
  14107. background.getRGB( _clearColor$1, LinearSRGBColorSpace );
  14108. _clearColor$1.a = 1;
  14109. forceClear = true;
  14110. } else if ( background.isNode === true ) {
  14111. const sceneData = this.get( scene );
  14112. const backgroundNode = background;
  14113. _clearColor$1.copy( renderer._clearColor );
  14114. let backgroundMesh = sceneData.backgroundMesh;
  14115. if ( backgroundMesh === undefined ) {
  14116. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  14117. // @TODO: Add Texture2D support using node context
  14118. getUV: () => backgroundRotation.mul( normalWorld ),
  14119. getTextureLevel: () => backgroundBlurriness
  14120. } );
  14121. let viewProj = modelViewProjection();
  14122. viewProj = viewProj.setZ( viewProj.w );
  14123. const nodeMaterial = new NodeMaterial();
  14124. nodeMaterial.name = 'Background.material';
  14125. nodeMaterial.side = BackSide;
  14126. nodeMaterial.depthTest = false;
  14127. nodeMaterial.depthWrite = false;
  14128. nodeMaterial.fog = false;
  14129. nodeMaterial.lights = false;
  14130. nodeMaterial.vertexNode = viewProj;
  14131. nodeMaterial.colorNode = backgroundMeshNode;
  14132. sceneData.backgroundMeshNode = backgroundMeshNode;
  14133. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  14134. backgroundMesh.frustumCulled = false;
  14135. backgroundMesh.name = 'Background.mesh';
  14136. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  14137. this.matrixWorld.copyPosition( camera.matrixWorld );
  14138. };
  14139. }
  14140. const backgroundCacheKey = backgroundNode.getCacheKey();
  14141. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  14142. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  14143. sceneData.backgroundMeshNode.needsUpdate = true;
  14144. backgroundMesh.material.needsUpdate = true;
  14145. sceneData.backgroundCacheKey = backgroundCacheKey;
  14146. }
  14147. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  14148. } else {
  14149. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  14150. }
  14151. //
  14152. if ( renderer.autoClear === true || forceClear === true ) {
  14153. const clearColorValue = renderContext.clearColorValue;
  14154. clearColorValue.r = _clearColor$1.r;
  14155. clearColorValue.g = _clearColor$1.g;
  14156. clearColorValue.b = _clearColor$1.b;
  14157. clearColorValue.a = _clearColor$1.a;
  14158. // premultiply alpha
  14159. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  14160. clearColorValue.r *= clearColorValue.a;
  14161. clearColorValue.g *= clearColorValue.a;
  14162. clearColorValue.b *= clearColorValue.a;
  14163. }
  14164. //
  14165. renderContext.depthClearValue = renderer._clearDepth;
  14166. renderContext.stencilClearValue = renderer._clearStencil;
  14167. renderContext.clearColor = renderer.autoClearColor === true;
  14168. renderContext.clearDepth = renderer.autoClearDepth === true;
  14169. renderContext.clearStencil = renderer.autoClearStencil === true;
  14170. } else {
  14171. renderContext.clearColor = false;
  14172. renderContext.clearDepth = false;
  14173. renderContext.clearStencil = false;
  14174. }
  14175. }
  14176. }
  14177. let _id$5 = 0;
  14178. class BindGroup {
  14179. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  14180. this.name = name;
  14181. this.bindings = bindings;
  14182. this.index = index;
  14183. this.bindingsReference = bindingsReference;
  14184. this.id = _id$5 ++;
  14185. }
  14186. }
  14187. class NodeBuilderState {
  14188. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, monitor, transforms = [] ) {
  14189. this.vertexShader = vertexShader;
  14190. this.fragmentShader = fragmentShader;
  14191. this.computeShader = computeShader;
  14192. this.transforms = transforms;
  14193. this.nodeAttributes = nodeAttributes;
  14194. this.bindings = bindings;
  14195. this.updateNodes = updateNodes;
  14196. this.updateBeforeNodes = updateBeforeNodes;
  14197. this.updateAfterNodes = updateAfterNodes;
  14198. this.monitor = monitor;
  14199. this.usedTimes = 0;
  14200. }
  14201. createBindings() {
  14202. const bindings = [];
  14203. for ( const instanceGroup of this.bindings ) {
  14204. const shared = instanceGroup.bindings[ 0 ].groupNode.shared;
  14205. if ( shared !== true ) {
  14206. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  14207. bindings.push( bindingsGroup );
  14208. for ( const instanceBinding of instanceGroup.bindings ) {
  14209. bindingsGroup.bindings.push( instanceBinding.clone() );
  14210. }
  14211. } else {
  14212. bindings.push( instanceGroup );
  14213. }
  14214. }
  14215. return bindings;
  14216. }
  14217. }
  14218. class NodeAttribute {
  14219. constructor( name, type, node = null ) {
  14220. this.isNodeAttribute = true;
  14221. this.name = name;
  14222. this.type = type;
  14223. this.node = node;
  14224. }
  14225. }
  14226. class NodeUniform {
  14227. constructor( name, type, node ) {
  14228. this.isNodeUniform = true;
  14229. this.name = name;
  14230. this.type = type;
  14231. this.node = node.getSelf();
  14232. }
  14233. get value() {
  14234. return this.node.value;
  14235. }
  14236. set value( val ) {
  14237. this.node.value = val;
  14238. }
  14239. get id() {
  14240. return this.node.id;
  14241. }
  14242. get groupNode() {
  14243. return this.node.groupNode;
  14244. }
  14245. }
  14246. class NodeVar {
  14247. constructor( name, type ) {
  14248. this.isNodeVar = true;
  14249. this.name = name;
  14250. this.type = type;
  14251. }
  14252. }
  14253. class NodeVarying extends NodeVar {
  14254. constructor( name, type ) {
  14255. super( name, type );
  14256. this.needsInterpolation = false;
  14257. this.isNodeVarying = true;
  14258. }
  14259. }
  14260. class NodeCode {
  14261. constructor( name, type, code = '' ) {
  14262. this.name = name;
  14263. this.type = type;
  14264. this.code = code;
  14265. Object.defineProperty( this, 'isNodeCode', { value: true } );
  14266. }
  14267. }
  14268. let id = 0;
  14269. class NodeCache {
  14270. constructor( parent = null ) {
  14271. this.id = id ++;
  14272. this.nodesData = new WeakMap();
  14273. this.parent = parent;
  14274. }
  14275. getData( node ) {
  14276. let data = this.nodesData.get( node );
  14277. if ( data === undefined && this.parent !== null ) {
  14278. data = this.parent.getData( node );
  14279. }
  14280. return data;
  14281. }
  14282. setData( node, data ) {
  14283. this.nodesData.set( node, data );
  14284. }
  14285. }
  14286. class Uniform {
  14287. constructor( name, value ) {
  14288. this.name = name;
  14289. this.value = value;
  14290. this.boundary = 0; // used to build the uniform buffer according to the STD140 layout
  14291. this.itemSize = 0;
  14292. this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer
  14293. }
  14294. setValue( value ) {
  14295. this.value = value;
  14296. }
  14297. getValue() {
  14298. return this.value;
  14299. }
  14300. }
  14301. class NumberUniform extends Uniform {
  14302. constructor( name, value = 0 ) {
  14303. super( name, value );
  14304. this.isNumberUniform = true;
  14305. this.boundary = 4;
  14306. this.itemSize = 1;
  14307. }
  14308. }
  14309. class Vector2Uniform extends Uniform {
  14310. constructor( name, value = new Vector2() ) {
  14311. super( name, value );
  14312. this.isVector2Uniform = true;
  14313. this.boundary = 8;
  14314. this.itemSize = 2;
  14315. }
  14316. }
  14317. class Vector3Uniform extends Uniform {
  14318. constructor( name, value = new Vector3() ) {
  14319. super( name, value );
  14320. this.isVector3Uniform = true;
  14321. this.boundary = 16;
  14322. this.itemSize = 3;
  14323. }
  14324. }
  14325. class Vector4Uniform extends Uniform {
  14326. constructor( name, value = new Vector4() ) {
  14327. super( name, value );
  14328. this.isVector4Uniform = true;
  14329. this.boundary = 16;
  14330. this.itemSize = 4;
  14331. }
  14332. }
  14333. class ColorUniform extends Uniform {
  14334. constructor( name, value = new Color() ) {
  14335. super( name, value );
  14336. this.isColorUniform = true;
  14337. this.boundary = 16;
  14338. this.itemSize = 3;
  14339. }
  14340. }
  14341. class Matrix3Uniform extends Uniform {
  14342. constructor( name, value = new Matrix3() ) {
  14343. super( name, value );
  14344. this.isMatrix3Uniform = true;
  14345. this.boundary = 48;
  14346. this.itemSize = 12;
  14347. }
  14348. }
  14349. class Matrix4Uniform extends Uniform {
  14350. constructor( name, value = new Matrix4() ) {
  14351. super( name, value );
  14352. this.isMatrix4Uniform = true;
  14353. this.boundary = 64;
  14354. this.itemSize = 16;
  14355. }
  14356. }
  14357. class NumberNodeUniform extends NumberUniform {
  14358. constructor( nodeUniform ) {
  14359. super( nodeUniform.name, nodeUniform.value );
  14360. this.nodeUniform = nodeUniform;
  14361. }
  14362. getValue() {
  14363. return this.nodeUniform.value;
  14364. }
  14365. getType() {
  14366. return this.nodeUniform.type;
  14367. }
  14368. }
  14369. class Vector2NodeUniform extends Vector2Uniform {
  14370. constructor( nodeUniform ) {
  14371. super( nodeUniform.name, nodeUniform.value );
  14372. this.nodeUniform = nodeUniform;
  14373. }
  14374. getValue() {
  14375. return this.nodeUniform.value;
  14376. }
  14377. getType() {
  14378. return this.nodeUniform.type;
  14379. }
  14380. }
  14381. class Vector3NodeUniform extends Vector3Uniform {
  14382. constructor( nodeUniform ) {
  14383. super( nodeUniform.name, nodeUniform.value );
  14384. this.nodeUniform = nodeUniform;
  14385. }
  14386. getValue() {
  14387. return this.nodeUniform.value;
  14388. }
  14389. getType() {
  14390. return this.nodeUniform.type;
  14391. }
  14392. }
  14393. class Vector4NodeUniform extends Vector4Uniform {
  14394. constructor( nodeUniform ) {
  14395. super( nodeUniform.name, nodeUniform.value );
  14396. this.nodeUniform = nodeUniform;
  14397. }
  14398. getValue() {
  14399. return this.nodeUniform.value;
  14400. }
  14401. getType() {
  14402. return this.nodeUniform.type;
  14403. }
  14404. }
  14405. class ColorNodeUniform extends ColorUniform {
  14406. constructor( nodeUniform ) {
  14407. super( nodeUniform.name, nodeUniform.value );
  14408. this.nodeUniform = nodeUniform;
  14409. }
  14410. getValue() {
  14411. return this.nodeUniform.value;
  14412. }
  14413. getType() {
  14414. return this.nodeUniform.type;
  14415. }
  14416. }
  14417. class Matrix3NodeUniform extends Matrix3Uniform {
  14418. constructor( nodeUniform ) {
  14419. super( nodeUniform.name, nodeUniform.value );
  14420. this.nodeUniform = nodeUniform;
  14421. }
  14422. getValue() {
  14423. return this.nodeUniform.value;
  14424. }
  14425. getType() {
  14426. return this.nodeUniform.type;
  14427. }
  14428. }
  14429. class Matrix4NodeUniform extends Matrix4Uniform {
  14430. constructor( nodeUniform ) {
  14431. super( nodeUniform.name, nodeUniform.value );
  14432. this.nodeUniform = nodeUniform;
  14433. }
  14434. getValue() {
  14435. return this.nodeUniform.value;
  14436. }
  14437. getType() {
  14438. return this.nodeUniform.type;
  14439. }
  14440. }
  14441. const LOD_MIN = 4;
  14442. // The standard deviations (radians) associated with the extra mips. These are
  14443. // chosen to approximate a Trowbridge-Reitz distribution function times the
  14444. // geometric shadowing function. These sigma values squared must match the
  14445. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  14446. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  14447. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  14448. // samples and exit early, but not recompile the shader.
  14449. const MAX_SAMPLES = 20;
  14450. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  14451. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  14452. const _clearColor = /*@__PURE__*/ new Color();
  14453. let _oldTarget = null;
  14454. let _oldActiveCubeFace = 0;
  14455. let _oldActiveMipmapLevel = 0;
  14456. // Golden Ratio
  14457. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  14458. const INV_PHI = 1 / PHI;
  14459. // Vertices of a dodecahedron (except the opposites, which represent the
  14460. // same axis), used as axis directions evenly spread on a sphere.
  14461. const _axisDirections = [
  14462. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  14463. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  14464. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  14465. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  14466. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  14467. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  14468. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  14469. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  14470. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  14471. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  14472. ];
  14473. //
  14474. // WebGPU Face indices
  14475. const _faceLib = [
  14476. 3, 1, 5,
  14477. 0, 4, 2
  14478. ];
  14479. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  14480. const outputDirection = vec3( direction.x, direction.y.negate(), direction.z );
  14481. /**
  14482. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  14483. * (PMREM) from a cubeMap environment texture. This allows different levels of
  14484. * blur to be quickly accessed based on material roughness. It is packed into a
  14485. * special CubeUV format that allows us to perform custom interpolation so that
  14486. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  14487. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  14488. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  14489. * higher roughness levels. In this way we maintain resolution to smoothly
  14490. * interpolate diffuse lighting while limiting sampling computation.
  14491. *
  14492. * Paper: Fast, Accurate Image-Based Lighting
  14493. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  14494. */
  14495. class PMREMGenerator {
  14496. constructor( renderer ) {
  14497. this._renderer = renderer;
  14498. this._pingPongRenderTarget = null;
  14499. this._lodMax = 0;
  14500. this._cubeSize = 0;
  14501. this._lodPlanes = [];
  14502. this._sizeLods = [];
  14503. this._sigmas = [];
  14504. this._lodMeshes = [];
  14505. this._blurMaterial = null;
  14506. this._cubemapMaterial = null;
  14507. this._equirectMaterial = null;
  14508. this._backgroundBox = null;
  14509. }
  14510. get _hasInitialized() {
  14511. return this._renderer.hasInitialized();
  14512. }
  14513. /**
  14514. * Generates a PMREM from a supplied Scene, which can be faster than using an
  14515. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  14516. * in radians to be applied to the scene before PMREM generation. Optional near
  14517. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  14518. * is placed at the origin).
  14519. */
  14520. fromScene( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  14521. this._setSize( 256 );
  14522. if ( this._hasInitialized === false ) {
  14523. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  14524. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  14525. this.fromSceneAsync( scene, sigma, near, far, cubeUVRenderTarget );
  14526. return cubeUVRenderTarget;
  14527. }
  14528. _oldTarget = this._renderer.getRenderTarget();
  14529. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  14530. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  14531. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  14532. cubeUVRenderTarget.depthBuffer = true;
  14533. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  14534. if ( sigma > 0 ) {
  14535. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  14536. }
  14537. this._applyPMREM( cubeUVRenderTarget );
  14538. this._cleanup( cubeUVRenderTarget );
  14539. return cubeUVRenderTarget;
  14540. }
  14541. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  14542. if ( this._hasInitialized === false ) await this._renderer.init();
  14543. return this.fromScene( scene, sigma, near, far, renderTarget );
  14544. }
  14545. /**
  14546. * Generates a PMREM from an equirectangular texture, which can be either LDR
  14547. * or HDR. The ideal input image size is 1k (1024 x 512),
  14548. * as this matches best with the 256 x 256 cubemap output.
  14549. */
  14550. fromEquirectangular( equirectangular, renderTarget = null ) {
  14551. if ( this._hasInitialized === false ) {
  14552. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  14553. this._setSizeFromTexture( equirectangular );
  14554. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  14555. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  14556. return cubeUVRenderTarget;
  14557. }
  14558. return this._fromTexture( equirectangular, renderTarget );
  14559. }
  14560. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  14561. if ( this._hasInitialized === false ) await this._renderer.init();
  14562. return this._fromTexture( equirectangular, renderTarget );
  14563. }
  14564. /**
  14565. * Generates a PMREM from an cubemap texture, which can be either LDR
  14566. * or HDR. The ideal input cube size is 256 x 256,
  14567. * as this matches best with the 256 x 256 cubemap output.
  14568. */
  14569. fromCubemap( cubemap, renderTarget = null ) {
  14570. if ( this._hasInitialized === false ) {
  14571. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  14572. this._setSizeFromTexture( cubemap );
  14573. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  14574. this.fromCubemapAsync( cubemap, renderTarget );
  14575. return cubeUVRenderTarget;
  14576. }
  14577. return this._fromTexture( cubemap, renderTarget );
  14578. }
  14579. async fromCubemapAsync( cubemap, renderTarget = null ) {
  14580. if ( this._hasInitialized === false ) await this._renderer.init();
  14581. return this._fromTexture( cubemap, renderTarget );
  14582. }
  14583. /**
  14584. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  14585. * your texture's network fetch for increased concurrency.
  14586. */
  14587. async compileCubemapShader() {
  14588. if ( this._cubemapMaterial === null ) {
  14589. this._cubemapMaterial = _getCubemapMaterial();
  14590. await this._compileMaterial( this._cubemapMaterial );
  14591. }
  14592. }
  14593. /**
  14594. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  14595. * your texture's network fetch for increased concurrency.
  14596. */
  14597. async compileEquirectangularShader() {
  14598. if ( this._equirectMaterial === null ) {
  14599. this._equirectMaterial = _getEquirectMaterial();
  14600. await this._compileMaterial( this._equirectMaterial );
  14601. }
  14602. }
  14603. /**
  14604. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  14605. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  14606. * one of them will cause any others to also become unusable.
  14607. */
  14608. dispose() {
  14609. this._dispose();
  14610. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  14611. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  14612. if ( this._backgroundBox !== null ) {
  14613. this._backgroundBox.geometry.dispose();
  14614. this._backgroundBox.material.dispose();
  14615. }
  14616. }
  14617. // private interface
  14618. _setSizeFromTexture( texture ) {
  14619. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  14620. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  14621. } else { // Equirectangular
  14622. this._setSize( texture.image.width / 4 );
  14623. }
  14624. }
  14625. _setSize( cubeSize ) {
  14626. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  14627. this._cubeSize = Math.pow( 2, this._lodMax );
  14628. }
  14629. _dispose() {
  14630. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  14631. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  14632. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  14633. this._lodPlanes[ i ].dispose();
  14634. }
  14635. }
  14636. _cleanup( outputTarget ) {
  14637. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  14638. outputTarget.scissorTest = false;
  14639. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  14640. }
  14641. _fromTexture( texture, renderTarget ) {
  14642. this._setSizeFromTexture( texture );
  14643. _oldTarget = this._renderer.getRenderTarget();
  14644. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  14645. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  14646. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  14647. this._textureToCubeUV( texture, cubeUVRenderTarget );
  14648. this._applyPMREM( cubeUVRenderTarget );
  14649. this._cleanup( cubeUVRenderTarget );
  14650. return cubeUVRenderTarget;
  14651. }
  14652. _allocateTargets() {
  14653. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  14654. const height = 4 * this._cubeSize;
  14655. const params = {
  14656. magFilter: LinearFilter,
  14657. minFilter: LinearFilter,
  14658. generateMipmaps: false,
  14659. type: HalfFloatType,
  14660. format: RGBAFormat,
  14661. colorSpace: LinearSRGBColorSpace,
  14662. //depthBuffer: false
  14663. };
  14664. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  14665. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  14666. if ( this._pingPongRenderTarget !== null ) {
  14667. this._dispose();
  14668. }
  14669. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  14670. const { _lodMax } = this;
  14671. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  14672. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  14673. }
  14674. return cubeUVRenderTarget;
  14675. }
  14676. async _compileMaterial( material ) {
  14677. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  14678. await this._renderer.compile( tmpMesh, _flatCamera );
  14679. }
  14680. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  14681. const cubeCamera = _cubeCamera;
  14682. cubeCamera.near = near;
  14683. cubeCamera.far = far;
  14684. // px, py, pz, nx, ny, nz
  14685. const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ];
  14686. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  14687. const renderer = this._renderer;
  14688. const originalAutoClear = renderer.autoClear;
  14689. renderer.getClearColor( _clearColor );
  14690. renderer.autoClear = false;
  14691. let backgroundBox = this._backgroundBox;
  14692. if ( backgroundBox === null ) {
  14693. const backgroundMaterial = new MeshBasicMaterial( {
  14694. name: 'PMREM.Background',
  14695. side: BackSide,
  14696. depthWrite: false,
  14697. depthTest: false
  14698. } );
  14699. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  14700. }
  14701. let useSolidColor = false;
  14702. const background = scene.background;
  14703. if ( background ) {
  14704. if ( background.isColor ) {
  14705. backgroundBox.material.color.copy( background );
  14706. scene.background = null;
  14707. useSolidColor = true;
  14708. }
  14709. } else {
  14710. backgroundBox.material.color.copy( _clearColor );
  14711. useSolidColor = true;
  14712. }
  14713. renderer.setRenderTarget( cubeUVRenderTarget );
  14714. renderer.clear();
  14715. if ( useSolidColor ) {
  14716. renderer.render( backgroundBox, cubeCamera );
  14717. }
  14718. for ( let i = 0; i < 6; i ++ ) {
  14719. const col = i % 3;
  14720. if ( col === 0 ) {
  14721. cubeCamera.up.set( 0, upSign[ i ], 0 );
  14722. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  14723. } else if ( col === 1 ) {
  14724. cubeCamera.up.set( 0, 0, upSign[ i ] );
  14725. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  14726. } else {
  14727. cubeCamera.up.set( 0, upSign[ i ], 0 );
  14728. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  14729. }
  14730. const size = this._cubeSize;
  14731. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  14732. renderer.render( scene, cubeCamera );
  14733. }
  14734. renderer.autoClear = originalAutoClear;
  14735. scene.background = background;
  14736. }
  14737. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  14738. const renderer = this._renderer;
  14739. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  14740. if ( isCubeTexture ) {
  14741. if ( this._cubemapMaterial === null ) {
  14742. this._cubemapMaterial = _getCubemapMaterial( texture );
  14743. }
  14744. } else {
  14745. if ( this._equirectMaterial === null ) {
  14746. this._equirectMaterial = _getEquirectMaterial( texture );
  14747. }
  14748. }
  14749. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  14750. material.fragmentNode.value = texture;
  14751. const mesh = this._lodMeshes[ 0 ];
  14752. mesh.material = material;
  14753. const size = this._cubeSize;
  14754. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  14755. renderer.setRenderTarget( cubeUVRenderTarget );
  14756. renderer.render( mesh, _flatCamera );
  14757. }
  14758. _applyPMREM( cubeUVRenderTarget ) {
  14759. const renderer = this._renderer;
  14760. const autoClear = renderer.autoClear;
  14761. renderer.autoClear = false;
  14762. const n = this._lodPlanes.length;
  14763. for ( let i = 1; i < n; i ++ ) {
  14764. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  14765. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  14766. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  14767. }
  14768. renderer.autoClear = autoClear;
  14769. }
  14770. /**
  14771. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  14772. * vertically and horizontally, but this breaks down on a cube. Here we apply
  14773. * the blur latitudinally (around the poles), and then longitudinally (towards
  14774. * the poles) to approximate the orthogonally-separable blur. It is least
  14775. * accurate at the poles, but still does a decent job.
  14776. */
  14777. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  14778. const pingPongRenderTarget = this._pingPongRenderTarget;
  14779. this._halfBlur(
  14780. cubeUVRenderTarget,
  14781. pingPongRenderTarget,
  14782. lodIn,
  14783. lodOut,
  14784. sigma,
  14785. 'latitudinal',
  14786. poleAxis );
  14787. this._halfBlur(
  14788. pingPongRenderTarget,
  14789. cubeUVRenderTarget,
  14790. lodOut,
  14791. lodOut,
  14792. sigma,
  14793. 'longitudinal',
  14794. poleAxis );
  14795. }
  14796. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  14797. const renderer = this._renderer;
  14798. const blurMaterial = this._blurMaterial;
  14799. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  14800. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  14801. }
  14802. // Number of standard deviations at which to cut off the discrete approximation.
  14803. const STANDARD_DEVIATIONS = 3;
  14804. const blurMesh = this._lodMeshes[ lodOut ];
  14805. blurMesh.material = blurMaterial;
  14806. const blurUniforms = blurMaterial.uniforms;
  14807. const pixels = this._sizeLods[ lodIn ] - 1;
  14808. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  14809. const sigmaPixels = sigmaRadians / radiansPerPixel;
  14810. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  14811. if ( samples > MAX_SAMPLES ) {
  14812. console.warn( `sigmaRadians, ${
  14813. sigmaRadians}, is too large and will clip, as it requested ${
  14814. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  14815. }
  14816. const weights = [];
  14817. let sum = 0;
  14818. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  14819. const x = i / sigmaPixels;
  14820. const weight = Math.exp( - x * x / 2 );
  14821. weights.push( weight );
  14822. if ( i === 0 ) {
  14823. sum += weight;
  14824. } else if ( i < samples ) {
  14825. sum += 2 * weight;
  14826. }
  14827. }
  14828. for ( let i = 0; i < weights.length; i ++ ) {
  14829. weights[ i ] = weights[ i ] / sum;
  14830. }
  14831. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  14832. blurUniforms.envMap.value = targetIn.texture;
  14833. blurUniforms.samples.value = samples;
  14834. blurUniforms.weights.array = weights;
  14835. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  14836. if ( poleAxis ) {
  14837. blurUniforms.poleAxis.value = poleAxis;
  14838. }
  14839. const { _lodMax } = this;
  14840. blurUniforms.dTheta.value = radiansPerPixel;
  14841. blurUniforms.mipInt.value = _lodMax - lodIn;
  14842. const outputSize = this._sizeLods[ lodOut ];
  14843. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  14844. const y = 4 * ( this._cubeSize - outputSize );
  14845. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  14846. renderer.setRenderTarget( targetOut );
  14847. renderer.render( blurMesh, _flatCamera );
  14848. }
  14849. }
  14850. function _createPlanes( lodMax ) {
  14851. const lodPlanes = [];
  14852. const sizeLods = [];
  14853. const sigmas = [];
  14854. const lodMeshes = [];
  14855. let lod = lodMax;
  14856. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  14857. for ( let i = 0; i < totalLods; i ++ ) {
  14858. const sizeLod = Math.pow( 2, lod );
  14859. sizeLods.push( sizeLod );
  14860. let sigma = 1.0 / sizeLod;
  14861. if ( i > lodMax - LOD_MIN ) {
  14862. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  14863. } else if ( i === 0 ) {
  14864. sigma = 0;
  14865. }
  14866. sigmas.push( sigma );
  14867. const texelSize = 1.0 / ( sizeLod - 2 );
  14868. const min = - texelSize;
  14869. const max = 1 + texelSize;
  14870. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  14871. const cubeFaces = 6;
  14872. const vertices = 6;
  14873. const positionSize = 3;
  14874. const uvSize = 2;
  14875. const faceIndexSize = 1;
  14876. const position = new Float32Array( positionSize * vertices * cubeFaces );
  14877. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  14878. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  14879. for ( let face = 0; face < cubeFaces; face ++ ) {
  14880. const x = ( face % 3 ) * 2 / 3 - 1;
  14881. const y = face > 2 ? 0 : - 1;
  14882. const coordinates = [
  14883. x, y, 0,
  14884. x + 2 / 3, y, 0,
  14885. x + 2 / 3, y + 1, 0,
  14886. x, y, 0,
  14887. x + 2 / 3, y + 1, 0,
  14888. x, y + 1, 0
  14889. ];
  14890. const faceIdx = _faceLib[ face ];
  14891. position.set( coordinates, positionSize * vertices * faceIdx );
  14892. uv.set( uv1, uvSize * vertices * faceIdx );
  14893. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  14894. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  14895. }
  14896. const planes = new BufferGeometry();
  14897. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  14898. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  14899. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  14900. lodPlanes.push( planes );
  14901. lodMeshes.push( new Mesh( planes, null ) );
  14902. if ( lod > LOD_MIN ) {
  14903. lod --;
  14904. }
  14905. }
  14906. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  14907. }
  14908. function _createRenderTarget( width, height, params ) {
  14909. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  14910. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  14911. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  14912. cubeUVRenderTarget.texture.isPMREMTexture = true;
  14913. cubeUVRenderTarget.scissorTest = true;
  14914. return cubeUVRenderTarget;
  14915. }
  14916. function _setViewport( target, x, y, width, height ) {
  14917. target.viewport.set( x, y, width, height );
  14918. target.scissor.set( x, y, width, height );
  14919. }
  14920. function _getMaterial( type ) {
  14921. const material = new NodeMaterial();
  14922. material.depthTest = false;
  14923. material.depthWrite = false;
  14924. material.blending = NoBlending;
  14925. material.name = `PMREM_${ type }`;
  14926. return material;
  14927. }
  14928. function _getBlurShader( lodMax, width, height ) {
  14929. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  14930. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  14931. const dTheta = uniform( 0 );
  14932. const n = float( MAX_SAMPLES );
  14933. const latitudinal = uniform( 0 ); // false, bool
  14934. const samples = uniform( 1 ); // int
  14935. const envMap = texture( null );
  14936. const mipInt = uniform( 0 ); // int
  14937. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  14938. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  14939. const CUBEUV_MAX_MIP = float( lodMax );
  14940. const materialUniforms = {
  14941. n,
  14942. latitudinal,
  14943. weights,
  14944. poleAxis,
  14945. outputDirection,
  14946. dTheta,
  14947. samples,
  14948. envMap,
  14949. mipInt,
  14950. CUBEUV_TEXEL_WIDTH,
  14951. CUBEUV_TEXEL_HEIGHT,
  14952. CUBEUV_MAX_MIP
  14953. };
  14954. const material = _getMaterial( 'blur' );
  14955. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  14956. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  14957. return material;
  14958. }
  14959. function _getCubemapMaterial( envTexture ) {
  14960. const material = _getMaterial( 'cubemap' );
  14961. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  14962. return material;
  14963. }
  14964. function _getEquirectMaterial( envTexture ) {
  14965. const material = _getMaterial( 'equirect' );
  14966. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  14967. return material;
  14968. }
  14969. const rendererCache = new WeakMap();
  14970. const typeFromArray = new Map( [
  14971. [ Int8Array, 'int' ],
  14972. [ Int16Array, 'int' ],
  14973. [ Int32Array, 'int' ],
  14974. [ Uint8Array, 'uint' ],
  14975. [ Uint16Array, 'uint' ],
  14976. [ Uint32Array, 'uint' ],
  14977. [ Float32Array, 'float' ]
  14978. ] );
  14979. const toFloat = ( value ) => {
  14980. if ( /e/g.test( value ) ) {
  14981. return String( value ).replace( /\+/g, '' );
  14982. } else {
  14983. value = Number( value );
  14984. return value + ( value % 1 ? '' : '.0' );
  14985. }
  14986. };
  14987. class NodeBuilder {
  14988. constructor( object, renderer, parser ) {
  14989. this.object = object;
  14990. this.material = ( object && object.material ) || null;
  14991. this.geometry = ( object && object.geometry ) || null;
  14992. this.renderer = renderer;
  14993. this.parser = parser;
  14994. this.scene = null;
  14995. this.camera = null;
  14996. this.nodes = [];
  14997. this.sequentialNodes = [];
  14998. this.updateNodes = [];
  14999. this.updateBeforeNodes = [];
  15000. this.updateAfterNodes = [];
  15001. this.hashNodes = {};
  15002. this.monitor = null;
  15003. this.lightsNode = null;
  15004. this.environmentNode = null;
  15005. this.fogNode = null;
  15006. this.clippingContext = null;
  15007. this.vertexShader = null;
  15008. this.fragmentShader = null;
  15009. this.computeShader = null;
  15010. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  15011. this.flowCode = { vertex: '', fragment: '', compute: '' };
  15012. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  15013. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  15014. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  15015. this.bindingsIndexes = {};
  15016. this.bindGroups = null;
  15017. this.attributes = [];
  15018. this.bufferAttributes = [];
  15019. this.varyings = [];
  15020. this.codes = {};
  15021. this.vars = {};
  15022. this.flow = { code: '' };
  15023. this.chaining = [];
  15024. this.stack = stack();
  15025. this.stacks = [];
  15026. this.tab = '\t';
  15027. this.currentFunctionNode = null;
  15028. this.context = {
  15029. material: this.material
  15030. };
  15031. this.cache = new NodeCache();
  15032. this.globalCache = this.cache;
  15033. this.flowsData = new WeakMap();
  15034. this.shaderStage = null;
  15035. this.buildStage = null;
  15036. this.useComparisonMethod = false;
  15037. }
  15038. getBindGroupsCache() {
  15039. let bindGroupsCache = rendererCache.get( this.renderer );
  15040. if ( bindGroupsCache === undefined ) {
  15041. bindGroupsCache = new ChainMap();
  15042. rendererCache.set( this.renderer, bindGroupsCache );
  15043. }
  15044. return bindGroupsCache;
  15045. }
  15046. createRenderTarget( width, height, options ) {
  15047. return new RenderTarget( width, height, options );
  15048. }
  15049. createCubeRenderTarget( size, options ) {
  15050. return new CubeRenderTarget( size, options );
  15051. }
  15052. createPMREMGenerator() {
  15053. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  15054. return new PMREMGenerator( this.renderer );
  15055. }
  15056. includes( node ) {
  15057. return this.nodes.includes( node );
  15058. }
  15059. _getBindGroup( groupName, bindings ) {
  15060. const bindGroupsCache = this.getBindGroupsCache();
  15061. //
  15062. const bindingsArray = [];
  15063. let sharedGroup = true;
  15064. for ( const binding of bindings ) {
  15065. bindingsArray.push( binding );
  15066. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  15067. }
  15068. //
  15069. let bindGroup;
  15070. if ( sharedGroup ) {
  15071. bindGroup = bindGroupsCache.get( bindingsArray );
  15072. if ( bindGroup === undefined ) {
  15073. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  15074. bindGroupsCache.set( bindingsArray, bindGroup );
  15075. }
  15076. } else {
  15077. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  15078. }
  15079. return bindGroup;
  15080. }
  15081. getBindGroupArray( groupName, shaderStage ) {
  15082. const bindings = this.bindings[ shaderStage ];
  15083. let bindGroup = bindings[ groupName ];
  15084. if ( bindGroup === undefined ) {
  15085. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  15086. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  15087. }
  15088. bindings[ groupName ] = bindGroup = [];
  15089. }
  15090. return bindGroup;
  15091. }
  15092. getBindings() {
  15093. let bindingsGroups = this.bindGroups;
  15094. if ( bindingsGroups === null ) {
  15095. const groups = {};
  15096. const bindings = this.bindings;
  15097. for ( const shaderStage of shaderStages ) {
  15098. for ( const groupName in bindings[ shaderStage ] ) {
  15099. const uniforms = bindings[ shaderStage ][ groupName ];
  15100. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  15101. groupUniforms.push( ...uniforms );
  15102. }
  15103. }
  15104. bindingsGroups = [];
  15105. for ( const groupName in groups ) {
  15106. const group = groups[ groupName ];
  15107. const bindingsGroup = this._getBindGroup( groupName, group );
  15108. bindingsGroups.push( bindingsGroup );
  15109. }
  15110. this.bindGroups = bindingsGroups;
  15111. }
  15112. return bindingsGroups;
  15113. }
  15114. sortBindingGroups() {
  15115. const bindingsGroups = this.getBindings();
  15116. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  15117. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  15118. const bindingGroup = bindingsGroups[ i ];
  15119. this.bindingsIndexes[ bindingGroup.name ].group = i;
  15120. bindingGroup.index = i;
  15121. }
  15122. }
  15123. setHashNode( node, hash ) {
  15124. this.hashNodes[ hash ] = node;
  15125. }
  15126. addNode( node ) {
  15127. if ( this.nodes.includes( node ) === false ) {
  15128. this.nodes.push( node );
  15129. this.setHashNode( node, node.getHash( this ) );
  15130. }
  15131. }
  15132. addSequentialNode( node ) {
  15133. if ( this.sequentialNodes.includes( node ) === false ) {
  15134. this.sequentialNodes.push( node );
  15135. }
  15136. }
  15137. buildUpdateNodes() {
  15138. for ( const node of this.nodes ) {
  15139. const updateType = node.getUpdateType();
  15140. if ( updateType !== NodeUpdateType.NONE ) {
  15141. this.updateNodes.push( node.getSelf() );
  15142. }
  15143. }
  15144. for ( const node of this.sequentialNodes ) {
  15145. const updateBeforeType = node.getUpdateBeforeType();
  15146. const updateAfterType = node.getUpdateAfterType();
  15147. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  15148. this.updateBeforeNodes.push( node.getSelf() );
  15149. }
  15150. if ( updateAfterType !== NodeUpdateType.NONE ) {
  15151. this.updateAfterNodes.push( node.getSelf() );
  15152. }
  15153. }
  15154. }
  15155. get currentNode() {
  15156. return this.chaining[ this.chaining.length - 1 ];
  15157. }
  15158. isFilteredTexture( texture ) {
  15159. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  15160. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  15161. }
  15162. addChain( node ) {
  15163. /*
  15164. if ( this.chaining.indexOf( node ) !== - 1 ) {
  15165. console.warn( 'Recursive node: ', node );
  15166. }
  15167. */
  15168. this.chaining.push( node );
  15169. }
  15170. removeChain( node ) {
  15171. const lastChain = this.chaining.pop();
  15172. if ( lastChain !== node ) {
  15173. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  15174. }
  15175. }
  15176. getMethod( method ) {
  15177. return method;
  15178. }
  15179. getNodeFromHash( hash ) {
  15180. return this.hashNodes[ hash ];
  15181. }
  15182. addFlow( shaderStage, node ) {
  15183. this.flowNodes[ shaderStage ].push( node );
  15184. return node;
  15185. }
  15186. setContext( context ) {
  15187. this.context = context;
  15188. }
  15189. getContext() {
  15190. return this.context;
  15191. }
  15192. getSharedContext() {
  15193. ({ ...this.context });
  15194. return this.context;
  15195. }
  15196. setCache( cache ) {
  15197. this.cache = cache;
  15198. }
  15199. getCache() {
  15200. return this.cache;
  15201. }
  15202. getCacheFromNode( node, parent = true ) {
  15203. const data = this.getDataFromNode( node );
  15204. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  15205. return data.cache;
  15206. }
  15207. isAvailable( /*name*/ ) {
  15208. return false;
  15209. }
  15210. getVertexIndex() {
  15211. console.warn( 'Abstract function.' );
  15212. }
  15213. getInstanceIndex() {
  15214. console.warn( 'Abstract function.' );
  15215. }
  15216. getDrawIndex() {
  15217. console.warn( 'Abstract function.' );
  15218. }
  15219. getFrontFacing() {
  15220. console.warn( 'Abstract function.' );
  15221. }
  15222. getFragCoord() {
  15223. console.warn( 'Abstract function.' );
  15224. }
  15225. isFlipY() {
  15226. return false;
  15227. }
  15228. increaseUsage( node ) {
  15229. const nodeData = this.getDataFromNode( node );
  15230. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  15231. return nodeData.usageCount;
  15232. }
  15233. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  15234. console.warn( 'Abstract function.' );
  15235. }
  15236. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  15237. console.warn( 'Abstract function.' );
  15238. }
  15239. generateConst( type, value = null ) {
  15240. if ( value === null ) {
  15241. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  15242. else if ( type === 'bool' ) value = false;
  15243. else if ( type === 'color' ) value = new Color();
  15244. else if ( type === 'vec2' ) value = new Vector2();
  15245. else if ( type === 'vec3' ) value = new Vector3();
  15246. else if ( type === 'vec4' ) value = new Vector4();
  15247. }
  15248. if ( type === 'float' ) return toFloat( value );
  15249. if ( type === 'int' ) return `${ Math.round( value ) }`;
  15250. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  15251. if ( type === 'bool' ) return value ? 'true' : 'false';
  15252. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  15253. const typeLength = this.getTypeLength( type );
  15254. const componentType = this.getComponentType( type );
  15255. const generateConst = value => this.generateConst( componentType, value );
  15256. if ( typeLength === 2 ) {
  15257. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  15258. } else if ( typeLength === 3 ) {
  15259. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  15260. } else if ( typeLength === 4 ) {
  15261. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  15262. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  15263. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  15264. } else if ( typeLength > 4 ) {
  15265. return `${ this.getType( type ) }()`;
  15266. }
  15267. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  15268. }
  15269. getType( type ) {
  15270. if ( type === 'color' ) return 'vec3';
  15271. return type;
  15272. }
  15273. hasGeometryAttribute( name ) {
  15274. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  15275. }
  15276. getAttribute( name, type ) {
  15277. const attributes = this.attributes;
  15278. // find attribute
  15279. for ( const attribute of attributes ) {
  15280. if ( attribute.name === name ) {
  15281. return attribute;
  15282. }
  15283. }
  15284. // create a new if no exist
  15285. const attribute = new NodeAttribute( name, type );
  15286. attributes.push( attribute );
  15287. return attribute;
  15288. }
  15289. getPropertyName( node/*, shaderStage*/ ) {
  15290. return node.name;
  15291. }
  15292. isVector( type ) {
  15293. return /vec\d/.test( type );
  15294. }
  15295. isMatrix( type ) {
  15296. return /mat\d/.test( type );
  15297. }
  15298. isReference( type ) {
  15299. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  15300. }
  15301. needsToWorkingColorSpace( /*texture*/ ) {
  15302. return false;
  15303. }
  15304. getComponentTypeFromTexture( texture ) {
  15305. const type = texture.type;
  15306. if ( texture.isDataTexture ) {
  15307. if ( type === IntType ) return 'int';
  15308. if ( type === UnsignedIntType ) return 'uint';
  15309. }
  15310. return 'float';
  15311. }
  15312. getElementType( type ) {
  15313. if ( type === 'mat2' ) return 'vec2';
  15314. if ( type === 'mat3' ) return 'vec3';
  15315. if ( type === 'mat4' ) return 'vec4';
  15316. return this.getComponentType( type );
  15317. }
  15318. getComponentType( type ) {
  15319. type = this.getVectorType( type );
  15320. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  15321. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  15322. if ( componentType === null ) return null;
  15323. if ( componentType[ 1 ] === 'b' ) return 'bool';
  15324. if ( componentType[ 1 ] === 'i' ) return 'int';
  15325. if ( componentType[ 1 ] === 'u' ) return 'uint';
  15326. return 'float';
  15327. }
  15328. getVectorType( type ) {
  15329. if ( type === 'color' ) return 'vec3';
  15330. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  15331. return type;
  15332. }
  15333. getTypeFromLength( length, componentType = 'float' ) {
  15334. if ( length === 1 ) return componentType;
  15335. const baseType = getTypeFromLength( length );
  15336. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  15337. return prefix + baseType;
  15338. }
  15339. getTypeFromArray( array ) {
  15340. return typeFromArray.get( array.constructor );
  15341. }
  15342. getTypeFromAttribute( attribute ) {
  15343. let dataAttribute = attribute;
  15344. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  15345. const array = dataAttribute.array;
  15346. const itemSize = attribute.itemSize;
  15347. const normalized = attribute.normalized;
  15348. let arrayType;
  15349. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  15350. arrayType = this.getTypeFromArray( array );
  15351. }
  15352. return this.getTypeFromLength( itemSize, arrayType );
  15353. }
  15354. getTypeLength( type ) {
  15355. const vecType = this.getVectorType( type );
  15356. const vecNum = /vec([2-4])/.exec( vecType );
  15357. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  15358. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  15359. if ( /mat2/.test( type ) === true ) return 4;
  15360. if ( /mat3/.test( type ) === true ) return 9;
  15361. if ( /mat4/.test( type ) === true ) return 16;
  15362. return 0;
  15363. }
  15364. getVectorFromMatrix( type ) {
  15365. return type.replace( 'mat', 'vec' );
  15366. }
  15367. changeComponentType( type, newComponentType ) {
  15368. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  15369. }
  15370. getIntegerType( type ) {
  15371. const componentType = this.getComponentType( type );
  15372. if ( componentType === 'int' || componentType === 'uint' ) return type;
  15373. return this.changeComponentType( type, 'int' );
  15374. }
  15375. addStack() {
  15376. this.stack = stack( this.stack );
  15377. this.stacks.push( getCurrentStack() || this.stack );
  15378. setCurrentStack( this.stack );
  15379. return this.stack;
  15380. }
  15381. removeStack() {
  15382. const lastStack = this.stack;
  15383. this.stack = lastStack.parent;
  15384. setCurrentStack( this.stacks.pop() );
  15385. return lastStack;
  15386. }
  15387. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  15388. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  15389. let nodeData = cache.getData( node );
  15390. if ( nodeData === undefined ) {
  15391. nodeData = {};
  15392. cache.setData( node, nodeData );
  15393. }
  15394. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  15395. return nodeData[ shaderStage ];
  15396. }
  15397. getNodeProperties( node, shaderStage = 'any' ) {
  15398. const nodeData = this.getDataFromNode( node, shaderStage );
  15399. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  15400. }
  15401. getBufferAttributeFromNode( node, type ) {
  15402. const nodeData = this.getDataFromNode( node );
  15403. let bufferAttribute = nodeData.bufferAttribute;
  15404. if ( bufferAttribute === undefined ) {
  15405. const index = this.uniforms.index ++;
  15406. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  15407. this.bufferAttributes.push( bufferAttribute );
  15408. nodeData.bufferAttribute = bufferAttribute;
  15409. }
  15410. return bufferAttribute;
  15411. }
  15412. getStructTypeFromNode( node, shaderStage = this.shaderStage ) {
  15413. const nodeData = this.getDataFromNode( node, shaderStage );
  15414. if ( nodeData.structType === undefined ) {
  15415. const index = this.structs.index ++;
  15416. node.name = `StructType${ index }`;
  15417. this.structs[ shaderStage ].push( node );
  15418. nodeData.structType = node;
  15419. }
  15420. return node;
  15421. }
  15422. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  15423. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  15424. let nodeUniform = nodeData.uniform;
  15425. if ( nodeUniform === undefined ) {
  15426. const index = this.uniforms.index ++;
  15427. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  15428. this.uniforms[ shaderStage ].push( nodeUniform );
  15429. nodeData.uniform = nodeUniform;
  15430. }
  15431. return nodeUniform;
  15432. }
  15433. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  15434. const nodeData = this.getDataFromNode( node, shaderStage );
  15435. let nodeVar = nodeData.variable;
  15436. if ( nodeVar === undefined ) {
  15437. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  15438. if ( name === null ) name = 'nodeVar' + vars.length;
  15439. nodeVar = new NodeVar( name, type );
  15440. vars.push( nodeVar );
  15441. nodeData.variable = nodeVar;
  15442. }
  15443. return nodeVar;
  15444. }
  15445. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  15446. const nodeData = this.getDataFromNode( node, 'any' );
  15447. let nodeVarying = nodeData.varying;
  15448. if ( nodeVarying === undefined ) {
  15449. const varyings = this.varyings;
  15450. const index = varyings.length;
  15451. if ( name === null ) name = 'nodeVarying' + index;
  15452. nodeVarying = new NodeVarying( name, type );
  15453. varyings.push( nodeVarying );
  15454. nodeData.varying = nodeVarying;
  15455. }
  15456. return nodeVarying;
  15457. }
  15458. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  15459. const nodeData = this.getDataFromNode( node );
  15460. let nodeCode = nodeData.code;
  15461. if ( nodeCode === undefined ) {
  15462. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  15463. const index = codes.length;
  15464. nodeCode = new NodeCode( 'nodeCode' + index, type );
  15465. codes.push( nodeCode );
  15466. nodeData.code = nodeCode;
  15467. }
  15468. return nodeCode;
  15469. }
  15470. addFlowCodeHierarchy( node, nodeBlock ) {
  15471. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  15472. let needsFlowCode = true;
  15473. let nodeBlockHierarchy = nodeBlock;
  15474. while ( nodeBlockHierarchy ) {
  15475. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  15476. needsFlowCode = false;
  15477. break;
  15478. }
  15479. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  15480. }
  15481. if ( needsFlowCode ) {
  15482. for ( const flowCode of flowCodes ) {
  15483. this.addLineFlowCode( flowCode );
  15484. }
  15485. }
  15486. }
  15487. addLineFlowCodeBlock( node, code, nodeBlock ) {
  15488. const nodeData = this.getDataFromNode( node );
  15489. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  15490. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  15491. flowCodes.push( code );
  15492. codeBlock.set( nodeBlock, true );
  15493. }
  15494. addLineFlowCode( code, node = null ) {
  15495. if ( code === '' ) return this;
  15496. if ( node !== null && this.context.nodeBlock ) {
  15497. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  15498. }
  15499. code = this.tab + code;
  15500. if ( ! /;\s*$/.test( code ) ) {
  15501. code = code + ';\n';
  15502. }
  15503. this.flow.code += code;
  15504. return this;
  15505. }
  15506. addFlowCode( code ) {
  15507. this.flow.code += code;
  15508. return this;
  15509. }
  15510. addFlowTab() {
  15511. this.tab += '\t';
  15512. return this;
  15513. }
  15514. removeFlowTab() {
  15515. this.tab = this.tab.slice( 0, - 1 );
  15516. return this;
  15517. }
  15518. getFlowData( node/*, shaderStage*/ ) {
  15519. return this.flowsData.get( node );
  15520. }
  15521. flowNode( node ) {
  15522. const output = node.getNodeType( this );
  15523. const flowData = this.flowChildNode( node, output );
  15524. this.flowsData.set( node, flowData );
  15525. return flowData;
  15526. }
  15527. buildFunctionNode( shaderNode ) {
  15528. const fn = new FunctionNode();
  15529. const previous = this.currentFunctionNode;
  15530. this.currentFunctionNode = fn;
  15531. fn.code = this.buildFunctionCode( shaderNode );
  15532. this.currentFunctionNode = previous;
  15533. return fn;
  15534. }
  15535. flowShaderNode( shaderNode ) {
  15536. const layout = shaderNode.layout;
  15537. const inputs = {
  15538. [ Symbol.iterator ]() {
  15539. let index = 0;
  15540. const values = Object.values( this );
  15541. return {
  15542. next: () => ( {
  15543. value: values[ index ],
  15544. done: index ++ >= values.length
  15545. } )
  15546. };
  15547. }
  15548. };
  15549. for ( const input of layout.inputs ) {
  15550. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  15551. }
  15552. //
  15553. shaderNode.layout = null;
  15554. const callNode = shaderNode.call( inputs );
  15555. const flowData = this.flowStagesNode( callNode, layout.type );
  15556. shaderNode.layout = layout;
  15557. return flowData;
  15558. }
  15559. flowStagesNode( node, output = null ) {
  15560. const previousFlow = this.flow;
  15561. const previousVars = this.vars;
  15562. const previousCache = this.cache;
  15563. const previousBuildStage = this.buildStage;
  15564. const previousStack = this.stack;
  15565. const flow = {
  15566. code: ''
  15567. };
  15568. this.flow = flow;
  15569. this.vars = {};
  15570. this.cache = new NodeCache();
  15571. this.stack = stack();
  15572. for ( const buildStage of defaultBuildStages ) {
  15573. this.setBuildStage( buildStage );
  15574. flow.result = node.build( this, output );
  15575. }
  15576. flow.vars = this.getVars( this.shaderStage );
  15577. this.flow = previousFlow;
  15578. this.vars = previousVars;
  15579. this.cache = previousCache;
  15580. this.stack = previousStack;
  15581. this.setBuildStage( previousBuildStage );
  15582. return flow;
  15583. }
  15584. getFunctionOperator() {
  15585. return null;
  15586. }
  15587. flowChildNode( node, output = null ) {
  15588. const previousFlow = this.flow;
  15589. const flow = {
  15590. code: ''
  15591. };
  15592. this.flow = flow;
  15593. flow.result = node.build( this, output );
  15594. this.flow = previousFlow;
  15595. return flow;
  15596. }
  15597. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  15598. const previousShaderStage = this.shaderStage;
  15599. this.setShaderStage( shaderStage );
  15600. const flowData = this.flowChildNode( node, output );
  15601. if ( propertyName !== null ) {
  15602. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  15603. }
  15604. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  15605. this.setShaderStage( previousShaderStage );
  15606. return flowData;
  15607. }
  15608. getAttributesArray() {
  15609. return this.attributes.concat( this.bufferAttributes );
  15610. }
  15611. getAttributes( /*shaderStage*/ ) {
  15612. console.warn( 'Abstract function.' );
  15613. }
  15614. getVaryings( /*shaderStage*/ ) {
  15615. console.warn( 'Abstract function.' );
  15616. }
  15617. getVar( type, name ) {
  15618. return `${ this.getType( type ) } ${ name }`;
  15619. }
  15620. getVars( shaderStage ) {
  15621. let snippet = '';
  15622. const vars = this.vars[ shaderStage ];
  15623. if ( vars !== undefined ) {
  15624. for ( const variable of vars ) {
  15625. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  15626. }
  15627. }
  15628. return snippet;
  15629. }
  15630. getUniforms( /*shaderStage*/ ) {
  15631. console.warn( 'Abstract function.' );
  15632. }
  15633. getCodes( shaderStage ) {
  15634. const codes = this.codes[ shaderStage ];
  15635. let code = '';
  15636. if ( codes !== undefined ) {
  15637. for ( const nodeCode of codes ) {
  15638. code += nodeCode.code + '\n';
  15639. }
  15640. }
  15641. return code;
  15642. }
  15643. getHash() {
  15644. return this.vertexShader + this.fragmentShader + this.computeShader;
  15645. }
  15646. setShaderStage( shaderStage ) {
  15647. this.shaderStage = shaderStage;
  15648. }
  15649. getShaderStage() {
  15650. return this.shaderStage;
  15651. }
  15652. setBuildStage( buildStage ) {
  15653. this.buildStage = buildStage;
  15654. }
  15655. getBuildStage() {
  15656. return this.buildStage;
  15657. }
  15658. buildCode() {
  15659. console.warn( 'Abstract function.' );
  15660. }
  15661. build() {
  15662. const { object, material, renderer } = this;
  15663. if ( material !== null ) {
  15664. let nodeMaterial = renderer.library.fromMaterial( material );
  15665. if ( nodeMaterial === null ) {
  15666. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  15667. nodeMaterial = new NodeMaterial();
  15668. }
  15669. nodeMaterial.build( this );
  15670. } else {
  15671. this.addFlow( 'compute', object );
  15672. }
  15673. // setup() -> stage 1: create possible new nodes and returns an output reference node
  15674. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  15675. // generate() -> stage 3: generate shader
  15676. for ( const buildStage of defaultBuildStages ) {
  15677. this.setBuildStage( buildStage );
  15678. if ( this.context.vertex && this.context.vertex.isNode ) {
  15679. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  15680. }
  15681. for ( const shaderStage of shaderStages ) {
  15682. this.setShaderStage( shaderStage );
  15683. const flowNodes = this.flowNodes[ shaderStage ];
  15684. for ( const node of flowNodes ) {
  15685. if ( buildStage === 'generate' ) {
  15686. this.flowNode( node );
  15687. } else {
  15688. node.build( this );
  15689. }
  15690. }
  15691. }
  15692. }
  15693. this.setBuildStage( null );
  15694. this.setShaderStage( null );
  15695. // stage 4: build code for a specific output
  15696. this.buildCode();
  15697. this.buildUpdateNodes();
  15698. return this;
  15699. }
  15700. getNodeUniform( uniformNode, type ) {
  15701. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  15702. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  15703. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  15704. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  15705. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  15706. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  15707. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  15708. throw new Error( `Uniform "${type}" not declared.` );
  15709. }
  15710. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  15711. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  15712. }
  15713. format( snippet, fromType, toType ) {
  15714. fromType = this.getVectorType( fromType );
  15715. toType = this.getVectorType( toType );
  15716. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  15717. return snippet;
  15718. }
  15719. const fromTypeLength = this.getTypeLength( fromType );
  15720. const toTypeLength = this.getTypeLength( toType );
  15721. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  15722. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  15723. }
  15724. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  15725. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  15726. }
  15727. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  15728. // @TODO: ignore for now
  15729. return snippet;
  15730. }
  15731. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  15732. // @TODO: ignore for now
  15733. return snippet;
  15734. }
  15735. if ( fromTypeLength === toTypeLength ) {
  15736. return `${ this.getType( toType ) }( ${ snippet } )`;
  15737. }
  15738. if ( fromTypeLength > toTypeLength ) {
  15739. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  15740. }
  15741. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  15742. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  15743. }
  15744. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  15745. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  15746. }
  15747. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  15748. // convert a number value to vector type, e.g:
  15749. // vec3( 1u ) -> vec3( float( 1u ) )
  15750. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  15751. }
  15752. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  15753. }
  15754. getSignature() {
  15755. return `// Three.js r${ REVISION } - Node System\n`;
  15756. }
  15757. }
  15758. class NodeFrame {
  15759. constructor() {
  15760. this.time = 0;
  15761. this.deltaTime = 0;
  15762. this.frameId = 0;
  15763. this.renderId = 0;
  15764. this.startTime = null;
  15765. this.updateMap = new WeakMap();
  15766. this.updateBeforeMap = new WeakMap();
  15767. this.updateAfterMap = new WeakMap();
  15768. this.renderer = null;
  15769. this.material = null;
  15770. this.camera = null;
  15771. this.object = null;
  15772. this.scene = null;
  15773. }
  15774. _getMaps( referenceMap, nodeRef ) {
  15775. let maps = referenceMap.get( nodeRef );
  15776. if ( maps === undefined ) {
  15777. maps = {
  15778. renderMap: new WeakMap(),
  15779. frameMap: new WeakMap()
  15780. };
  15781. referenceMap.set( nodeRef, maps );
  15782. }
  15783. return maps;
  15784. }
  15785. updateBeforeNode( node ) {
  15786. const updateType = node.getUpdateBeforeType();
  15787. const reference = node.updateReference( this );
  15788. if ( updateType === NodeUpdateType.FRAME ) {
  15789. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  15790. if ( frameMap.get( reference ) !== this.frameId ) {
  15791. if ( node.updateBefore( this ) !== false ) {
  15792. frameMap.set( reference, this.frameId );
  15793. }
  15794. }
  15795. } else if ( updateType === NodeUpdateType.RENDER ) {
  15796. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  15797. if ( renderMap.get( reference ) !== this.renderId ) {
  15798. if ( node.updateBefore( this ) !== false ) {
  15799. renderMap.set( reference, this.renderId );
  15800. }
  15801. }
  15802. } else if ( updateType === NodeUpdateType.OBJECT ) {
  15803. node.updateBefore( this );
  15804. }
  15805. }
  15806. updateAfterNode( node ) {
  15807. const updateType = node.getUpdateAfterType();
  15808. const reference = node.updateReference( this );
  15809. if ( updateType === NodeUpdateType.FRAME ) {
  15810. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  15811. if ( frameMap.get( reference ) !== this.frameId ) {
  15812. if ( node.updateAfter( this ) !== false ) {
  15813. frameMap.set( reference, this.frameId );
  15814. }
  15815. }
  15816. } else if ( updateType === NodeUpdateType.RENDER ) {
  15817. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  15818. if ( renderMap.get( reference ) !== this.renderId ) {
  15819. if ( node.updateAfter( this ) !== false ) {
  15820. renderMap.set( reference, this.renderId );
  15821. }
  15822. }
  15823. } else if ( updateType === NodeUpdateType.OBJECT ) {
  15824. node.updateAfter( this );
  15825. }
  15826. }
  15827. updateNode( node ) {
  15828. const updateType = node.getUpdateType();
  15829. const reference = node.updateReference( this );
  15830. if ( updateType === NodeUpdateType.FRAME ) {
  15831. const { frameMap } = this._getMaps( this.updateMap, reference );
  15832. if ( frameMap.get( reference ) !== this.frameId ) {
  15833. if ( node.update( this ) !== false ) {
  15834. frameMap.set( reference, this.frameId );
  15835. }
  15836. }
  15837. } else if ( updateType === NodeUpdateType.RENDER ) {
  15838. const { renderMap } = this._getMaps( this.updateMap, reference );
  15839. if ( renderMap.get( reference ) !== this.renderId ) {
  15840. if ( node.update( this ) !== false ) {
  15841. renderMap.set( reference, this.renderId );
  15842. }
  15843. }
  15844. } else if ( updateType === NodeUpdateType.OBJECT ) {
  15845. node.update( this );
  15846. }
  15847. }
  15848. update() {
  15849. this.frameId ++;
  15850. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  15851. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  15852. this.lastTime = performance.now();
  15853. this.time += this.deltaTime;
  15854. }
  15855. }
  15856. class NodeFunctionInput {
  15857. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  15858. this.type = type;
  15859. this.name = name;
  15860. this.count = count;
  15861. this.qualifier = qualifier;
  15862. this.isConst = isConst;
  15863. }
  15864. }
  15865. NodeFunctionInput.isNodeFunctionInput = true;
  15866. class DirectionalLightNode extends AnalyticLightNode {
  15867. static get type() {
  15868. return 'DirectionalLightNode';
  15869. }
  15870. constructor( light = null ) {
  15871. super( light );
  15872. }
  15873. setup( builder ) {
  15874. super.setup( builder );
  15875. const lightingModel = builder.context.lightingModel;
  15876. const lightColor = this.colorNode;
  15877. const lightDirection = lightTargetDirection( this.light );
  15878. const reflectedLight = builder.context.reflectedLight;
  15879. lightingModel.direct( {
  15880. lightDirection,
  15881. lightColor,
  15882. reflectedLight
  15883. }, builder.stack, builder );
  15884. }
  15885. }
  15886. const _matrix41 = /*@__PURE__*/ new Matrix4();
  15887. const _matrix42 = /*@__PURE__*/ new Matrix4();
  15888. let ltcLib = null;
  15889. class RectAreaLightNode extends AnalyticLightNode {
  15890. static get type() {
  15891. return 'RectAreaLightNode';
  15892. }
  15893. constructor( light = null ) {
  15894. super( light );
  15895. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  15896. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  15897. this.updateType = NodeUpdateType.RENDER;
  15898. }
  15899. update( frame ) {
  15900. super.update( frame );
  15901. const { light } = this;
  15902. const viewMatrix = frame.camera.matrixWorldInverse;
  15903. _matrix42.identity();
  15904. _matrix41.copy( light.matrixWorld );
  15905. _matrix41.premultiply( viewMatrix );
  15906. _matrix42.extractRotation( _matrix41 );
  15907. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  15908. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  15909. this.halfWidth.value.applyMatrix4( _matrix42 );
  15910. this.halfHeight.value.applyMatrix4( _matrix42 );
  15911. }
  15912. setup( builder ) {
  15913. super.setup( builder );
  15914. let ltc_1, ltc_2;
  15915. if ( builder.isAvailable( 'float32Filterable' ) ) {
  15916. ltc_1 = texture( ltcLib.LTC_FLOAT_1 );
  15917. ltc_2 = texture( ltcLib.LTC_FLOAT_2 );
  15918. } else {
  15919. ltc_1 = texture( ltcLib.LTC_HALF_1 );
  15920. ltc_2 = texture( ltcLib.LTC_HALF_2 );
  15921. }
  15922. const { colorNode, light } = this;
  15923. const lightingModel = builder.context.lightingModel;
  15924. const lightPosition = lightViewPosition( light );
  15925. const reflectedLight = builder.context.reflectedLight;
  15926. lightingModel.directRectArea( {
  15927. lightColor: colorNode,
  15928. lightPosition,
  15929. halfWidth: this.halfWidth,
  15930. halfHeight: this.halfHeight,
  15931. reflectedLight,
  15932. ltc_1,
  15933. ltc_2
  15934. }, builder.stack, builder );
  15935. }
  15936. static setLTC( ltc ) {
  15937. ltcLib = ltc;
  15938. }
  15939. }
  15940. class SpotLightNode extends AnalyticLightNode {
  15941. static get type() {
  15942. return 'SpotLightNode';
  15943. }
  15944. constructor( light = null ) {
  15945. super( light );
  15946. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  15947. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  15948. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  15949. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  15950. }
  15951. update( frame ) {
  15952. super.update( frame );
  15953. const { light } = this;
  15954. this.coneCosNode.value = Math.cos( light.angle );
  15955. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  15956. this.cutoffDistanceNode.value = light.distance;
  15957. this.decayExponentNode.value = light.decay;
  15958. }
  15959. getSpotAttenuation( angleCosine ) {
  15960. const { coneCosNode, penumbraCosNode } = this;
  15961. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  15962. }
  15963. setup( builder ) {
  15964. super.setup( builder );
  15965. const lightingModel = builder.context.lightingModel;
  15966. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  15967. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  15968. const lightDirection = lVector.normalize();
  15969. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  15970. const spotAttenuation = this.getSpotAttenuation( angleCos );
  15971. const lightDistance = lVector.length();
  15972. const lightAttenuation = getDistanceAttenuation( {
  15973. lightDistance,
  15974. cutoffDistance: cutoffDistanceNode,
  15975. decayExponent: decayExponentNode
  15976. } );
  15977. const lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  15978. const reflectedLight = builder.context.reflectedLight;
  15979. lightingModel.direct( {
  15980. lightDirection,
  15981. lightColor,
  15982. reflectedLight
  15983. }, builder.stack, builder );
  15984. }
  15985. }
  15986. class IESSpotLightNode extends SpotLightNode {
  15987. static get type() {
  15988. return 'IESSpotLightNode';
  15989. }
  15990. getSpotAttenuation( angleCosine ) {
  15991. const iesMap = this.light.iesMap;
  15992. let spotAttenuation = null;
  15993. if ( iesMap && iesMap.isTexture === true ) {
  15994. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  15995. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  15996. } else {
  15997. spotAttenuation = super.getSpotAttenuation( angleCosine );
  15998. }
  15999. return spotAttenuation;
  16000. }
  16001. }
  16002. class AmbientLightNode extends AnalyticLightNode {
  16003. static get type() {
  16004. return 'AmbientLightNode';
  16005. }
  16006. constructor( light = null ) {
  16007. super( light );
  16008. }
  16009. setup( { context } ) {
  16010. context.irradiance.addAssign( this.colorNode );
  16011. }
  16012. }
  16013. class HemisphereLightNode extends AnalyticLightNode {
  16014. static get type() {
  16015. return 'HemisphereLightNode';
  16016. }
  16017. constructor( light = null ) {
  16018. super( light );
  16019. this.lightPositionNode = lightPosition( light );
  16020. this.lightDirectionNode = this.lightPositionNode.normalize();
  16021. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  16022. }
  16023. update( frame ) {
  16024. const { light } = this;
  16025. super.update( frame );
  16026. this.lightPositionNode.object3d = light;
  16027. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  16028. }
  16029. setup( builder ) {
  16030. const { colorNode, groundColorNode, lightDirectionNode } = this;
  16031. const dotNL = normalView.dot( lightDirectionNode );
  16032. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  16033. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  16034. builder.context.irradiance.addAssign( irradiance );
  16035. }
  16036. }
  16037. class LightProbeNode extends AnalyticLightNode {
  16038. static get type() {
  16039. return 'LightProbeNode';
  16040. }
  16041. constructor( light = null ) {
  16042. super( light );
  16043. const array = [];
  16044. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  16045. this.lightProbe = uniformArray( array );
  16046. }
  16047. update( frame ) {
  16048. const { light } = this;
  16049. super.update( frame );
  16050. //
  16051. for ( let i = 0; i < 9; i ++ ) {
  16052. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  16053. }
  16054. }
  16055. setup( builder ) {
  16056. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  16057. builder.context.irradiance.addAssign( irradiance );
  16058. }
  16059. }
  16060. class NodeParser {
  16061. parseFunction( /*source*/ ) {
  16062. console.warn( 'Abstract function.' );
  16063. }
  16064. }
  16065. class NodeFunction {
  16066. constructor( type, inputs, name = '', precision = '' ) {
  16067. this.type = type;
  16068. this.inputs = inputs;
  16069. this.name = name;
  16070. this.precision = precision;
  16071. }
  16072. getCode( /*name = this.name*/ ) {
  16073. console.warn( 'Abstract function.' );
  16074. }
  16075. }
  16076. NodeFunction.isNodeFunction = true;
  16077. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  16078. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  16079. const pragmaMain = '#pragma main';
  16080. const parse$1 = ( source ) => {
  16081. source = source.trim();
  16082. const pragmaMainIndex = source.indexOf( pragmaMain );
  16083. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  16084. const declaration = mainCode.match( declarationRegexp$1 );
  16085. if ( declaration !== null && declaration.length === 5 ) {
  16086. // tokenizer
  16087. const inputsCode = declaration[ 4 ];
  16088. const propsMatches = [];
  16089. let nameMatch = null;
  16090. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  16091. propsMatches.push( nameMatch );
  16092. }
  16093. // parser
  16094. const inputs = [];
  16095. let i = 0;
  16096. while ( i < propsMatches.length ) {
  16097. const isConst = propsMatches[ i ][ 0 ] === 'const';
  16098. if ( isConst === true ) {
  16099. i ++;
  16100. }
  16101. let qualifier = propsMatches[ i ][ 0 ];
  16102. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  16103. i ++;
  16104. } else {
  16105. qualifier = '';
  16106. }
  16107. const type = propsMatches[ i ++ ][ 0 ];
  16108. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  16109. if ( Number.isNaN( count ) === false ) i ++;
  16110. else count = null;
  16111. const name = propsMatches[ i ++ ][ 0 ];
  16112. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  16113. }
  16114. //
  16115. const blockCode = mainCode.substring( declaration[ 0 ].length );
  16116. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  16117. const type = declaration[ 2 ];
  16118. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  16119. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  16120. return {
  16121. type,
  16122. inputs,
  16123. name,
  16124. precision,
  16125. inputsCode,
  16126. blockCode,
  16127. headerCode
  16128. };
  16129. } else {
  16130. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  16131. }
  16132. };
  16133. class GLSLNodeFunction extends NodeFunction {
  16134. constructor( source ) {
  16135. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  16136. super( type, inputs, name, precision );
  16137. this.inputsCode = inputsCode;
  16138. this.blockCode = blockCode;
  16139. this.headerCode = headerCode;
  16140. }
  16141. getCode( name = this.name ) {
  16142. let code;
  16143. const blockCode = this.blockCode;
  16144. if ( blockCode !== '' ) {
  16145. const { type, inputsCode, headerCode, precision } = this;
  16146. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  16147. if ( precision !== '' ) {
  16148. declarationCode = `${ precision } ${ declarationCode }`;
  16149. }
  16150. code = headerCode + declarationCode + blockCode;
  16151. } else {
  16152. // interface function
  16153. code = '';
  16154. }
  16155. return code;
  16156. }
  16157. }
  16158. class GLSLNodeParser extends NodeParser {
  16159. parseFunction( source ) {
  16160. return new GLSLNodeFunction( source );
  16161. }
  16162. }
  16163. const outputNodeMap = new WeakMap();
  16164. class Nodes extends DataMap {
  16165. constructor( renderer, backend ) {
  16166. super();
  16167. this.renderer = renderer;
  16168. this.backend = backend;
  16169. this.nodeFrame = new NodeFrame();
  16170. this.nodeBuilderCache = new Map();
  16171. this.callHashCache = new ChainMap();
  16172. this.groupsData = new ChainMap();
  16173. }
  16174. updateGroup( nodeUniformsGroup ) {
  16175. const groupNode = nodeUniformsGroup.groupNode;
  16176. const name = groupNode.name;
  16177. // objectGroup is every updated
  16178. if ( name === objectGroup.name ) return true;
  16179. // renderGroup is updated once per render/compute call
  16180. if ( name === renderGroup.name ) {
  16181. const uniformsGroupData = this.get( nodeUniformsGroup );
  16182. const renderId = this.nodeFrame.renderId;
  16183. if ( uniformsGroupData.renderId !== renderId ) {
  16184. uniformsGroupData.renderId = renderId;
  16185. return true;
  16186. }
  16187. return false;
  16188. }
  16189. // frameGroup is updated once per frame
  16190. if ( name === frameGroup.name ) {
  16191. const uniformsGroupData = this.get( nodeUniformsGroup );
  16192. const frameId = this.nodeFrame.frameId;
  16193. if ( uniformsGroupData.frameId !== frameId ) {
  16194. uniformsGroupData.frameId = frameId;
  16195. return true;
  16196. }
  16197. return false;
  16198. }
  16199. // other groups are updated just when groupNode.needsUpdate is true
  16200. const groupChain = [ groupNode, nodeUniformsGroup ];
  16201. let groupData = this.groupsData.get( groupChain );
  16202. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  16203. if ( groupData.version !== groupNode.version ) {
  16204. groupData.version = groupNode.version;
  16205. return true;
  16206. }
  16207. return false;
  16208. }
  16209. getForRenderCacheKey( renderObject ) {
  16210. return renderObject.initialCacheKey;
  16211. }
  16212. getForRender( renderObject ) {
  16213. const renderObjectData = this.get( renderObject );
  16214. let nodeBuilderState = renderObjectData.nodeBuilderState;
  16215. if ( nodeBuilderState === undefined ) {
  16216. const { nodeBuilderCache } = this;
  16217. const cacheKey = this.getForRenderCacheKey( renderObject );
  16218. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  16219. if ( nodeBuilderState === undefined ) {
  16220. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  16221. nodeBuilder.scene = renderObject.scene;
  16222. nodeBuilder.material = renderObject.material;
  16223. nodeBuilder.camera = renderObject.camera;
  16224. nodeBuilder.context.material = renderObject.material;
  16225. nodeBuilder.lightsNode = renderObject.lightsNode;
  16226. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  16227. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  16228. nodeBuilder.clippingContext = renderObject.clippingContext;
  16229. nodeBuilder.build();
  16230. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  16231. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  16232. }
  16233. nodeBuilderState.usedTimes ++;
  16234. renderObjectData.nodeBuilderState = nodeBuilderState;
  16235. }
  16236. return nodeBuilderState;
  16237. }
  16238. delete( object ) {
  16239. if ( object.isRenderObject ) {
  16240. const nodeBuilderState = this.get( object ).nodeBuilderState;
  16241. nodeBuilderState.usedTimes --;
  16242. if ( nodeBuilderState.usedTimes === 0 ) {
  16243. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  16244. }
  16245. }
  16246. return super.delete( object );
  16247. }
  16248. getForCompute( computeNode ) {
  16249. const computeData = this.get( computeNode );
  16250. let nodeBuilderState = computeData.nodeBuilderState;
  16251. if ( nodeBuilderState === undefined ) {
  16252. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  16253. nodeBuilder.build();
  16254. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  16255. computeData.nodeBuilderState = nodeBuilderState;
  16256. }
  16257. return nodeBuilderState;
  16258. }
  16259. _createNodeBuilderState( nodeBuilder ) {
  16260. return new NodeBuilderState(
  16261. nodeBuilder.vertexShader,
  16262. nodeBuilder.fragmentShader,
  16263. nodeBuilder.computeShader,
  16264. nodeBuilder.getAttributesArray(),
  16265. nodeBuilder.getBindings(),
  16266. nodeBuilder.updateNodes,
  16267. nodeBuilder.updateBeforeNodes,
  16268. nodeBuilder.updateAfterNodes,
  16269. nodeBuilder.monitor,
  16270. nodeBuilder.transforms
  16271. );
  16272. }
  16273. getEnvironmentNode( scene ) {
  16274. return scene.environmentNode || this.get( scene ).environmentNode || null;
  16275. }
  16276. getBackgroundNode( scene ) {
  16277. return scene.backgroundNode || this.get( scene ).backgroundNode || null;
  16278. }
  16279. getFogNode( scene ) {
  16280. return scene.fogNode || this.get( scene ).fogNode || null;
  16281. }
  16282. getCacheKey( scene, lightsNode ) {
  16283. const chain = [ scene, lightsNode ];
  16284. const callId = this.renderer.info.calls;
  16285. let cacheKeyData = this.callHashCache.get( chain );
  16286. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  16287. const environmentNode = this.getEnvironmentNode( scene );
  16288. const fogNode = this.getFogNode( scene );
  16289. const values = [];
  16290. if ( lightsNode ) values.push( lightsNode.getCacheKey( true ) );
  16291. if ( environmentNode ) values.push( environmentNode.getCacheKey() );
  16292. if ( fogNode ) values.push( fogNode.getCacheKey() );
  16293. values.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  16294. cacheKeyData = {
  16295. callId,
  16296. cacheKey: hashArray( values )
  16297. };
  16298. this.callHashCache.set( chain, cacheKeyData );
  16299. }
  16300. return cacheKeyData.cacheKey;
  16301. }
  16302. updateScene( scene ) {
  16303. this.updateEnvironment( scene );
  16304. this.updateFog( scene );
  16305. this.updateBackground( scene );
  16306. }
  16307. get isToneMappingState() {
  16308. return this.renderer.getRenderTarget() ? false : true;
  16309. }
  16310. updateBackground( scene ) {
  16311. const sceneData = this.get( scene );
  16312. const background = scene.background;
  16313. if ( background ) {
  16314. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  16315. if ( sceneData.background !== background || forceUpdate ) {
  16316. let backgroundNode = null;
  16317. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  16318. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  16319. backgroundNode = pmremTexture( background );
  16320. } else {
  16321. let envMap;
  16322. if ( background.isCubeTexture === true ) {
  16323. envMap = cubeTexture( background );
  16324. } else {
  16325. envMap = texture( background );
  16326. }
  16327. backgroundNode = cubeMapNode( envMap );
  16328. }
  16329. } else if ( background.isTexture === true ) {
  16330. backgroundNode = texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  16331. } else if ( background.isColor !== true ) {
  16332. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  16333. }
  16334. sceneData.backgroundNode = backgroundNode;
  16335. sceneData.background = background;
  16336. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  16337. }
  16338. } else if ( sceneData.backgroundNode ) {
  16339. delete sceneData.backgroundNode;
  16340. delete sceneData.background;
  16341. }
  16342. }
  16343. updateFog( scene ) {
  16344. const sceneData = this.get( scene );
  16345. const fog = scene.fog;
  16346. if ( fog ) {
  16347. if ( sceneData.fog !== fog ) {
  16348. let fogNode = null;
  16349. if ( fog.isFogExp2 ) {
  16350. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  16351. const density = reference( 'density', 'float', fog ).setGroup( renderGroup );
  16352. fogNode = densityFog( color, density );
  16353. } else if ( fog.isFog ) {
  16354. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  16355. const near = reference( 'near', 'float', fog ).setGroup( renderGroup );
  16356. const far = reference( 'far', 'float', fog ).setGroup( renderGroup );
  16357. fogNode = rangeFog( color, near, far );
  16358. } else {
  16359. console.error( 'WebGPUNodes: Unsupported fog configuration.', fog );
  16360. }
  16361. sceneData.fogNode = fogNode;
  16362. sceneData.fog = fog;
  16363. }
  16364. } else {
  16365. delete sceneData.fogNode;
  16366. delete sceneData.fog;
  16367. }
  16368. }
  16369. updateEnvironment( scene ) {
  16370. const sceneData = this.get( scene );
  16371. const environment = scene.environment;
  16372. if ( environment ) {
  16373. if ( sceneData.environment !== environment ) {
  16374. let environmentNode = null;
  16375. if ( environment.isCubeTexture === true ) {
  16376. environmentNode = cubeTexture( environment );
  16377. } else if ( environment.isTexture === true ) {
  16378. environmentNode = texture( environment );
  16379. } else {
  16380. console.error( 'Nodes: Unsupported environment configuration.', environment );
  16381. }
  16382. sceneData.environmentNode = environmentNode;
  16383. sceneData.environment = environment;
  16384. }
  16385. } else if ( sceneData.environmentNode ) {
  16386. delete sceneData.environmentNode;
  16387. delete sceneData.environment;
  16388. }
  16389. }
  16390. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  16391. const nodeFrame = this.nodeFrame;
  16392. nodeFrame.renderer = renderer;
  16393. nodeFrame.scene = scene;
  16394. nodeFrame.object = object;
  16395. nodeFrame.camera = camera;
  16396. nodeFrame.material = material;
  16397. return nodeFrame;
  16398. }
  16399. getNodeFrameForRender( renderObject ) {
  16400. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  16401. }
  16402. getOutputCacheKey() {
  16403. const renderer = this.renderer;
  16404. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  16405. }
  16406. hasOutputChange( outputTarget ) {
  16407. const cacheKey = outputNodeMap.get( outputTarget );
  16408. return cacheKey !== this.getOutputCacheKey();
  16409. }
  16410. getOutputNode( outputTexture ) {
  16411. const renderer = this.renderer;
  16412. const cacheKey = this.getOutputCacheKey();
  16413. const output = texture( outputTexture, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  16414. outputNodeMap.set( outputTexture, cacheKey );
  16415. return output;
  16416. }
  16417. updateBefore( renderObject ) {
  16418. const nodeBuilder = renderObject.getNodeBuilderState();
  16419. for ( const node of nodeBuilder.updateBeforeNodes ) {
  16420. // update frame state for each node
  16421. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  16422. }
  16423. }
  16424. updateAfter( renderObject ) {
  16425. const nodeBuilder = renderObject.getNodeBuilderState();
  16426. for ( const node of nodeBuilder.updateAfterNodes ) {
  16427. // update frame state for each node
  16428. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  16429. }
  16430. }
  16431. updateForCompute( computeNode ) {
  16432. const nodeFrame = this.getNodeFrame();
  16433. const nodeBuilder = this.getForCompute( computeNode );
  16434. for ( const node of nodeBuilder.updateNodes ) {
  16435. nodeFrame.updateNode( node );
  16436. }
  16437. }
  16438. updateForRender( renderObject ) {
  16439. const nodeFrame = this.getNodeFrameForRender( renderObject );
  16440. const nodeBuilder = renderObject.getNodeBuilderState();
  16441. for ( const node of nodeBuilder.updateNodes ) {
  16442. nodeFrame.updateNode( node );
  16443. }
  16444. }
  16445. needsRefresh( renderObject ) {
  16446. const nodeFrame = this.getNodeFrameForRender( renderObject );
  16447. const monitor = renderObject.getMonitor();
  16448. return monitor.needsRefresh( renderObject, nodeFrame );
  16449. }
  16450. dispose() {
  16451. super.dispose();
  16452. this.nodeFrame = new NodeFrame();
  16453. this.nodeBuilderCache = new Map();
  16454. }
  16455. }
  16456. const _plane = /*@__PURE__*/ new Plane();
  16457. class ClippingContext {
  16458. constructor( parentContext = null ) {
  16459. this.version = 0;
  16460. this.clipIntersection = null;
  16461. this.cacheKey = '';
  16462. if ( parentContext === null ) {
  16463. this.intersectionPlanes = [];
  16464. this.unionPlanes = [];
  16465. this.viewNormalMatrix = new Matrix3();
  16466. this.clippingGroupContexts = new WeakMap();
  16467. this.shadowPass = false;
  16468. } else {
  16469. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  16470. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  16471. this.shadowPass = parentContext.shadowPass;
  16472. this.viewMatrix = parentContext.viewMatrix;
  16473. }
  16474. this.parentVersion = null;
  16475. }
  16476. projectPlanes( source, destination, offset ) {
  16477. const l = source.length;
  16478. for ( let i = 0; i < l; i ++ ) {
  16479. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  16480. const v = destination[ offset + i ];
  16481. const normal = _plane.normal;
  16482. v.x = - normal.x;
  16483. v.y = - normal.y;
  16484. v.z = - normal.z;
  16485. v.w = _plane.constant;
  16486. }
  16487. }
  16488. updateGlobal( scene, camera ) {
  16489. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowNodeMaterial );
  16490. this.viewMatrix = camera.matrixWorldInverse;
  16491. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  16492. }
  16493. update( parentContext, clippingGroup ) {
  16494. let update = false;
  16495. if ( parentContext.version !== this.parentVersion ) {
  16496. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  16497. this.unionPlanes = Array.from( parentContext.unionPlanes );
  16498. this.parentVersion = parentContext.version;
  16499. }
  16500. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  16501. this.clipIntersection = clippingGroup.clipIntersection;
  16502. if ( this.clipIntersection ) {
  16503. this.unionPlanes.length = parentContext.unionPlanes.length;
  16504. } else {
  16505. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  16506. }
  16507. }
  16508. const srcClippingPlanes = clippingGroup.clippingPlanes;
  16509. const l = srcClippingPlanes.length;
  16510. let dstClippingPlanes;
  16511. let offset;
  16512. if ( this.clipIntersection ) {
  16513. dstClippingPlanes = this.intersectionPlanes;
  16514. offset = parentContext.intersectionPlanes.length;
  16515. } else {
  16516. dstClippingPlanes = this.unionPlanes;
  16517. offset = parentContext.unionPlanes.length;
  16518. }
  16519. if ( dstClippingPlanes.length !== offset + l ) {
  16520. dstClippingPlanes.length = offset + l;
  16521. for ( let i = 0; i < l; i ++ ) {
  16522. dstClippingPlanes[ offset + i ] = new Vector4();
  16523. }
  16524. update = true;
  16525. }
  16526. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  16527. if ( update ) {
  16528. this.version ++;
  16529. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  16530. }
  16531. }
  16532. getGroupContext( clippingGroup ) {
  16533. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  16534. let context = this.clippingGroupContexts.get( clippingGroup );
  16535. if ( context === undefined ) {
  16536. context = new ClippingContext( this );
  16537. this.clippingGroupContexts.set( clippingGroup, context );
  16538. }
  16539. context.update( this, clippingGroup );
  16540. return context;
  16541. }
  16542. get unionClippingCount() {
  16543. return this.unionPlanes.length;
  16544. }
  16545. }
  16546. class RenderBundle {
  16547. constructor( scene, camera ) {
  16548. this.scene = scene;
  16549. this.camera = camera;
  16550. }
  16551. clone() {
  16552. return Object.assign( new this.constructor(), this );
  16553. }
  16554. }
  16555. class RenderBundles {
  16556. constructor() {
  16557. this.lists = new ChainMap();
  16558. }
  16559. get( scene, camera ) {
  16560. const lists = this.lists;
  16561. const keys = [ scene, camera ];
  16562. let list = lists.get( keys );
  16563. if ( list === undefined ) {
  16564. list = new RenderBundle( scene, camera );
  16565. lists.set( keys, list );
  16566. }
  16567. return list;
  16568. }
  16569. dispose() {
  16570. this.lists = new ChainMap();
  16571. }
  16572. }
  16573. class NodeLibrary {
  16574. constructor() {
  16575. this.lightNodes = new WeakMap();
  16576. this.materialNodes = new Map();
  16577. this.toneMappingNodes = new Map();
  16578. }
  16579. fromMaterial( material ) {
  16580. if ( material.isNodeMaterial ) return material;
  16581. let nodeMaterial = null;
  16582. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  16583. if ( nodeMaterialClass !== null ) {
  16584. nodeMaterial = new nodeMaterialClass();
  16585. for ( const key in material ) {
  16586. nodeMaterial[ key ] = material[ key ];
  16587. }
  16588. }
  16589. return nodeMaterial;
  16590. }
  16591. addToneMapping( toneMappingNode, toneMapping ) {
  16592. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  16593. }
  16594. getToneMappingFunction( toneMapping ) {
  16595. return this.toneMappingNodes.get( toneMapping ) || null;
  16596. }
  16597. getMaterialNodeClass( materialType ) {
  16598. return this.materialNodes.get( materialType ) || null;
  16599. }
  16600. addMaterial( materialNodeClass, materialClassType ) {
  16601. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  16602. }
  16603. getLightNodeClass( light ) {
  16604. return this.lightNodes.get( light ) || null;
  16605. }
  16606. addLight( lightNodeClass, lightClass ) {
  16607. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  16608. }
  16609. addType( nodeClass, type, library ) {
  16610. if ( library.has( type ) ) {
  16611. console.warn( `Redefinition of node ${ type }` );
  16612. return;
  16613. }
  16614. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  16615. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  16616. library.set( type, nodeClass );
  16617. }
  16618. addClass( nodeClass, baseClass, library ) {
  16619. if ( library.has( baseClass ) ) {
  16620. console.warn( `Redefinition of node ${ baseClass.name }` );
  16621. return;
  16622. }
  16623. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  16624. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  16625. library.set( baseClass, nodeClass );
  16626. }
  16627. }
  16628. const _defaultLights = /*@__PURE__*/ new LightsNode();
  16629. class Lighting extends ChainMap {
  16630. constructor() {
  16631. super();
  16632. }
  16633. createNode( lights = [] ) {
  16634. return new LightsNode().setLights( lights );
  16635. }
  16636. getNode( scene, camera ) {
  16637. // ignore post-processing
  16638. if ( scene.isQuadMesh ) return _defaultLights;
  16639. // tiled lighting
  16640. const keys = [ scene, camera ];
  16641. let node = this.get( keys );
  16642. if ( node === undefined ) {
  16643. node = this.createNode();
  16644. this.set( keys, node );
  16645. }
  16646. return node;
  16647. }
  16648. }
  16649. const _scene = /*@__PURE__*/ new Scene();
  16650. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  16651. const _screen = /*@__PURE__*/ new Vector4();
  16652. const _frustum = /*@__PURE__*/ new Frustum();
  16653. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  16654. const _vector4 = /*@__PURE__*/ new Vector4();
  16655. class Renderer {
  16656. constructor( backend, parameters = {} ) {
  16657. this.isRenderer = true;
  16658. //
  16659. const {
  16660. logarithmicDepthBuffer = false,
  16661. alpha = true,
  16662. depth = true,
  16663. stencil = false,
  16664. antialias = false,
  16665. samples = 0,
  16666. getFallback = null
  16667. } = parameters;
  16668. // public
  16669. this.domElement = backend.getDomElement();
  16670. this.backend = backend;
  16671. this.samples = samples || ( antialias === true ) ? 4 : 0;
  16672. this.autoClear = true;
  16673. this.autoClearColor = true;
  16674. this.autoClearDepth = true;
  16675. this.autoClearStencil = true;
  16676. this.alpha = alpha;
  16677. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  16678. this.outputColorSpace = SRGBColorSpace;
  16679. this.toneMapping = NoToneMapping;
  16680. this.toneMappingExposure = 1.0;
  16681. this.sortObjects = true;
  16682. this.depth = depth;
  16683. this.stencil = stencil;
  16684. this.info = new Info();
  16685. this.nodes = {
  16686. modelViewMatrix: null,
  16687. modelNormalViewMatrix: null
  16688. };
  16689. this.library = new NodeLibrary();
  16690. this.lighting = new Lighting();
  16691. // internals
  16692. this._getFallback = getFallback;
  16693. this._pixelRatio = 1;
  16694. this._width = this.domElement.width;
  16695. this._height = this.domElement.height;
  16696. this._viewport = new Vector4( 0, 0, this._width, this._height );
  16697. this._scissor = new Vector4( 0, 0, this._width, this._height );
  16698. this._scissorTest = false;
  16699. this._attributes = null;
  16700. this._geometries = null;
  16701. this._nodes = null;
  16702. this._animation = null;
  16703. this._bindings = null;
  16704. this._objects = null;
  16705. this._pipelines = null;
  16706. this._bundles = null;
  16707. this._renderLists = null;
  16708. this._renderContexts = null;
  16709. this._textures = null;
  16710. this._background = null;
  16711. this._quad = new QuadMesh( new NodeMaterial() );
  16712. this._quad.material.type = 'Renderer_output';
  16713. this._currentRenderContext = null;
  16714. this._opaqueSort = null;
  16715. this._transparentSort = null;
  16716. this._frameBufferTarget = null;
  16717. const alphaClear = this.alpha === true ? 0 : 1;
  16718. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  16719. this._clearDepth = 1;
  16720. this._clearStencil = 0;
  16721. this._renderTarget = null;
  16722. this._activeCubeFace = 0;
  16723. this._activeMipmapLevel = 0;
  16724. this._mrt = null;
  16725. this._renderObjectFunction = null;
  16726. this._currentRenderObjectFunction = null;
  16727. this._currentRenderBundle = null;
  16728. this._handleObjectFunction = this._renderObjectDirect;
  16729. this._isDeviceLost = false;
  16730. this.onDeviceLost = this._onDeviceLost;
  16731. this._initialized = false;
  16732. this._initPromise = null;
  16733. this._compilationPromises = null;
  16734. this.transparent = true;
  16735. this.opaque = true;
  16736. this.shadowMap = {
  16737. enabled: false,
  16738. type: PCFShadowMap
  16739. };
  16740. this.xr = {
  16741. enabled: false
  16742. };
  16743. this.debug = {
  16744. checkShaderErrors: true,
  16745. onShaderError: null,
  16746. getShaderAsync: async ( scene, camera, object ) => {
  16747. await this.compileAsync( scene, camera );
  16748. const renderList = this._renderLists.get( scene, camera );
  16749. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  16750. const material = scene.overrideMaterial || object.material;
  16751. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  16752. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  16753. return { fragmentShader, vertexShader };
  16754. }
  16755. };
  16756. }
  16757. async init() {
  16758. if ( this._initialized ) {
  16759. throw new Error( 'Renderer: Backend has already been initialized.' );
  16760. }
  16761. if ( this._initPromise !== null ) {
  16762. return this._initPromise;
  16763. }
  16764. this._initPromise = new Promise( async ( resolve, reject ) => {
  16765. let backend = this.backend;
  16766. try {
  16767. await backend.init( this );
  16768. } catch ( error ) {
  16769. if ( this._getFallback !== null ) {
  16770. // try the fallback
  16771. try {
  16772. this.backend = backend = this._getFallback( error );
  16773. await backend.init( this );
  16774. } catch ( error ) {
  16775. reject( error );
  16776. return;
  16777. }
  16778. } else {
  16779. reject( error );
  16780. return;
  16781. }
  16782. }
  16783. this._nodes = new Nodes( this, backend );
  16784. this._animation = new Animation( this._nodes, this.info );
  16785. this._attributes = new Attributes( backend );
  16786. this._background = new Background( this, this._nodes );
  16787. this._geometries = new Geometries( this._attributes, this.info );
  16788. this._textures = new Textures( this, backend, this.info );
  16789. this._pipelines = new Pipelines( backend, this._nodes );
  16790. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  16791. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  16792. this._renderLists = new RenderLists( this.lighting );
  16793. this._bundles = new RenderBundles();
  16794. this._renderContexts = new RenderContexts();
  16795. //
  16796. this._animation.start();
  16797. this._initialized = true;
  16798. resolve();
  16799. } );
  16800. return this._initPromise;
  16801. }
  16802. get coordinateSystem() {
  16803. return this.backend.coordinateSystem;
  16804. }
  16805. async compileAsync( scene, camera, targetScene = null ) {
  16806. if ( this._isDeviceLost === true ) return;
  16807. if ( this._initialized === false ) await this.init();
  16808. // preserve render tree
  16809. const nodeFrame = this._nodes.nodeFrame;
  16810. const previousRenderId = nodeFrame.renderId;
  16811. const previousRenderContext = this._currentRenderContext;
  16812. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  16813. const previousCompilationPromises = this._compilationPromises;
  16814. //
  16815. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  16816. if ( targetScene === null ) targetScene = scene;
  16817. const renderTarget = this._renderTarget;
  16818. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  16819. const activeMipmapLevel = this._activeMipmapLevel;
  16820. const compilationPromises = [];
  16821. this._currentRenderContext = renderContext;
  16822. this._currentRenderObjectFunction = this.renderObject;
  16823. this._handleObjectFunction = this._createObjectPipeline;
  16824. this._compilationPromises = compilationPromises;
  16825. nodeFrame.renderId ++;
  16826. //
  16827. nodeFrame.update();
  16828. //
  16829. renderContext.depth = this.depth;
  16830. renderContext.stencil = this.stencil;
  16831. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  16832. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  16833. //
  16834. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  16835. //
  16836. const renderList = this._renderLists.get( scene, camera );
  16837. renderList.begin();
  16838. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  16839. // include lights from target scene
  16840. if ( targetScene !== scene ) {
  16841. targetScene.traverseVisible( function ( object ) {
  16842. if ( object.isLight && object.layers.test( camera.layers ) ) {
  16843. renderList.pushLight( object );
  16844. }
  16845. } );
  16846. }
  16847. renderList.finish();
  16848. //
  16849. if ( renderTarget !== null ) {
  16850. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  16851. const renderTargetData = this._textures.get( renderTarget );
  16852. renderContext.textures = renderTargetData.textures;
  16853. renderContext.depthTexture = renderTargetData.depthTexture;
  16854. } else {
  16855. renderContext.textures = null;
  16856. renderContext.depthTexture = null;
  16857. }
  16858. //
  16859. this._nodes.updateScene( sceneRef );
  16860. //
  16861. this._background.update( sceneRef, renderList, renderContext );
  16862. // process render lists
  16863. const opaqueObjects = renderList.opaque;
  16864. const transparentObjects = renderList.transparent;
  16865. const transparentDoublePassObjects = renderList.transparentDoublePass;
  16866. const lightsNode = renderList.lightsNode;
  16867. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  16868. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  16869. // restore render tree
  16870. nodeFrame.renderId = previousRenderId;
  16871. this._currentRenderContext = previousRenderContext;
  16872. this._currentRenderObjectFunction = previousRenderObjectFunction;
  16873. this._compilationPromises = previousCompilationPromises;
  16874. this._handleObjectFunction = this._renderObjectDirect;
  16875. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  16876. await Promise.all( compilationPromises );
  16877. }
  16878. async renderAsync( scene, camera ) {
  16879. if ( this._initialized === false ) await this.init();
  16880. const renderContext = this._renderScene( scene, camera );
  16881. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  16882. }
  16883. async waitForGPU() {
  16884. await this.backend.waitForGPU();
  16885. }
  16886. setMRT( mrt ) {
  16887. this._mrt = mrt;
  16888. return this;
  16889. }
  16890. getMRT() {
  16891. return this._mrt;
  16892. }
  16893. _onDeviceLost( info ) {
  16894. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  16895. if ( info.reason ) {
  16896. errorMessage += `\nReason: ${info.reason}`;
  16897. }
  16898. console.error( errorMessage );
  16899. this._isDeviceLost = true;
  16900. }
  16901. _renderBundle( bundle, sceneRef, lightsNode ) {
  16902. const { bundleGroup, camera, renderList } = bundle;
  16903. const renderContext = this._currentRenderContext;
  16904. //
  16905. const renderBundle = this._bundles.get( bundleGroup, camera );
  16906. const renderBundleData = this.backend.get( renderBundle );
  16907. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  16908. //
  16909. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  16910. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  16911. renderBundleData.renderContexts.add( renderContext );
  16912. if ( renderBundleNeedsUpdate ) {
  16913. this.backend.beginBundle( renderContext );
  16914. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  16915. renderBundleData.renderObjects = [];
  16916. }
  16917. this._currentRenderBundle = renderBundle;
  16918. const opaqueObjects = renderList.opaque;
  16919. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  16920. this._currentRenderBundle = null;
  16921. //
  16922. this.backend.finishBundle( renderContext, renderBundle );
  16923. renderBundleData.version = bundleGroup.version;
  16924. } else {
  16925. const { renderObjects } = renderBundleData;
  16926. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  16927. const renderObject = renderObjects[ i ];
  16928. if ( this._nodes.needsRefresh( renderObject ) ) {
  16929. this._nodes.updateBefore( renderObject );
  16930. this._nodes.updateForRender( renderObject );
  16931. this._bindings.updateForRender( renderObject );
  16932. this._nodes.updateAfter( renderObject );
  16933. }
  16934. }
  16935. }
  16936. this.backend.addBundle( renderContext, renderBundle );
  16937. }
  16938. render( scene, camera ) {
  16939. if ( this._initialized === false ) {
  16940. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  16941. return this.renderAsync( scene, camera );
  16942. }
  16943. this._renderScene( scene, camera );
  16944. }
  16945. _getFrameBufferTarget() {
  16946. const { currentToneMapping, currentColorSpace } = this;
  16947. const useToneMapping = currentToneMapping !== NoToneMapping;
  16948. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  16949. if ( useToneMapping === false && useColorSpace === false ) return null;
  16950. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  16951. const { depth, stencil } = this;
  16952. let frameBufferTarget = this._frameBufferTarget;
  16953. if ( frameBufferTarget === null ) {
  16954. frameBufferTarget = new RenderTarget( width, height, {
  16955. depthBuffer: depth,
  16956. stencilBuffer: stencil,
  16957. type: HalfFloatType, // FloatType
  16958. format: RGBAFormat,
  16959. colorSpace: LinearSRGBColorSpace,
  16960. generateMipmaps: false,
  16961. minFilter: LinearFilter,
  16962. magFilter: LinearFilter,
  16963. samples: this.samples
  16964. } );
  16965. frameBufferTarget.isPostProcessingRenderTarget = true;
  16966. this._frameBufferTarget = frameBufferTarget;
  16967. }
  16968. frameBufferTarget.depthBuffer = depth;
  16969. frameBufferTarget.stencilBuffer = stencil;
  16970. frameBufferTarget.setSize( width, height );
  16971. frameBufferTarget.viewport.copy( this._viewport );
  16972. frameBufferTarget.scissor.copy( this._scissor );
  16973. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  16974. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  16975. frameBufferTarget.scissorTest = this._scissorTest;
  16976. return frameBufferTarget;
  16977. }
  16978. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  16979. if ( this._isDeviceLost === true ) return;
  16980. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  16981. // preserve render tree
  16982. const nodeFrame = this._nodes.nodeFrame;
  16983. const previousRenderId = nodeFrame.renderId;
  16984. const previousRenderContext = this._currentRenderContext;
  16985. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  16986. //
  16987. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  16988. const outputRenderTarget = this._renderTarget;
  16989. const activeCubeFace = this._activeCubeFace;
  16990. const activeMipmapLevel = this._activeMipmapLevel;
  16991. //
  16992. let renderTarget;
  16993. if ( frameBufferTarget !== null ) {
  16994. renderTarget = frameBufferTarget;
  16995. this.setRenderTarget( renderTarget );
  16996. } else {
  16997. renderTarget = outputRenderTarget;
  16998. }
  16999. //
  17000. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  17001. this._currentRenderContext = renderContext;
  17002. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  17003. //
  17004. this.info.calls ++;
  17005. this.info.render.calls ++;
  17006. this.info.render.frameCalls ++;
  17007. nodeFrame.renderId = this.info.calls;
  17008. //
  17009. const coordinateSystem = this.coordinateSystem;
  17010. if ( camera.coordinateSystem !== coordinateSystem ) {
  17011. camera.coordinateSystem = coordinateSystem;
  17012. camera.updateProjectionMatrix();
  17013. }
  17014. //
  17015. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  17016. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  17017. //
  17018. let viewport = this._viewport;
  17019. let scissor = this._scissor;
  17020. let pixelRatio = this._pixelRatio;
  17021. if ( renderTarget !== null ) {
  17022. viewport = renderTarget.viewport;
  17023. scissor = renderTarget.scissor;
  17024. pixelRatio = 1;
  17025. }
  17026. this.getDrawingBufferSize( _drawingBufferSize );
  17027. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  17028. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  17029. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  17030. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  17031. renderContext.viewportValue.width >>= activeMipmapLevel;
  17032. renderContext.viewportValue.height >>= activeMipmapLevel;
  17033. renderContext.viewportValue.minDepth = minDepth;
  17034. renderContext.viewportValue.maxDepth = maxDepth;
  17035. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  17036. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  17037. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  17038. renderContext.scissorValue.width >>= activeMipmapLevel;
  17039. renderContext.scissorValue.height >>= activeMipmapLevel;
  17040. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  17041. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  17042. //
  17043. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  17044. //
  17045. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  17046. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  17047. const renderList = this._renderLists.get( scene, camera );
  17048. renderList.begin();
  17049. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  17050. renderList.finish();
  17051. if ( this.sortObjects === true ) {
  17052. renderList.sort( this._opaqueSort, this._transparentSort );
  17053. }
  17054. //
  17055. if ( renderTarget !== null ) {
  17056. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  17057. const renderTargetData = this._textures.get( renderTarget );
  17058. renderContext.textures = renderTargetData.textures;
  17059. renderContext.depthTexture = renderTargetData.depthTexture;
  17060. renderContext.width = renderTargetData.width;
  17061. renderContext.height = renderTargetData.height;
  17062. renderContext.renderTarget = renderTarget;
  17063. renderContext.depth = renderTarget.depthBuffer;
  17064. renderContext.stencil = renderTarget.stencilBuffer;
  17065. } else {
  17066. renderContext.textures = null;
  17067. renderContext.depthTexture = null;
  17068. renderContext.width = this.domElement.width;
  17069. renderContext.height = this.domElement.height;
  17070. renderContext.depth = this.depth;
  17071. renderContext.stencil = this.stencil;
  17072. }
  17073. renderContext.width >>= activeMipmapLevel;
  17074. renderContext.height >>= activeMipmapLevel;
  17075. renderContext.activeCubeFace = activeCubeFace;
  17076. renderContext.activeMipmapLevel = activeMipmapLevel;
  17077. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  17078. //
  17079. this._nodes.updateScene( sceneRef );
  17080. //
  17081. this._background.update( sceneRef, renderList, renderContext );
  17082. //
  17083. this.backend.beginRender( renderContext );
  17084. // process render lists
  17085. const {
  17086. bundles,
  17087. lightsNode,
  17088. transparentDoublePass: transparentDoublePassObjects,
  17089. transparent: transparentObjects,
  17090. opaque: opaqueObjects
  17091. } = renderList;
  17092. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  17093. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  17094. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  17095. // finish render pass
  17096. this.backend.finishRender( renderContext );
  17097. // restore render tree
  17098. nodeFrame.renderId = previousRenderId;
  17099. this._currentRenderContext = previousRenderContext;
  17100. this._currentRenderObjectFunction = previousRenderObjectFunction;
  17101. //
  17102. if ( frameBufferTarget !== null ) {
  17103. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  17104. const quad = this._quad;
  17105. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  17106. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  17107. quad.material.needsUpdate = true;
  17108. }
  17109. this._renderScene( quad, quad.camera, false );
  17110. }
  17111. //
  17112. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  17113. //
  17114. return renderContext;
  17115. }
  17116. getMaxAnisotropy() {
  17117. return this.backend.getMaxAnisotropy();
  17118. }
  17119. getActiveCubeFace() {
  17120. return this._activeCubeFace;
  17121. }
  17122. getActiveMipmapLevel() {
  17123. return this._activeMipmapLevel;
  17124. }
  17125. async setAnimationLoop( callback ) {
  17126. if ( this._initialized === false ) await this.init();
  17127. this._animation.setAnimationLoop( callback );
  17128. }
  17129. async getArrayBufferAsync( attribute ) {
  17130. return await this.backend.getArrayBufferAsync( attribute );
  17131. }
  17132. getContext() {
  17133. return this.backend.getContext();
  17134. }
  17135. getPixelRatio() {
  17136. return this._pixelRatio;
  17137. }
  17138. getDrawingBufferSize( target ) {
  17139. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  17140. }
  17141. getSize( target ) {
  17142. return target.set( this._width, this._height );
  17143. }
  17144. setPixelRatio( value = 1 ) {
  17145. if ( this._pixelRatio === value ) return;
  17146. this._pixelRatio = value;
  17147. this.setSize( this._width, this._height, false );
  17148. }
  17149. setDrawingBufferSize( width, height, pixelRatio ) {
  17150. this._width = width;
  17151. this._height = height;
  17152. this._pixelRatio = pixelRatio;
  17153. this.domElement.width = Math.floor( width * pixelRatio );
  17154. this.domElement.height = Math.floor( height * pixelRatio );
  17155. this.setViewport( 0, 0, width, height );
  17156. if ( this._initialized ) this.backend.updateSize();
  17157. }
  17158. setSize( width, height, updateStyle = true ) {
  17159. this._width = width;
  17160. this._height = height;
  17161. this.domElement.width = Math.floor( width * this._pixelRatio );
  17162. this.domElement.height = Math.floor( height * this._pixelRatio );
  17163. if ( updateStyle === true ) {
  17164. this.domElement.style.width = width + 'px';
  17165. this.domElement.style.height = height + 'px';
  17166. }
  17167. this.setViewport( 0, 0, width, height );
  17168. if ( this._initialized ) this.backend.updateSize();
  17169. }
  17170. setOpaqueSort( method ) {
  17171. this._opaqueSort = method;
  17172. }
  17173. setTransparentSort( method ) {
  17174. this._transparentSort = method;
  17175. }
  17176. getScissor( target ) {
  17177. const scissor = this._scissor;
  17178. target.x = scissor.x;
  17179. target.y = scissor.y;
  17180. target.width = scissor.width;
  17181. target.height = scissor.height;
  17182. return target;
  17183. }
  17184. setScissor( x, y, width, height ) {
  17185. const scissor = this._scissor;
  17186. if ( x.isVector4 ) {
  17187. scissor.copy( x );
  17188. } else {
  17189. scissor.set( x, y, width, height );
  17190. }
  17191. }
  17192. getScissorTest() {
  17193. return this._scissorTest;
  17194. }
  17195. setScissorTest( boolean ) {
  17196. this._scissorTest = boolean;
  17197. this.backend.setScissorTest( boolean );
  17198. }
  17199. getViewport( target ) {
  17200. return target.copy( this._viewport );
  17201. }
  17202. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  17203. const viewport = this._viewport;
  17204. if ( x.isVector4 ) {
  17205. viewport.copy( x );
  17206. } else {
  17207. viewport.set( x, y, width, height );
  17208. }
  17209. viewport.minDepth = minDepth;
  17210. viewport.maxDepth = maxDepth;
  17211. }
  17212. getClearColor( target ) {
  17213. return target.copy( this._clearColor );
  17214. }
  17215. setClearColor( color, alpha = 1 ) {
  17216. this._clearColor.set( color );
  17217. this._clearColor.a = alpha;
  17218. }
  17219. getClearAlpha() {
  17220. return this._clearColor.a;
  17221. }
  17222. setClearAlpha( alpha ) {
  17223. this._clearColor.a = alpha;
  17224. }
  17225. getClearDepth() {
  17226. return this._clearDepth;
  17227. }
  17228. setClearDepth( depth ) {
  17229. this._clearDepth = depth;
  17230. }
  17231. getClearStencil() {
  17232. return this._clearStencil;
  17233. }
  17234. setClearStencil( stencil ) {
  17235. this._clearStencil = stencil;
  17236. }
  17237. isOccluded( object ) {
  17238. const renderContext = this._currentRenderContext;
  17239. return renderContext && this.backend.isOccluded( renderContext, object );
  17240. }
  17241. clear( color = true, depth = true, stencil = true ) {
  17242. if ( this._initialized === false ) {
  17243. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  17244. return this.clearAsync( color, depth, stencil );
  17245. }
  17246. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  17247. let renderTargetData = null;
  17248. if ( renderTarget !== null ) {
  17249. this._textures.updateRenderTarget( renderTarget );
  17250. renderTargetData = this._textures.get( renderTarget );
  17251. }
  17252. this.backend.clear( color, depth, stencil, renderTargetData );
  17253. if ( renderTarget !== null && this._renderTarget === null ) {
  17254. // If a color space transform or tone mapping is required,
  17255. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  17256. const quad = this._quad;
  17257. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  17258. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  17259. quad.material.needsUpdate = true;
  17260. }
  17261. this._renderScene( quad, quad.camera, false );
  17262. }
  17263. }
  17264. clearColor() {
  17265. return this.clear( true, false, false );
  17266. }
  17267. clearDepth() {
  17268. return this.clear( false, true, false );
  17269. }
  17270. clearStencil() {
  17271. return this.clear( false, false, true );
  17272. }
  17273. async clearAsync( color = true, depth = true, stencil = true ) {
  17274. if ( this._initialized === false ) await this.init();
  17275. this.clear( color, depth, stencil );
  17276. }
  17277. clearColorAsync() {
  17278. return this.clearAsync( true, false, false );
  17279. }
  17280. clearDepthAsync() {
  17281. return this.clearAsync( false, true, false );
  17282. }
  17283. clearStencilAsync() {
  17284. return this.clearAsync( false, false, true );
  17285. }
  17286. get currentToneMapping() {
  17287. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  17288. }
  17289. get currentColorSpace() {
  17290. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  17291. }
  17292. dispose() {
  17293. this.info.dispose();
  17294. this.backend.dispose();
  17295. this._animation.dispose();
  17296. this._objects.dispose();
  17297. this._pipelines.dispose();
  17298. this._nodes.dispose();
  17299. this._bindings.dispose();
  17300. this._renderLists.dispose();
  17301. this._renderContexts.dispose();
  17302. this._textures.dispose();
  17303. this.setRenderTarget( null );
  17304. this.setAnimationLoop( null );
  17305. }
  17306. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  17307. this._renderTarget = renderTarget;
  17308. this._activeCubeFace = activeCubeFace;
  17309. this._activeMipmapLevel = activeMipmapLevel;
  17310. }
  17311. getRenderTarget() {
  17312. return this._renderTarget;
  17313. }
  17314. setRenderObjectFunction( renderObjectFunction ) {
  17315. this._renderObjectFunction = renderObjectFunction;
  17316. }
  17317. getRenderObjectFunction() {
  17318. return this._renderObjectFunction;
  17319. }
  17320. compute( computeNodes ) {
  17321. if ( this.isDeviceLost === true ) return;
  17322. if ( this._initialized === false ) {
  17323. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  17324. return this.computeAsync( computeNodes );
  17325. }
  17326. //
  17327. const nodeFrame = this._nodes.nodeFrame;
  17328. const previousRenderId = nodeFrame.renderId;
  17329. //
  17330. this.info.calls ++;
  17331. this.info.compute.calls ++;
  17332. this.info.compute.frameCalls ++;
  17333. nodeFrame.renderId = this.info.calls;
  17334. //
  17335. const backend = this.backend;
  17336. const pipelines = this._pipelines;
  17337. const bindings = this._bindings;
  17338. const nodes = this._nodes;
  17339. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  17340. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  17341. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  17342. }
  17343. backend.beginCompute( computeNodes );
  17344. for ( const computeNode of computeList ) {
  17345. // onInit
  17346. if ( pipelines.has( computeNode ) === false ) {
  17347. const dispose = () => {
  17348. computeNode.removeEventListener( 'dispose', dispose );
  17349. pipelines.delete( computeNode );
  17350. bindings.delete( computeNode );
  17351. nodes.delete( computeNode );
  17352. };
  17353. computeNode.addEventListener( 'dispose', dispose );
  17354. //
  17355. const onInitFn = computeNode.onInitFunction;
  17356. if ( onInitFn !== null ) {
  17357. onInitFn.call( computeNode, { renderer: this } );
  17358. }
  17359. }
  17360. nodes.updateForCompute( computeNode );
  17361. bindings.updateForCompute( computeNode );
  17362. const computeBindings = bindings.getForCompute( computeNode );
  17363. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  17364. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  17365. }
  17366. backend.finishCompute( computeNodes );
  17367. //
  17368. nodeFrame.renderId = previousRenderId;
  17369. }
  17370. async computeAsync( computeNodes ) {
  17371. if ( this._initialized === false ) await this.init();
  17372. this.compute( computeNodes );
  17373. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  17374. }
  17375. async hasFeatureAsync( name ) {
  17376. if ( this._initialized === false ) await this.init();
  17377. return this.backend.hasFeature( name );
  17378. }
  17379. hasFeature( name ) {
  17380. if ( this._initialized === false ) {
  17381. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  17382. return false;
  17383. }
  17384. return this.backend.hasFeature( name );
  17385. }
  17386. hasInitialized() {
  17387. return this._initialized;
  17388. }
  17389. async initTextureAsync( texture ) {
  17390. if ( this._initialized === false ) await this.init();
  17391. this._textures.updateTexture( texture );
  17392. }
  17393. initTexture( texture ) {
  17394. if ( this._initialized === false ) {
  17395. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  17396. return false;
  17397. }
  17398. this._textures.updateTexture( texture );
  17399. }
  17400. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  17401. if ( rectangle !== null ) {
  17402. if ( rectangle.isVector2 ) {
  17403. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  17404. } else if ( rectangle.isVector4 ) {
  17405. rectangle = _vector4.copy( rectangle ).floor();
  17406. } else {
  17407. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  17408. return;
  17409. }
  17410. } else {
  17411. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  17412. }
  17413. //
  17414. let renderContext = this._currentRenderContext;
  17415. let renderTarget;
  17416. if ( renderContext !== null ) {
  17417. renderTarget = renderContext.renderTarget;
  17418. } else {
  17419. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  17420. if ( renderTarget !== null ) {
  17421. this._textures.updateRenderTarget( renderTarget );
  17422. renderContext = this._textures.get( renderTarget );
  17423. }
  17424. }
  17425. //
  17426. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  17427. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  17428. }
  17429. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  17430. this._textures.updateTexture( srcTexture );
  17431. this._textures.updateTexture( dstTexture );
  17432. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  17433. }
  17434. readRenderTargetPixelsAsync( renderTarget, x, y, width, height, index = 0, faceIndex = 0 ) {
  17435. return this.backend.copyTextureToBuffer( renderTarget.textures[ index ], x, y, width, height, faceIndex );
  17436. }
  17437. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  17438. if ( object.visible === false ) return;
  17439. const visible = object.layers.test( camera.layers );
  17440. if ( visible ) {
  17441. if ( object.isGroup ) {
  17442. groupOrder = object.renderOrder;
  17443. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  17444. } else if ( object.isLOD ) {
  17445. if ( object.autoUpdate === true ) object.update( camera );
  17446. } else if ( object.isLight ) {
  17447. renderList.pushLight( object );
  17448. } else if ( object.isSprite ) {
  17449. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  17450. if ( this.sortObjects === true ) {
  17451. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  17452. }
  17453. const { geometry, material } = object;
  17454. if ( material.visible ) {
  17455. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  17456. }
  17457. }
  17458. } else if ( object.isLineLoop ) {
  17459. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  17460. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  17461. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  17462. const { geometry, material } = object;
  17463. if ( this.sortObjects === true ) {
  17464. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17465. _vector4
  17466. .copy( geometry.boundingSphere.center )
  17467. .applyMatrix4( object.matrixWorld )
  17468. .applyMatrix4( _projScreenMatrix );
  17469. }
  17470. if ( Array.isArray( material ) ) {
  17471. const groups = geometry.groups;
  17472. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17473. const group = groups[ i ];
  17474. const groupMaterial = material[ group.materialIndex ];
  17475. if ( groupMaterial && groupMaterial.visible ) {
  17476. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  17477. }
  17478. }
  17479. } else if ( material.visible ) {
  17480. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  17481. }
  17482. }
  17483. }
  17484. }
  17485. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  17486. const baseRenderList = renderList;
  17487. // replace render list
  17488. renderList = this._renderLists.get( object, camera );
  17489. renderList.begin();
  17490. baseRenderList.pushBundle( {
  17491. bundleGroup: object,
  17492. camera,
  17493. renderList,
  17494. } );
  17495. renderList.finish();
  17496. }
  17497. const children = object.children;
  17498. for ( let i = 0, l = children.length; i < l; i ++ ) {
  17499. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  17500. }
  17501. }
  17502. _renderBundles( bundles, sceneRef, lightsNode ) {
  17503. for ( const bundle of bundles ) {
  17504. this._renderBundle( bundle, sceneRef, lightsNode );
  17505. }
  17506. }
  17507. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  17508. if ( doublePassList.length > 0 ) {
  17509. // render back side
  17510. for ( const { material } of doublePassList ) {
  17511. material.side = BackSide;
  17512. }
  17513. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  17514. // render front side
  17515. for ( const { material } of doublePassList ) {
  17516. material.side = FrontSide;
  17517. }
  17518. this._renderObjects( renderList, camera, scene, lightsNode );
  17519. // restore
  17520. for ( const { material } of doublePassList ) {
  17521. material.side = DoubleSide;
  17522. }
  17523. } else {
  17524. this._renderObjects( renderList, camera, scene, lightsNode );
  17525. }
  17526. }
  17527. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  17528. // process renderable objects
  17529. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  17530. const renderItem = renderList[ i ];
  17531. // @TODO: Add support for multiple materials per object. This will require to extract
  17532. // the material from the renderItem object and pass it with its group data to renderObject().
  17533. const { object, geometry, material, group, clippingContext } = renderItem;
  17534. if ( camera.isArrayCamera ) {
  17535. const cameras = camera.cameras;
  17536. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  17537. const camera2 = cameras[ j ];
  17538. if ( object.layers.test( camera2.layers ) ) {
  17539. const vp = camera2.viewport;
  17540. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  17541. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  17542. const viewportValue = this._currentRenderContext.viewportValue;
  17543. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  17544. viewportValue.minDepth = minDepth;
  17545. viewportValue.maxDepth = maxDepth;
  17546. this.backend.updateViewport( this._currentRenderContext );
  17547. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode, clippingContext, passId );
  17548. }
  17549. }
  17550. } else {
  17551. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  17552. }
  17553. }
  17554. }
  17555. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  17556. let overridePositionNode;
  17557. let overrideFragmentNode;
  17558. let overrideDepthNode;
  17559. //
  17560. object.onBeforeRender( this, scene, camera, geometry, material, group );
  17561. //
  17562. if ( scene.overrideMaterial !== null ) {
  17563. const overrideMaterial = scene.overrideMaterial;
  17564. if ( material.positionNode && material.positionNode.isNode ) {
  17565. overridePositionNode = overrideMaterial.positionNode;
  17566. overrideMaterial.positionNode = material.positionNode;
  17567. }
  17568. if ( overrideMaterial.isShadowNodeMaterial ) {
  17569. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  17570. if ( material.depthNode && material.depthNode.isNode ) {
  17571. overrideDepthNode = overrideMaterial.depthNode;
  17572. overrideMaterial.depthNode = material.depthNode;
  17573. }
  17574. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  17575. overrideFragmentNode = overrideMaterial.fragmentNode;
  17576. overrideMaterial.fragmentNode = material.castShadowNode;
  17577. }
  17578. }
  17579. material = overrideMaterial;
  17580. }
  17581. //
  17582. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  17583. material.side = BackSide;
  17584. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  17585. material.side = FrontSide;
  17586. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  17587. material.side = DoubleSide;
  17588. } else {
  17589. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  17590. }
  17591. //
  17592. if ( overridePositionNode !== undefined ) {
  17593. scene.overrideMaterial.positionNode = overridePositionNode;
  17594. }
  17595. if ( overrideDepthNode !== undefined ) {
  17596. scene.overrideMaterial.depthNode = overrideDepthNode;
  17597. }
  17598. if ( overrideFragmentNode !== undefined ) {
  17599. scene.overrideMaterial.fragmentNode = overrideFragmentNode;
  17600. }
  17601. //
  17602. object.onAfterRender( this, scene, camera, geometry, material, group );
  17603. }
  17604. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  17605. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  17606. renderObject.drawRange = object.geometry.drawRange;
  17607. renderObject.group = group;
  17608. //
  17609. const needsRefresh = this._nodes.needsRefresh( renderObject );
  17610. if ( needsRefresh ) {
  17611. this._nodes.updateBefore( renderObject );
  17612. this._geometries.updateForRender( renderObject );
  17613. this._nodes.updateForRender( renderObject );
  17614. this._bindings.updateForRender( renderObject );
  17615. }
  17616. this._pipelines.updateForRender( renderObject );
  17617. //
  17618. if ( this._currentRenderBundle !== null ) {
  17619. const renderBundleData = this.backend.get( this._currentRenderBundle );
  17620. renderBundleData.renderObjects.push( renderObject );
  17621. renderObject.bundle = this._currentRenderBundle.scene;
  17622. }
  17623. this.backend.draw( renderObject, this.info );
  17624. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  17625. }
  17626. _createObjectPipeline( object, material, scene, camera, lightsNode, clippingContext, passId ) {
  17627. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  17628. //
  17629. this._nodes.updateBefore( renderObject );
  17630. this._geometries.updateForRender( renderObject );
  17631. this._nodes.updateForRender( renderObject );
  17632. this._bindings.updateForRender( renderObject );
  17633. this._pipelines.getForRender( renderObject, this._compilationPromises );
  17634. this._nodes.updateAfter( renderObject );
  17635. }
  17636. get compile() {
  17637. return this.compileAsync;
  17638. }
  17639. }
  17640. class Binding {
  17641. constructor( name = '' ) {
  17642. this.name = name;
  17643. this.visibility = 0;
  17644. }
  17645. setVisibility( visibility ) {
  17646. this.visibility |= visibility;
  17647. }
  17648. clone() {
  17649. return Object.assign( new this.constructor(), this );
  17650. }
  17651. }
  17652. function getFloatLength( floatLength ) {
  17653. // ensure chunk size alignment (STD140 layout)
  17654. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  17655. }
  17656. class Buffer extends Binding {
  17657. constructor( name, buffer = null ) {
  17658. super( name );
  17659. this.isBuffer = true;
  17660. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  17661. this._buffer = buffer;
  17662. }
  17663. get byteLength() {
  17664. return getFloatLength( this._buffer.byteLength );
  17665. }
  17666. get buffer() {
  17667. return this._buffer;
  17668. }
  17669. update() {
  17670. return true;
  17671. }
  17672. }
  17673. class UniformBuffer extends Buffer {
  17674. constructor( name, buffer = null ) {
  17675. super( name, buffer );
  17676. this.isUniformBuffer = true;
  17677. }
  17678. }
  17679. let _id$4 = 0;
  17680. class NodeUniformBuffer extends UniformBuffer {
  17681. constructor( nodeUniform, groupNode ) {
  17682. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  17683. this.nodeUniform = nodeUniform;
  17684. this.groupNode = groupNode;
  17685. }
  17686. get buffer() {
  17687. return this.nodeUniform.value;
  17688. }
  17689. }
  17690. class UniformsGroup extends UniformBuffer {
  17691. constructor( name ) {
  17692. super( name );
  17693. this.isUniformsGroup = true;
  17694. this._values = null;
  17695. // the order of uniforms in this array must match the order of uniforms in the shader
  17696. this.uniforms = [];
  17697. }
  17698. addUniform( uniform ) {
  17699. this.uniforms.push( uniform );
  17700. return this;
  17701. }
  17702. removeUniform( uniform ) {
  17703. const index = this.uniforms.indexOf( uniform );
  17704. if ( index !== - 1 ) {
  17705. this.uniforms.splice( index, 1 );
  17706. }
  17707. return this;
  17708. }
  17709. get values() {
  17710. if ( this._values === null ) {
  17711. this._values = Array.from( this.buffer );
  17712. }
  17713. return this._values;
  17714. }
  17715. get buffer() {
  17716. let buffer = this._buffer;
  17717. if ( buffer === null ) {
  17718. const byteLength = this.byteLength;
  17719. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  17720. this._buffer = buffer;
  17721. }
  17722. return buffer;
  17723. }
  17724. get byteLength() {
  17725. let offset = 0; // global buffer offset in bytes
  17726. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  17727. const uniform = this.uniforms[ i ];
  17728. const { boundary, itemSize } = uniform;
  17729. // offset within a single chunk in bytes
  17730. const chunkOffset = offset % GPU_CHUNK_BYTES;
  17731. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  17732. // conformance tests
  17733. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  17734. // check for chunk overflow
  17735. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  17736. } else if ( chunkOffset % boundary !== 0 ) {
  17737. // check for correct alignment
  17738. offset += ( chunkOffset % boundary );
  17739. }
  17740. uniform.offset = ( offset / this.bytesPerElement );
  17741. offset += ( itemSize * this.bytesPerElement );
  17742. }
  17743. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  17744. }
  17745. update() {
  17746. let updated = false;
  17747. for ( const uniform of this.uniforms ) {
  17748. if ( this.updateByType( uniform ) === true ) {
  17749. updated = true;
  17750. }
  17751. }
  17752. return updated;
  17753. }
  17754. updateByType( uniform ) {
  17755. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  17756. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  17757. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  17758. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  17759. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  17760. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  17761. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  17762. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  17763. }
  17764. updateNumber( uniform ) {
  17765. let updated = false;
  17766. const a = this.values;
  17767. const v = uniform.getValue();
  17768. const offset = uniform.offset;
  17769. const type = uniform.getType();
  17770. if ( a[ offset ] !== v ) {
  17771. const b = this._getBufferForType( type );
  17772. b[ offset ] = a[ offset ] = v;
  17773. updated = true;
  17774. }
  17775. return updated;
  17776. }
  17777. updateVector2( uniform ) {
  17778. let updated = false;
  17779. const a = this.values;
  17780. const v = uniform.getValue();
  17781. const offset = uniform.offset;
  17782. const type = uniform.getType();
  17783. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  17784. const b = this._getBufferForType( type );
  17785. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  17786. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  17787. updated = true;
  17788. }
  17789. return updated;
  17790. }
  17791. updateVector3( uniform ) {
  17792. let updated = false;
  17793. const a = this.values;
  17794. const v = uniform.getValue();
  17795. const offset = uniform.offset;
  17796. const type = uniform.getType();
  17797. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  17798. const b = this._getBufferForType( type );
  17799. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  17800. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  17801. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  17802. updated = true;
  17803. }
  17804. return updated;
  17805. }
  17806. updateVector4( uniform ) {
  17807. let updated = false;
  17808. const a = this.values;
  17809. const v = uniform.getValue();
  17810. const offset = uniform.offset;
  17811. const type = uniform.getType();
  17812. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  17813. const b = this._getBufferForType( type );
  17814. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  17815. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  17816. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  17817. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  17818. updated = true;
  17819. }
  17820. return updated;
  17821. }
  17822. updateColor( uniform ) {
  17823. let updated = false;
  17824. const a = this.values;
  17825. const c = uniform.getValue();
  17826. const offset = uniform.offset;
  17827. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  17828. const b = this.buffer;
  17829. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  17830. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  17831. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  17832. updated = true;
  17833. }
  17834. return updated;
  17835. }
  17836. updateMatrix3( uniform ) {
  17837. let updated = false;
  17838. const a = this.values;
  17839. const e = uniform.getValue().elements;
  17840. const offset = uniform.offset;
  17841. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  17842. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  17843. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  17844. const b = this.buffer;
  17845. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  17846. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  17847. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  17848. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  17849. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  17850. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  17851. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  17852. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  17853. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  17854. updated = true;
  17855. }
  17856. return updated;
  17857. }
  17858. updateMatrix4( uniform ) {
  17859. let updated = false;
  17860. const a = this.values;
  17861. const e = uniform.getValue().elements;
  17862. const offset = uniform.offset;
  17863. if ( arraysEqual( a, e, offset ) === false ) {
  17864. const b = this.buffer;
  17865. b.set( e, offset );
  17866. setArray( a, e, offset );
  17867. updated = true;
  17868. }
  17869. return updated;
  17870. }
  17871. _getBufferForType( type ) {
  17872. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  17873. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  17874. return this.buffer;
  17875. }
  17876. }
  17877. function setArray( a, b, offset ) {
  17878. for ( let i = 0, l = b.length; i < l; i ++ ) {
  17879. a[ offset + i ] = b[ i ];
  17880. }
  17881. }
  17882. function arraysEqual( a, b, offset ) {
  17883. for ( let i = 0, l = b.length; i < l; i ++ ) {
  17884. if ( a[ offset + i ] !== b[ i ] ) return false;
  17885. }
  17886. return true;
  17887. }
  17888. let _id$3 = 0;
  17889. class NodeUniformsGroup extends UniformsGroup {
  17890. constructor( name, groupNode ) {
  17891. super( name );
  17892. this.id = _id$3 ++;
  17893. this.groupNode = groupNode;
  17894. this.isNodeUniformsGroup = true;
  17895. }
  17896. getNodes() {
  17897. const nodes = [];
  17898. for ( const uniform of this.uniforms ) {
  17899. const node = uniform.nodeUniform.node;
  17900. if ( ! node ) throw new Error( 'NodeUniformsGroup: Uniform has no node.' );
  17901. nodes.push( node );
  17902. }
  17903. return nodes;
  17904. }
  17905. }
  17906. let _id$2 = 0;
  17907. class SampledTexture extends Binding {
  17908. constructor( name, texture ) {
  17909. super( name );
  17910. this.id = _id$2 ++;
  17911. this.texture = texture;
  17912. this.version = texture ? texture.version : 0;
  17913. this.store = false;
  17914. this.generation = null;
  17915. this.isSampledTexture = true;
  17916. }
  17917. needsBindingsUpdate( generation ) {
  17918. const { texture } = this;
  17919. if ( generation !== this.generation ) {
  17920. this.generation = generation;
  17921. return true;
  17922. }
  17923. return texture.isVideoTexture;
  17924. }
  17925. update() {
  17926. const { texture, version } = this;
  17927. if ( version !== texture.version ) {
  17928. this.version = texture.version;
  17929. return true;
  17930. }
  17931. return false;
  17932. }
  17933. }
  17934. class NodeSampledTexture extends SampledTexture {
  17935. constructor( name, textureNode, groupNode, access = null ) {
  17936. super( name, textureNode ? textureNode.value : null );
  17937. this.textureNode = textureNode;
  17938. this.groupNode = groupNode;
  17939. this.access = access;
  17940. }
  17941. needsBindingsUpdate( generation ) {
  17942. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  17943. }
  17944. update() {
  17945. const { textureNode } = this;
  17946. if ( this.texture !== textureNode.value ) {
  17947. this.texture = textureNode.value;
  17948. return true;
  17949. }
  17950. return super.update();
  17951. }
  17952. }
  17953. class NodeSampledCubeTexture extends NodeSampledTexture {
  17954. constructor( name, textureNode, groupNode, access ) {
  17955. super( name, textureNode, groupNode, access );
  17956. this.isSampledCubeTexture = true;
  17957. }
  17958. }
  17959. class NodeSampledTexture3D extends NodeSampledTexture {
  17960. constructor( name, textureNode, groupNode, access ) {
  17961. super( name, textureNode, groupNode, access );
  17962. this.isSampledTexture3D = true;
  17963. }
  17964. }
  17965. const glslMethods = {
  17966. atan2: 'atan',
  17967. textureDimensions: 'textureSize',
  17968. equals: 'equal'
  17969. };
  17970. const precisionLib = {
  17971. low: 'lowp',
  17972. medium: 'mediump',
  17973. high: 'highp'
  17974. };
  17975. const supports$1 = {
  17976. swizzleAssign: true,
  17977. storageBuffer: false
  17978. };
  17979. const defaultPrecisions = `
  17980. precision highp float;
  17981. precision highp int;
  17982. precision highp sampler2D;
  17983. precision highp sampler3D;
  17984. precision highp samplerCube;
  17985. precision highp sampler2DArray;
  17986. precision highp usampler2D;
  17987. precision highp usampler3D;
  17988. precision highp usamplerCube;
  17989. precision highp usampler2DArray;
  17990. precision highp isampler2D;
  17991. precision highp isampler3D;
  17992. precision highp isamplerCube;
  17993. precision highp isampler2DArray;
  17994. precision lowp sampler2DShadow;
  17995. `;
  17996. class GLSLNodeBuilder extends NodeBuilder {
  17997. constructor( object, renderer ) {
  17998. super( object, renderer, new GLSLNodeParser() );
  17999. this.uniformGroups = {};
  18000. this.transforms = [];
  18001. this.extensions = {};
  18002. this.builtins = { vertex: [], fragment: [], compute: [] };
  18003. this.useComparisonMethod = true;
  18004. }
  18005. needsToWorkingColorSpace( texture ) {
  18006. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  18007. }
  18008. getMethod( method ) {
  18009. return glslMethods[ method ] || method;
  18010. }
  18011. getOutputStructName() {
  18012. return '';
  18013. }
  18014. buildFunctionCode( shaderNode ) {
  18015. const layout = shaderNode.layout;
  18016. const flowData = this.flowShaderNode( shaderNode );
  18017. const parameters = [];
  18018. for ( const input of layout.inputs ) {
  18019. parameters.push( this.getType( input.type ) + ' ' + input.name );
  18020. }
  18021. //
  18022. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  18023. ${ flowData.vars }
  18024. ${ flowData.code }
  18025. return ${ flowData.result };
  18026. }`;
  18027. //
  18028. return code;
  18029. }
  18030. setupPBO( storageBufferNode ) {
  18031. const attribute = storageBufferNode.value;
  18032. if ( attribute.pbo === undefined ) {
  18033. const originalArray = attribute.array;
  18034. const numElements = attribute.count * attribute.itemSize;
  18035. const { itemSize } = attribute;
  18036. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  18037. let format = isInteger ? RedIntegerFormat : RedFormat;
  18038. if ( itemSize === 2 ) {
  18039. format = isInteger ? RGIntegerFormat : RGFormat;
  18040. } else if ( itemSize === 3 ) {
  18041. format = isInteger ? RGBIntegerFormat : RGBFormat;
  18042. } else if ( itemSize === 4 ) {
  18043. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  18044. }
  18045. const typeMap = {
  18046. Float32Array: FloatType,
  18047. Uint8Array: UnsignedByteType,
  18048. Uint16Array: UnsignedShortType,
  18049. Uint32Array: UnsignedIntType,
  18050. Int8Array: ByteType,
  18051. Int16Array: ShortType,
  18052. Int32Array: IntType,
  18053. Uint8ClampedArray: UnsignedByteType,
  18054. };
  18055. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  18056. let height = Math.ceil( ( numElements / itemSize ) / width );
  18057. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  18058. const newSize = width * height * itemSize;
  18059. const newArray = new originalArray.constructor( newSize );
  18060. newArray.set( originalArray, 0 );
  18061. attribute.array = newArray;
  18062. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  18063. pboTexture.needsUpdate = true;
  18064. pboTexture.isPBOTexture = true;
  18065. const pbo = new TextureNode( pboTexture, null, null );
  18066. pbo.setPrecision( 'high' );
  18067. attribute.pboNode = pbo;
  18068. attribute.pbo = pbo.value;
  18069. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  18070. }
  18071. }
  18072. getPropertyName( node, shaderStage = this.shaderStage ) {
  18073. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  18074. return shaderStage.charAt( 0 ) + '_' + node.name;
  18075. }
  18076. return super.getPropertyName( node, shaderStage );
  18077. }
  18078. generatePBO( storageArrayElementNode ) {
  18079. const { node, indexNode } = storageArrayElementNode;
  18080. const attribute = node.value;
  18081. if ( this.renderer.backend.has( attribute ) ) {
  18082. const attributeData = this.renderer.backend.get( attribute );
  18083. attributeData.pbo = attribute.pbo;
  18084. }
  18085. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  18086. const textureName = this.getPropertyName( nodeUniform );
  18087. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  18088. const indexSnippet = indexNode.build( this, 'uint' );
  18089. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  18090. let propertyName = elementNodeData.propertyName;
  18091. if ( propertyName === undefined ) {
  18092. // property element
  18093. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  18094. propertyName = this.getPropertyName( nodeVar );
  18095. // property size
  18096. const bufferNodeData = this.getDataFromNode( node );
  18097. let propertySizeName = bufferNodeData.propertySizeName;
  18098. if ( propertySizeName === undefined ) {
  18099. propertySizeName = propertyName + 'Size';
  18100. this.getVarFromNode( node, propertySizeName, 'uint' );
  18101. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  18102. bufferNodeData.propertySizeName = propertySizeName;
  18103. }
  18104. //
  18105. const { itemSize } = attribute;
  18106. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  18107. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  18108. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  18109. //
  18110. let prefix = 'vec4';
  18111. if ( attribute.pbo.type === UnsignedIntType ) {
  18112. prefix = 'uvec4';
  18113. } else if ( attribute.pbo.type === IntType ) {
  18114. prefix = 'ivec4';
  18115. }
  18116. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  18117. elementNodeData.propertyName = propertyName;
  18118. }
  18119. return propertyName;
  18120. }
  18121. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  18122. if ( depthSnippet ) {
  18123. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  18124. } else {
  18125. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  18126. }
  18127. }
  18128. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  18129. if ( texture.isDepthTexture ) {
  18130. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  18131. } else {
  18132. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  18133. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  18134. }
  18135. }
  18136. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  18137. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  18138. }
  18139. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  18140. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  18141. }
  18142. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  18143. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  18144. }
  18145. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  18146. if ( shaderStage === 'fragment' ) {
  18147. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  18148. } else {
  18149. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  18150. }
  18151. }
  18152. getVars( shaderStage ) {
  18153. const snippets = [];
  18154. const vars = this.vars[ shaderStage ];
  18155. if ( vars !== undefined ) {
  18156. for ( const variable of vars ) {
  18157. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  18158. }
  18159. }
  18160. return snippets.join( '\n\t' );
  18161. }
  18162. getUniforms( shaderStage ) {
  18163. const uniforms = this.uniforms[ shaderStage ];
  18164. const bindingSnippets = [];
  18165. const uniformGroups = {};
  18166. for ( const uniform of uniforms ) {
  18167. let snippet = null;
  18168. let group = false;
  18169. if ( uniform.type === 'texture' ) {
  18170. const texture = uniform.node.value;
  18171. let typePrefix = '';
  18172. if ( texture.isDataTexture === true ) {
  18173. if ( texture.type === UnsignedIntType ) {
  18174. typePrefix = 'u';
  18175. } else if ( texture.type === IntType ) {
  18176. typePrefix = 'i';
  18177. }
  18178. }
  18179. if ( texture.compareFunction ) {
  18180. snippet = `sampler2DShadow ${ uniform.name };`;
  18181. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  18182. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  18183. } else {
  18184. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  18185. }
  18186. } else if ( uniform.type === 'cubeTexture' ) {
  18187. snippet = `samplerCube ${ uniform.name };`;
  18188. } else if ( uniform.type === 'texture3D' ) {
  18189. snippet = `sampler3D ${ uniform.name };`;
  18190. } else if ( uniform.type === 'buffer' ) {
  18191. const bufferNode = uniform.node;
  18192. const bufferType = this.getType( bufferNode.bufferType );
  18193. const bufferCount = bufferNode.bufferCount;
  18194. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  18195. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  18196. } else {
  18197. const vectorType = this.getVectorType( uniform.type );
  18198. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  18199. group = true;
  18200. }
  18201. const precision = uniform.node.precision;
  18202. if ( precision !== null ) {
  18203. snippet = precisionLib[ precision ] + ' ' + snippet;
  18204. }
  18205. if ( group ) {
  18206. snippet = '\t' + snippet;
  18207. const groupName = uniform.groupNode.name;
  18208. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  18209. groupSnippets.push( snippet );
  18210. } else {
  18211. snippet = 'uniform ' + snippet;
  18212. bindingSnippets.push( snippet );
  18213. }
  18214. }
  18215. let output = '';
  18216. for ( const name in uniformGroups ) {
  18217. const groupSnippets = uniformGroups[ name ];
  18218. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  18219. }
  18220. output += bindingSnippets.join( '\n' );
  18221. return output;
  18222. }
  18223. getTypeFromAttribute( attribute ) {
  18224. let nodeType = super.getTypeFromAttribute( attribute );
  18225. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  18226. let dataAttribute = attribute;
  18227. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  18228. const array = dataAttribute.array;
  18229. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  18230. nodeType = nodeType.slice( 1 );
  18231. }
  18232. }
  18233. return nodeType;
  18234. }
  18235. getAttributes( shaderStage ) {
  18236. let snippet = '';
  18237. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  18238. const attributes = this.getAttributesArray();
  18239. let location = 0;
  18240. for ( const attribute of attributes ) {
  18241. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  18242. }
  18243. }
  18244. return snippet;
  18245. }
  18246. getStructMembers( struct ) {
  18247. const snippets = [];
  18248. const members = struct.getMemberTypes();
  18249. for ( let i = 0; i < members.length; i ++ ) {
  18250. const member = members[ i ];
  18251. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  18252. }
  18253. return snippets.join( '\n' );
  18254. }
  18255. getStructs( shaderStage ) {
  18256. const snippets = [];
  18257. const structs = this.structs[ shaderStage ];
  18258. if ( structs.length === 0 ) {
  18259. return 'layout( location = 0 ) out vec4 fragColor;\n';
  18260. }
  18261. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  18262. const struct = structs[ index ];
  18263. let snippet = '\n';
  18264. snippet += this.getStructMembers( struct );
  18265. snippet += '\n';
  18266. snippets.push( snippet );
  18267. }
  18268. return snippets.join( '\n\n' );
  18269. }
  18270. getVaryings( shaderStage ) {
  18271. let snippet = '';
  18272. const varyings = this.varyings;
  18273. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  18274. for ( const varying of varyings ) {
  18275. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  18276. const type = this.getType( varying.type );
  18277. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  18278. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  18279. }
  18280. } else if ( shaderStage === 'fragment' ) {
  18281. for ( const varying of varyings ) {
  18282. if ( varying.needsInterpolation ) {
  18283. const type = this.getType( varying.type );
  18284. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  18285. snippet += `${flat}in ${type} ${varying.name};\n`;
  18286. }
  18287. }
  18288. }
  18289. for ( const builtin of this.builtins[ shaderStage ] ) {
  18290. snippet += `${builtin};\n`;
  18291. }
  18292. return snippet;
  18293. }
  18294. getVertexIndex() {
  18295. return 'uint( gl_VertexID )';
  18296. }
  18297. getInstanceIndex() {
  18298. return 'uint( gl_InstanceID )';
  18299. }
  18300. getInvocationLocalIndex() {
  18301. const workgroupSize = this.object.workgroupSize;
  18302. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  18303. return `uint( gl_InstanceID ) % ${size}u`;
  18304. }
  18305. getDrawIndex() {
  18306. const extensions = this.renderer.backend.extensions;
  18307. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  18308. return 'uint( gl_DrawID )';
  18309. }
  18310. return null;
  18311. }
  18312. getFrontFacing() {
  18313. return 'gl_FrontFacing';
  18314. }
  18315. getFragCoord() {
  18316. return 'gl_FragCoord.xy';
  18317. }
  18318. getFragDepth() {
  18319. return 'gl_FragDepth';
  18320. }
  18321. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  18322. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  18323. if ( map.has( name ) === false ) {
  18324. map.set( name, {
  18325. name,
  18326. behavior
  18327. } );
  18328. }
  18329. }
  18330. getExtensions( shaderStage ) {
  18331. const snippets = [];
  18332. if ( shaderStage === 'vertex' ) {
  18333. const ext = this.renderer.backend.extensions;
  18334. const isBatchedMesh = this.object.isBatchedMesh;
  18335. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  18336. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  18337. }
  18338. }
  18339. const extensions = this.extensions[ shaderStage ];
  18340. if ( extensions !== undefined ) {
  18341. for ( const { name, behavior } of extensions.values() ) {
  18342. snippets.push( `#extension ${name} : ${behavior}` );
  18343. }
  18344. }
  18345. return snippets.join( '\n' );
  18346. }
  18347. getClipDistance() {
  18348. return 'gl_ClipDistance';
  18349. }
  18350. isAvailable( name ) {
  18351. let result = supports$1[ name ];
  18352. if ( result === undefined ) {
  18353. let extensionName;
  18354. result = false;
  18355. switch ( name ) {
  18356. case 'float32Filterable':
  18357. extensionName = 'OES_texture_float_linear';
  18358. break;
  18359. case 'clipDistance':
  18360. extensionName = 'WEBGL_clip_cull_distance';
  18361. break;
  18362. }
  18363. if ( extensionName !== undefined ) {
  18364. const extensions = this.renderer.backend.extensions;
  18365. if ( extensions.has( extensionName ) ) {
  18366. extensions.get( extensionName );
  18367. result = true;
  18368. }
  18369. }
  18370. supports$1[ name ] = result;
  18371. }
  18372. return result;
  18373. }
  18374. isFlipY() {
  18375. return true;
  18376. }
  18377. enableHardwareClipping( planeCount ) {
  18378. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  18379. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  18380. }
  18381. registerTransform( varyingName, attributeNode ) {
  18382. this.transforms.push( { varyingName, attributeNode } );
  18383. }
  18384. getTransforms( /* shaderStage */ ) {
  18385. const transforms = this.transforms;
  18386. let snippet = '';
  18387. for ( let i = 0; i < transforms.length; i ++ ) {
  18388. const transform = transforms[ i ];
  18389. const attributeName = this.getPropertyName( transform.attributeNode );
  18390. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  18391. }
  18392. return snippet;
  18393. }
  18394. _getGLSLUniformStruct( name, vars ) {
  18395. return `
  18396. layout( std140 ) uniform ${name} {
  18397. ${vars}
  18398. };`;
  18399. }
  18400. _getGLSLVertexCode( shaderData ) {
  18401. return `#version 300 es
  18402. ${ this.getSignature() }
  18403. // extensions
  18404. ${shaderData.extensions}
  18405. // precision
  18406. ${ defaultPrecisions }
  18407. // uniforms
  18408. ${shaderData.uniforms}
  18409. // varyings
  18410. ${shaderData.varyings}
  18411. // attributes
  18412. ${shaderData.attributes}
  18413. // codes
  18414. ${shaderData.codes}
  18415. void main() {
  18416. // vars
  18417. ${shaderData.vars}
  18418. // transforms
  18419. ${shaderData.transforms}
  18420. // flow
  18421. ${shaderData.flow}
  18422. gl_PointSize = 1.0;
  18423. }
  18424. `;
  18425. }
  18426. _getGLSLFragmentCode( shaderData ) {
  18427. return `#version 300 es
  18428. ${ this.getSignature() }
  18429. // precision
  18430. ${ defaultPrecisions }
  18431. // uniforms
  18432. ${shaderData.uniforms}
  18433. // varyings
  18434. ${shaderData.varyings}
  18435. // codes
  18436. ${shaderData.codes}
  18437. ${shaderData.structs}
  18438. void main() {
  18439. // vars
  18440. ${shaderData.vars}
  18441. // flow
  18442. ${shaderData.flow}
  18443. }
  18444. `;
  18445. }
  18446. buildCode() {
  18447. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  18448. this.sortBindingGroups();
  18449. for ( const shaderStage in shadersData ) {
  18450. let flow = '// code\n\n';
  18451. flow += this.flowCode[ shaderStage ];
  18452. const flowNodes = this.flowNodes[ shaderStage ];
  18453. const mainNode = flowNodes[ flowNodes.length - 1 ];
  18454. for ( const node of flowNodes ) {
  18455. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  18456. const slotName = node.name;
  18457. if ( slotName ) {
  18458. if ( flow.length > 0 ) flow += '\n';
  18459. flow += `\t// flow -> ${ slotName }\n\t`;
  18460. }
  18461. flow += `${ flowSlotData.code }\n\t`;
  18462. if ( node === mainNode && shaderStage !== 'compute' ) {
  18463. flow += '// result\n\t';
  18464. if ( shaderStage === 'vertex' ) {
  18465. flow += 'gl_Position = ';
  18466. flow += `${ flowSlotData.result };`;
  18467. } else if ( shaderStage === 'fragment' ) {
  18468. if ( ! node.outputNode.isOutputStructNode ) {
  18469. flow += 'fragColor = ';
  18470. flow += `${ flowSlotData.result };`;
  18471. }
  18472. }
  18473. }
  18474. }
  18475. const stageData = shadersData[ shaderStage ];
  18476. stageData.extensions = this.getExtensions( shaderStage );
  18477. stageData.uniforms = this.getUniforms( shaderStage );
  18478. stageData.attributes = this.getAttributes( shaderStage );
  18479. stageData.varyings = this.getVaryings( shaderStage );
  18480. stageData.vars = this.getVars( shaderStage );
  18481. stageData.structs = this.getStructs( shaderStage );
  18482. stageData.codes = this.getCodes( shaderStage );
  18483. stageData.transforms = this.getTransforms( shaderStage );
  18484. stageData.flow = flow;
  18485. }
  18486. if ( this.material !== null ) {
  18487. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  18488. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  18489. } else {
  18490. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  18491. }
  18492. }
  18493. getUniformFromNode( node, type, shaderStage, name = null ) {
  18494. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  18495. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  18496. let uniformGPU = nodeData.uniformGPU;
  18497. if ( uniformGPU === undefined ) {
  18498. const group = node.groupNode;
  18499. const groupName = group.name;
  18500. const bindings = this.getBindGroupArray( groupName, shaderStage );
  18501. if ( type === 'texture' ) {
  18502. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  18503. bindings.push( uniformGPU );
  18504. } else if ( type === 'cubeTexture' ) {
  18505. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  18506. bindings.push( uniformGPU );
  18507. } else if ( type === 'texture3D' ) {
  18508. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  18509. bindings.push( uniformGPU );
  18510. } else if ( type === 'buffer' ) {
  18511. node.name = `NodeBuffer_${ node.id }`;
  18512. uniformNode.name = `buffer${ node.id }`;
  18513. const buffer = new NodeUniformBuffer( node, group );
  18514. buffer.name = node.name;
  18515. bindings.push( buffer );
  18516. uniformGPU = buffer;
  18517. } else {
  18518. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  18519. let uniformsGroup = uniformsStage[ groupName ];
  18520. if ( uniformsGroup === undefined ) {
  18521. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  18522. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  18523. uniformsStage[ groupName ] = uniformsGroup;
  18524. bindings.push( uniformsGroup );
  18525. }
  18526. uniformGPU = this.getNodeUniform( uniformNode, type );
  18527. uniformsGroup.addUniform( uniformGPU );
  18528. }
  18529. nodeData.uniformGPU = uniformGPU;
  18530. }
  18531. return uniformNode;
  18532. }
  18533. }
  18534. let vector2 = null;
  18535. let vector4 = null;
  18536. let color4 = null;
  18537. class Backend {
  18538. constructor( parameters = {} ) {
  18539. this.parameters = Object.assign( {}, parameters );
  18540. this.data = new WeakMap();
  18541. this.renderer = null;
  18542. this.domElement = null;
  18543. }
  18544. async init( renderer ) {
  18545. this.renderer = renderer;
  18546. }
  18547. // render context
  18548. begin( /*renderContext*/ ) { }
  18549. finish( /*renderContext*/ ) { }
  18550. // render object
  18551. draw( /*renderObject, info*/ ) { }
  18552. // program
  18553. createProgram( /*program*/ ) { }
  18554. destroyProgram( /*program*/ ) { }
  18555. // bindings
  18556. createBindings( /*bingGroup, bindings*/ ) { }
  18557. updateBindings( /*bingGroup, bindings*/ ) { }
  18558. // pipeline
  18559. createRenderPipeline( /*renderObject*/ ) { }
  18560. createComputePipeline( /*computeNode, pipeline*/ ) { }
  18561. destroyPipeline( /*pipeline*/ ) { }
  18562. // cache key
  18563. needsRenderUpdate( /*renderObject*/ ) { } // return Boolean ( fast test )
  18564. getRenderCacheKey( /*renderObject*/ ) { } // return String
  18565. // node builder
  18566. createNodeBuilder( /*renderObject*/ ) { } // return NodeBuilder (ADD IT)
  18567. // textures
  18568. createSampler( /*texture*/ ) { }
  18569. createDefaultTexture( /*texture*/ ) { }
  18570. createTexture( /*texture*/ ) { }
  18571. copyTextureToBuffer( /*texture, x, y, width, height*/ ) {}
  18572. // attributes
  18573. createAttribute( /*attribute*/ ) { }
  18574. createIndexAttribute( /*attribute*/ ) { }
  18575. updateAttribute( /*attribute*/ ) { }
  18576. destroyAttribute( /*attribute*/ ) { }
  18577. // canvas
  18578. getContext() { }
  18579. updateSize() { }
  18580. // utils
  18581. resolveTimestampAsync( /*renderContext, type*/ ) { }
  18582. hasFeatureAsync( /*name*/ ) { } // return Boolean
  18583. hasFeature( /*name*/ ) { } // return Boolean
  18584. getInstanceCount( renderObject ) {
  18585. const { object, geometry } = renderObject;
  18586. return geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  18587. }
  18588. getDrawingBufferSize() {
  18589. vector2 = vector2 || new Vector2();
  18590. return this.renderer.getDrawingBufferSize( vector2 );
  18591. }
  18592. getScissor() {
  18593. vector4 = vector4 || new Vector4();
  18594. return this.renderer.getScissor( vector4 );
  18595. }
  18596. setScissorTest( /*boolean*/ ) { }
  18597. getClearColor() {
  18598. const renderer = this.renderer;
  18599. color4 = color4 || new Color4();
  18600. renderer.getClearColor( color4 );
  18601. color4.getRGB( color4, this.renderer.currentColorSpace );
  18602. return color4;
  18603. }
  18604. getDomElement() {
  18605. let domElement = this.domElement;
  18606. if ( domElement === null ) {
  18607. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  18608. // OffscreenCanvas does not have setAttribute, see #22811
  18609. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  18610. this.domElement = domElement;
  18611. }
  18612. return domElement;
  18613. }
  18614. // resource properties
  18615. set( object, value ) {
  18616. this.data.set( object, value );
  18617. }
  18618. get( object ) {
  18619. let map = this.data.get( object );
  18620. if ( map === undefined ) {
  18621. map = {};
  18622. this.data.set( object, map );
  18623. }
  18624. return map;
  18625. }
  18626. has( object ) {
  18627. return this.data.has( object );
  18628. }
  18629. delete( object ) {
  18630. this.data.delete( object );
  18631. }
  18632. dispose() { }
  18633. }
  18634. let _id$1 = 0;
  18635. class DualAttributeData {
  18636. constructor( attributeData, dualBuffer ) {
  18637. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  18638. this.type = attributeData.type;
  18639. this.bufferType = attributeData.bufferType;
  18640. this.pbo = attributeData.pbo;
  18641. this.byteLength = attributeData.byteLength;
  18642. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  18643. this.version = attributeData.version;
  18644. this.isInteger = attributeData.isInteger;
  18645. this.activeBufferIndex = 0;
  18646. this.baseId = attributeData.id;
  18647. }
  18648. get id() {
  18649. return `${ this.baseId }|${ this.activeBufferIndex }`;
  18650. }
  18651. get bufferGPU() {
  18652. return this.buffers[ this.activeBufferIndex ];
  18653. }
  18654. get transformBuffer() {
  18655. return this.buffers[ this.activeBufferIndex ^ 1 ];
  18656. }
  18657. switchBuffers() {
  18658. this.activeBufferIndex ^= 1;
  18659. }
  18660. }
  18661. class WebGLAttributeUtils {
  18662. constructor( backend ) {
  18663. this.backend = backend;
  18664. }
  18665. createAttribute( attribute, bufferType ) {
  18666. const backend = this.backend;
  18667. const { gl } = backend;
  18668. const array = attribute.array;
  18669. const usage = attribute.usage || gl.STATIC_DRAW;
  18670. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  18671. const bufferData = backend.get( bufferAttribute );
  18672. let bufferGPU = bufferData.bufferGPU;
  18673. if ( bufferGPU === undefined ) {
  18674. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  18675. bufferData.bufferGPU = bufferGPU;
  18676. bufferData.bufferType = bufferType;
  18677. bufferData.version = bufferAttribute.version;
  18678. }
  18679. //attribute.onUploadCallback();
  18680. let type;
  18681. if ( array instanceof Float32Array ) {
  18682. type = gl.FLOAT;
  18683. } else if ( array instanceof Uint16Array ) {
  18684. if ( attribute.isFloat16BufferAttribute ) {
  18685. type = gl.HALF_FLOAT;
  18686. } else {
  18687. type = gl.UNSIGNED_SHORT;
  18688. }
  18689. } else if ( array instanceof Int16Array ) {
  18690. type = gl.SHORT;
  18691. } else if ( array instanceof Uint32Array ) {
  18692. type = gl.UNSIGNED_INT;
  18693. } else if ( array instanceof Int32Array ) {
  18694. type = gl.INT;
  18695. } else if ( array instanceof Int8Array ) {
  18696. type = gl.BYTE;
  18697. } else if ( array instanceof Uint8Array ) {
  18698. type = gl.UNSIGNED_BYTE;
  18699. } else if ( array instanceof Uint8ClampedArray ) {
  18700. type = gl.UNSIGNED_BYTE;
  18701. } else {
  18702. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  18703. }
  18704. let attributeData = {
  18705. bufferGPU,
  18706. bufferType,
  18707. type,
  18708. byteLength: array.byteLength,
  18709. bytesPerElement: array.BYTES_PER_ELEMENT,
  18710. version: attribute.version,
  18711. pbo: attribute.pbo,
  18712. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  18713. id: _id$1 ++
  18714. };
  18715. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  18716. // create buffer for tranform feedback use
  18717. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  18718. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  18719. }
  18720. backend.set( attribute, attributeData );
  18721. }
  18722. updateAttribute( attribute ) {
  18723. const backend = this.backend;
  18724. const { gl } = backend;
  18725. const array = attribute.array;
  18726. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  18727. const bufferData = backend.get( bufferAttribute );
  18728. const bufferType = bufferData.bufferType;
  18729. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  18730. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  18731. if ( updateRanges.length === 0 ) {
  18732. // Not using update ranges
  18733. gl.bufferSubData( bufferType, 0, array );
  18734. } else {
  18735. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  18736. const range = updateRanges[ i ];
  18737. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  18738. array, range.start, range.count );
  18739. }
  18740. bufferAttribute.clearUpdateRanges();
  18741. }
  18742. gl.bindBuffer( bufferType, null );
  18743. bufferData.version = bufferAttribute.version;
  18744. }
  18745. destroyAttribute( attribute ) {
  18746. const backend = this.backend;
  18747. const { gl } = backend;
  18748. if ( attribute.isInterleavedBufferAttribute ) {
  18749. backend.delete( attribute.data );
  18750. }
  18751. const attributeData = backend.get( attribute );
  18752. gl.deleteBuffer( attributeData.bufferGPU );
  18753. backend.delete( attribute );
  18754. }
  18755. async getArrayBufferAsync( attribute ) {
  18756. const backend = this.backend;
  18757. const { gl } = backend;
  18758. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  18759. const { bufferGPU } = backend.get( bufferAttribute );
  18760. const array = attribute.array;
  18761. const byteLength = array.byteLength;
  18762. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  18763. const writeBuffer = gl.createBuffer();
  18764. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  18765. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  18766. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  18767. await backend.utils._clientWaitAsync();
  18768. const dstBuffer = new attribute.array.constructor( array.length );
  18769. // Ensure the buffer is bound before reading
  18770. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  18771. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  18772. gl.deleteBuffer( writeBuffer );
  18773. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  18774. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  18775. return dstBuffer.buffer;
  18776. }
  18777. _createBuffer( gl, bufferType, array, usage ) {
  18778. const bufferGPU = gl.createBuffer();
  18779. gl.bindBuffer( bufferType, bufferGPU );
  18780. gl.bufferData( bufferType, array, usage );
  18781. gl.bindBuffer( bufferType, null );
  18782. return bufferGPU;
  18783. }
  18784. }
  18785. let initialized$1 = false, equationToGL, factorToGL;
  18786. class WebGLState {
  18787. constructor( backend ) {
  18788. this.backend = backend;
  18789. this.gl = this.backend.gl;
  18790. this.enabled = {};
  18791. this.currentFlipSided = null;
  18792. this.currentCullFace = null;
  18793. this.currentProgram = null;
  18794. this.currentBlendingEnabled = false;
  18795. this.currentBlending = null;
  18796. this.currentBlendSrc = null;
  18797. this.currentBlendDst = null;
  18798. this.currentBlendSrcAlpha = null;
  18799. this.currentBlendDstAlpha = null;
  18800. this.currentPremultipledAlpha = null;
  18801. this.currentPolygonOffsetFactor = null;
  18802. this.currentPolygonOffsetUnits = null;
  18803. this.currentColorMask = null;
  18804. this.currentDepthFunc = null;
  18805. this.currentDepthMask = null;
  18806. this.currentStencilFunc = null;
  18807. this.currentStencilRef = null;
  18808. this.currentStencilFuncMask = null;
  18809. this.currentStencilFail = null;
  18810. this.currentStencilZFail = null;
  18811. this.currentStencilZPass = null;
  18812. this.currentStencilMask = null;
  18813. this.currentLineWidth = null;
  18814. this.currentClippingPlanes = 0;
  18815. this.currentBoundFramebuffers = {};
  18816. this.currentDrawbuffers = new WeakMap();
  18817. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  18818. this.currentTextureSlot = null;
  18819. this.currentBoundTextures = {};
  18820. this.currentBoundBufferBases = {};
  18821. if ( initialized$1 === false ) {
  18822. this._init( this.gl );
  18823. initialized$1 = true;
  18824. }
  18825. }
  18826. _init( gl ) {
  18827. // Store only WebGL constants here.
  18828. equationToGL = {
  18829. [ AddEquation ]: gl.FUNC_ADD,
  18830. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  18831. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  18832. };
  18833. factorToGL = {
  18834. [ ZeroFactor ]: gl.ZERO,
  18835. [ OneFactor ]: gl.ONE,
  18836. [ SrcColorFactor ]: gl.SRC_COLOR,
  18837. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  18838. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  18839. [ DstColorFactor ]: gl.DST_COLOR,
  18840. [ DstAlphaFactor ]: gl.DST_ALPHA,
  18841. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  18842. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  18843. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  18844. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  18845. };
  18846. }
  18847. enable( id ) {
  18848. const { enabled } = this;
  18849. if ( enabled[ id ] !== true ) {
  18850. this.gl.enable( id );
  18851. enabled[ id ] = true;
  18852. }
  18853. }
  18854. disable( id ) {
  18855. const { enabled } = this;
  18856. if ( enabled[ id ] !== false ) {
  18857. this.gl.disable( id );
  18858. enabled[ id ] = false;
  18859. }
  18860. }
  18861. setFlipSided( flipSided ) {
  18862. if ( this.currentFlipSided !== flipSided ) {
  18863. const { gl } = this;
  18864. if ( flipSided ) {
  18865. gl.frontFace( gl.CW );
  18866. } else {
  18867. gl.frontFace( gl.CCW );
  18868. }
  18869. this.currentFlipSided = flipSided;
  18870. }
  18871. }
  18872. setCullFace( cullFace ) {
  18873. const { gl } = this;
  18874. if ( cullFace !== CullFaceNone ) {
  18875. this.enable( gl.CULL_FACE );
  18876. if ( cullFace !== this.currentCullFace ) {
  18877. if ( cullFace === CullFaceBack ) {
  18878. gl.cullFace( gl.BACK );
  18879. } else if ( cullFace === CullFaceFront ) {
  18880. gl.cullFace( gl.FRONT );
  18881. } else {
  18882. gl.cullFace( gl.FRONT_AND_BACK );
  18883. }
  18884. }
  18885. } else {
  18886. this.disable( gl.CULL_FACE );
  18887. }
  18888. this.currentCullFace = cullFace;
  18889. }
  18890. setLineWidth( width ) {
  18891. const { currentLineWidth, gl } = this;
  18892. if ( width !== currentLineWidth ) {
  18893. gl.lineWidth( width );
  18894. this.currentLineWidth = width;
  18895. }
  18896. }
  18897. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  18898. const { gl } = this;
  18899. if ( blending === NoBlending ) {
  18900. if ( this.currentBlendingEnabled === true ) {
  18901. this.disable( gl.BLEND );
  18902. this.currentBlendingEnabled = false;
  18903. }
  18904. return;
  18905. }
  18906. if ( this.currentBlendingEnabled === false ) {
  18907. this.enable( gl.BLEND );
  18908. this.currentBlendingEnabled = true;
  18909. }
  18910. if ( blending !== CustomBlending ) {
  18911. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  18912. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  18913. gl.blendEquation( gl.FUNC_ADD );
  18914. this.currentBlendEquation = AddEquation;
  18915. this.currentBlendEquationAlpha = AddEquation;
  18916. }
  18917. if ( premultipliedAlpha ) {
  18918. switch ( blending ) {
  18919. case NormalBlending:
  18920. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  18921. break;
  18922. case AdditiveBlending:
  18923. gl.blendFunc( gl.ONE, gl.ONE );
  18924. break;
  18925. case SubtractiveBlending:
  18926. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  18927. break;
  18928. case MultiplyBlending:
  18929. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  18930. break;
  18931. default:
  18932. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  18933. break;
  18934. }
  18935. } else {
  18936. switch ( blending ) {
  18937. case NormalBlending:
  18938. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  18939. break;
  18940. case AdditiveBlending:
  18941. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  18942. break;
  18943. case SubtractiveBlending:
  18944. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  18945. break;
  18946. case MultiplyBlending:
  18947. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  18948. break;
  18949. default:
  18950. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  18951. break;
  18952. }
  18953. }
  18954. this.currentBlendSrc = null;
  18955. this.currentBlendDst = null;
  18956. this.currentBlendSrcAlpha = null;
  18957. this.currentBlendDstAlpha = null;
  18958. this.currentBlending = blending;
  18959. this.currentPremultipledAlpha = premultipliedAlpha;
  18960. }
  18961. return;
  18962. }
  18963. // custom blending
  18964. blendEquationAlpha = blendEquationAlpha || blendEquation;
  18965. blendSrcAlpha = blendSrcAlpha || blendSrc;
  18966. blendDstAlpha = blendDstAlpha || blendDst;
  18967. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  18968. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  18969. this.currentBlendEquation = blendEquation;
  18970. this.currentBlendEquationAlpha = blendEquationAlpha;
  18971. }
  18972. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  18973. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  18974. this.currentBlendSrc = blendSrc;
  18975. this.currentBlendDst = blendDst;
  18976. this.currentBlendSrcAlpha = blendSrcAlpha;
  18977. this.currentBlendDstAlpha = blendDstAlpha;
  18978. }
  18979. this.currentBlending = blending;
  18980. this.currentPremultipledAlpha = false;
  18981. }
  18982. setColorMask( colorMask ) {
  18983. if ( this.currentColorMask !== colorMask ) {
  18984. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  18985. this.currentColorMask = colorMask;
  18986. }
  18987. }
  18988. setDepthTest( depthTest ) {
  18989. const { gl } = this;
  18990. if ( depthTest ) {
  18991. this.enable( gl.DEPTH_TEST );
  18992. } else {
  18993. this.disable( gl.DEPTH_TEST );
  18994. }
  18995. }
  18996. setDepthMask( depthMask ) {
  18997. if ( this.currentDepthMask !== depthMask ) {
  18998. this.gl.depthMask( depthMask );
  18999. this.currentDepthMask = depthMask;
  19000. }
  19001. }
  19002. setDepthFunc( depthFunc ) {
  19003. if ( this.currentDepthFunc !== depthFunc ) {
  19004. const { gl } = this;
  19005. switch ( depthFunc ) {
  19006. case NeverDepth:
  19007. gl.depthFunc( gl.NEVER );
  19008. break;
  19009. case AlwaysDepth:
  19010. gl.depthFunc( gl.ALWAYS );
  19011. break;
  19012. case LessDepth:
  19013. gl.depthFunc( gl.LESS );
  19014. break;
  19015. case LessEqualDepth:
  19016. gl.depthFunc( gl.LEQUAL );
  19017. break;
  19018. case EqualDepth:
  19019. gl.depthFunc( gl.EQUAL );
  19020. break;
  19021. case GreaterEqualDepth:
  19022. gl.depthFunc( gl.GEQUAL );
  19023. break;
  19024. case GreaterDepth:
  19025. gl.depthFunc( gl.GREATER );
  19026. break;
  19027. case NotEqualDepth:
  19028. gl.depthFunc( gl.NOTEQUAL );
  19029. break;
  19030. default:
  19031. gl.depthFunc( gl.LEQUAL );
  19032. }
  19033. this.currentDepthFunc = depthFunc;
  19034. }
  19035. }
  19036. setStencilTest( stencilTest ) {
  19037. const { gl } = this;
  19038. if ( stencilTest ) {
  19039. this.enable( gl.STENCIL_TEST );
  19040. } else {
  19041. this.disable( gl.STENCIL_TEST );
  19042. }
  19043. }
  19044. setStencilMask( stencilMask ) {
  19045. if ( this.currentStencilMask !== stencilMask ) {
  19046. this.gl.stencilMask( stencilMask );
  19047. this.currentStencilMask = stencilMask;
  19048. }
  19049. }
  19050. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  19051. if ( this.currentStencilFunc !== stencilFunc ||
  19052. this.currentStencilRef !== stencilRef ||
  19053. this.currentStencilFuncMask !== stencilMask ) {
  19054. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  19055. this.currentStencilFunc = stencilFunc;
  19056. this.currentStencilRef = stencilRef;
  19057. this.currentStencilFuncMask = stencilMask;
  19058. }
  19059. }
  19060. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  19061. if ( this.currentStencilFail !== stencilFail ||
  19062. this.currentStencilZFail !== stencilZFail ||
  19063. this.currentStencilZPass !== stencilZPass ) {
  19064. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  19065. this.currentStencilFail = stencilFail;
  19066. this.currentStencilZFail = stencilZFail;
  19067. this.currentStencilZPass = stencilZPass;
  19068. }
  19069. }
  19070. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  19071. const { gl } = this;
  19072. material.side === DoubleSide
  19073. ? this.disable( gl.CULL_FACE )
  19074. : this.enable( gl.CULL_FACE );
  19075. let flipSided = ( material.side === BackSide );
  19076. if ( frontFaceCW ) flipSided = ! flipSided;
  19077. this.setFlipSided( flipSided );
  19078. ( material.blending === NormalBlending && material.transparent === false )
  19079. ? this.setBlending( NoBlending )
  19080. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  19081. this.setDepthFunc( material.depthFunc );
  19082. this.setDepthTest( material.depthTest );
  19083. this.setDepthMask( material.depthWrite );
  19084. this.setColorMask( material.colorWrite );
  19085. const stencilWrite = material.stencilWrite;
  19086. this.setStencilTest( stencilWrite );
  19087. if ( stencilWrite ) {
  19088. this.setStencilMask( material.stencilWriteMask );
  19089. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  19090. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  19091. }
  19092. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  19093. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  19094. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  19095. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  19096. if ( hardwareClippingPlanes > 0 ) {
  19097. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  19098. const CLIP_DISTANCE0_WEBGL = 0x3000;
  19099. for ( let i = 0; i < 8; i ++ ) {
  19100. if ( i < hardwareClippingPlanes ) {
  19101. this.enable( CLIP_DISTANCE0_WEBGL + i );
  19102. } else {
  19103. this.disable( CLIP_DISTANCE0_WEBGL + i );
  19104. }
  19105. }
  19106. }
  19107. }
  19108. }
  19109. setPolygonOffset( polygonOffset, factor, units ) {
  19110. const { gl } = this;
  19111. if ( polygonOffset ) {
  19112. this.enable( gl.POLYGON_OFFSET_FILL );
  19113. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  19114. gl.polygonOffset( factor, units );
  19115. this.currentPolygonOffsetFactor = factor;
  19116. this.currentPolygonOffsetUnits = units;
  19117. }
  19118. } else {
  19119. this.disable( gl.POLYGON_OFFSET_FILL );
  19120. }
  19121. }
  19122. useProgram( program ) {
  19123. if ( this.currentProgram !== program ) {
  19124. this.gl.useProgram( program );
  19125. this.currentProgram = program;
  19126. return true;
  19127. }
  19128. return false;
  19129. }
  19130. // framebuffer
  19131. bindFramebuffer( target, framebuffer ) {
  19132. const { gl, currentBoundFramebuffers } = this;
  19133. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  19134. gl.bindFramebuffer( target, framebuffer );
  19135. currentBoundFramebuffers[ target ] = framebuffer;
  19136. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  19137. if ( target === gl.DRAW_FRAMEBUFFER ) {
  19138. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  19139. }
  19140. if ( target === gl.FRAMEBUFFER ) {
  19141. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  19142. }
  19143. return true;
  19144. }
  19145. return false;
  19146. }
  19147. drawBuffers( renderContext, framebuffer ) {
  19148. const { gl } = this;
  19149. let drawBuffers = [];
  19150. let needsUpdate = false;
  19151. if ( renderContext.textures !== null ) {
  19152. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  19153. if ( drawBuffers === undefined ) {
  19154. drawBuffers = [];
  19155. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  19156. }
  19157. const textures = renderContext.textures;
  19158. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  19159. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  19160. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  19161. }
  19162. drawBuffers.length = textures.length;
  19163. needsUpdate = true;
  19164. }
  19165. } else {
  19166. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  19167. drawBuffers[ 0 ] = gl.BACK;
  19168. needsUpdate = true;
  19169. }
  19170. }
  19171. if ( needsUpdate ) {
  19172. gl.drawBuffers( drawBuffers );
  19173. }
  19174. }
  19175. // texture
  19176. activeTexture( webglSlot ) {
  19177. const { gl, currentTextureSlot, maxTextures } = this;
  19178. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  19179. if ( currentTextureSlot !== webglSlot ) {
  19180. gl.activeTexture( webglSlot );
  19181. this.currentTextureSlot = webglSlot;
  19182. }
  19183. }
  19184. bindTexture( webglType, webglTexture, webglSlot ) {
  19185. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  19186. if ( webglSlot === undefined ) {
  19187. if ( currentTextureSlot === null ) {
  19188. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  19189. } else {
  19190. webglSlot = currentTextureSlot;
  19191. }
  19192. }
  19193. let boundTexture = currentBoundTextures[ webglSlot ];
  19194. if ( boundTexture === undefined ) {
  19195. boundTexture = { type: undefined, texture: undefined };
  19196. currentBoundTextures[ webglSlot ] = boundTexture;
  19197. }
  19198. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  19199. if ( currentTextureSlot !== webglSlot ) {
  19200. gl.activeTexture( webglSlot );
  19201. this.currentTextureSlot = webglSlot;
  19202. }
  19203. gl.bindTexture( webglType, webglTexture );
  19204. boundTexture.type = webglType;
  19205. boundTexture.texture = webglTexture;
  19206. }
  19207. }
  19208. bindBufferBase( target, index, buffer ) {
  19209. const { gl } = this;
  19210. const key = `${target}-${index}`;
  19211. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  19212. gl.bindBufferBase( target, index, buffer );
  19213. this.currentBoundBufferBases[ key ] = buffer;
  19214. return true;
  19215. }
  19216. return false;
  19217. }
  19218. unbindTexture() {
  19219. const { gl, currentTextureSlot, currentBoundTextures } = this;
  19220. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  19221. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  19222. gl.bindTexture( boundTexture.type, null );
  19223. boundTexture.type = undefined;
  19224. boundTexture.texture = undefined;
  19225. }
  19226. }
  19227. }
  19228. class WebGLUtils {
  19229. constructor( backend ) {
  19230. this.backend = backend;
  19231. this.gl = this.backend.gl;
  19232. this.extensions = backend.extensions;
  19233. }
  19234. convert( p, colorSpace = NoColorSpace ) {
  19235. const { gl, extensions } = this;
  19236. let extension;
  19237. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  19238. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  19239. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  19240. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  19241. if ( p === ByteType ) return gl.BYTE;
  19242. if ( p === ShortType ) return gl.SHORT;
  19243. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  19244. if ( p === IntType ) return gl.INT;
  19245. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  19246. if ( p === FloatType ) return gl.FLOAT;
  19247. if ( p === HalfFloatType ) {
  19248. return gl.HALF_FLOAT;
  19249. }
  19250. if ( p === AlphaFormat ) return gl.ALPHA;
  19251. if ( p === RGBFormat ) return gl.RGB;
  19252. if ( p === RGBAFormat ) return gl.RGBA;
  19253. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  19254. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  19255. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  19256. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  19257. // WebGL2 formats.
  19258. if ( p === RedFormat ) return gl.RED;
  19259. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  19260. if ( p === RGFormat ) return gl.RG;
  19261. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  19262. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  19263. // S3TC
  19264. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  19265. if ( colorSpace === SRGBColorSpace ) {
  19266. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  19267. if ( extension !== null ) {
  19268. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  19269. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  19270. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  19271. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  19272. } else {
  19273. return null;
  19274. }
  19275. } else {
  19276. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  19277. if ( extension !== null ) {
  19278. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  19279. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  19280. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  19281. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  19282. } else {
  19283. return null;
  19284. }
  19285. }
  19286. }
  19287. // PVRTC
  19288. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  19289. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  19290. if ( extension !== null ) {
  19291. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  19292. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  19293. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  19294. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  19295. } else {
  19296. return null;
  19297. }
  19298. }
  19299. // ETC
  19300. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  19301. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  19302. if ( extension !== null ) {
  19303. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  19304. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  19305. } else {
  19306. return null;
  19307. }
  19308. }
  19309. // ASTC
  19310. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  19311. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  19312. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  19313. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  19314. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  19315. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  19316. if ( extension !== null ) {
  19317. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  19318. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  19319. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  19320. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  19321. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  19322. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  19323. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  19324. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  19325. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  19326. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  19327. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  19328. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  19329. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  19330. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  19331. } else {
  19332. return null;
  19333. }
  19334. }
  19335. // BPTC
  19336. if ( p === RGBA_BPTC_Format ) {
  19337. extension = extensions.get( 'EXT_texture_compression_bptc' );
  19338. if ( extension !== null ) {
  19339. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  19340. } else {
  19341. return null;
  19342. }
  19343. }
  19344. // RGTC
  19345. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  19346. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  19347. if ( extension !== null ) {
  19348. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  19349. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  19350. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  19351. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  19352. } else {
  19353. return null;
  19354. }
  19355. }
  19356. //
  19357. if ( p === UnsignedInt248Type ) {
  19358. return gl.UNSIGNED_INT_24_8;
  19359. }
  19360. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  19361. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  19362. }
  19363. _clientWaitAsync() {
  19364. const { gl } = this;
  19365. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  19366. gl.flush();
  19367. return new Promise( ( resolve, reject ) => {
  19368. function test() {
  19369. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  19370. if ( res === gl.WAIT_FAILED ) {
  19371. gl.deleteSync( sync );
  19372. reject();
  19373. return;
  19374. }
  19375. if ( res === gl.TIMEOUT_EXPIRED ) {
  19376. requestAnimationFrame( test );
  19377. return;
  19378. }
  19379. gl.deleteSync( sync );
  19380. resolve();
  19381. }
  19382. test();
  19383. } );
  19384. }
  19385. }
  19386. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  19387. class WebGLTextureUtils {
  19388. constructor( backend ) {
  19389. this.backend = backend;
  19390. this.gl = backend.gl;
  19391. this.extensions = backend.extensions;
  19392. this.defaultTextures = {};
  19393. if ( initialized === false ) {
  19394. this._init( this.gl );
  19395. initialized = true;
  19396. }
  19397. }
  19398. _init( gl ) {
  19399. // Store only WebGL constants here.
  19400. wrappingToGL = {
  19401. [ RepeatWrapping ]: gl.REPEAT,
  19402. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  19403. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  19404. };
  19405. filterToGL = {
  19406. [ NearestFilter ]: gl.NEAREST,
  19407. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  19408. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  19409. [ LinearFilter ]: gl.LINEAR,
  19410. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  19411. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  19412. };
  19413. compareToGL = {
  19414. [ NeverCompare ]: gl.NEVER,
  19415. [ AlwaysCompare ]: gl.ALWAYS,
  19416. [ LessCompare ]: gl.LESS,
  19417. [ LessEqualCompare ]: gl.LEQUAL,
  19418. [ EqualCompare ]: gl.EQUAL,
  19419. [ GreaterEqualCompare ]: gl.GEQUAL,
  19420. [ GreaterCompare ]: gl.GREATER,
  19421. [ NotEqualCompare ]: gl.NOTEQUAL
  19422. };
  19423. }
  19424. filterFallback( f ) {
  19425. const { gl } = this;
  19426. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  19427. return gl.NEAREST;
  19428. }
  19429. return gl.LINEAR;
  19430. }
  19431. getGLTextureType( texture ) {
  19432. const { gl } = this;
  19433. let glTextureType;
  19434. if ( texture.isCubeTexture === true ) {
  19435. glTextureType = gl.TEXTURE_CUBE_MAP;
  19436. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  19437. glTextureType = gl.TEXTURE_2D_ARRAY;
  19438. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  19439. glTextureType = gl.TEXTURE_3D;
  19440. } else {
  19441. glTextureType = gl.TEXTURE_2D;
  19442. }
  19443. return glTextureType;
  19444. }
  19445. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  19446. const { gl, extensions } = this;
  19447. if ( internalFormatName !== null ) {
  19448. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  19449. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  19450. }
  19451. let internalFormat = glFormat;
  19452. if ( glFormat === gl.RED ) {
  19453. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  19454. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  19455. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  19456. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  19457. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  19458. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  19459. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  19460. if ( glType === gl.INT ) internalFormat = gl.R32I;
  19461. }
  19462. if ( glFormat === gl.RED_INTEGER ) {
  19463. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  19464. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  19465. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  19466. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  19467. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  19468. if ( glType === gl.INT ) internalFormat = gl.R32I;
  19469. }
  19470. if ( glFormat === gl.RG ) {
  19471. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  19472. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  19473. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  19474. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  19475. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  19476. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  19477. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  19478. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  19479. }
  19480. if ( glFormat === gl.RG_INTEGER ) {
  19481. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  19482. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  19483. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  19484. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  19485. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  19486. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  19487. }
  19488. if ( glFormat === gl.RGB ) {
  19489. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  19490. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  19491. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  19492. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  19493. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  19494. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  19495. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  19496. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  19497. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  19498. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  19499. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  19500. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  19501. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  19502. }
  19503. if ( glFormat === gl.RGB_INTEGER ) {
  19504. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  19505. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  19506. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  19507. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  19508. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  19509. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  19510. }
  19511. if ( glFormat === gl.RGBA ) {
  19512. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  19513. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  19514. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  19515. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  19516. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  19517. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  19518. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  19519. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  19520. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  19521. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  19522. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  19523. }
  19524. if ( glFormat === gl.RGBA_INTEGER ) {
  19525. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  19526. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  19527. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  19528. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  19529. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  19530. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  19531. }
  19532. if ( glFormat === gl.DEPTH_COMPONENT ) {
  19533. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  19534. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  19535. }
  19536. if ( glFormat === gl.DEPTH_STENCIL ) {
  19537. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  19538. }
  19539. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  19540. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  19541. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  19542. extensions.get( 'EXT_color_buffer_float' );
  19543. }
  19544. return internalFormat;
  19545. }
  19546. setTextureParameters( textureType, texture ) {
  19547. const { gl, extensions, backend } = this;
  19548. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  19549. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  19550. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  19551. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  19552. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  19553. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  19554. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  19555. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  19556. }
  19557. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  19558. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  19559. // follow WebGPU backend mapping for texture filtering
  19560. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  19561. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  19562. if ( texture.compareFunction ) {
  19563. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  19564. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  19565. }
  19566. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  19567. if ( texture.magFilter === NearestFilter ) return;
  19568. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  19569. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  19570. if ( texture.anisotropy > 1 ) {
  19571. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  19572. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  19573. }
  19574. }
  19575. }
  19576. createDefaultTexture( texture ) {
  19577. const { gl, backend, defaultTextures } = this;
  19578. const glTextureType = this.getGLTextureType( texture );
  19579. let textureGPU = defaultTextures[ glTextureType ];
  19580. if ( textureGPU === undefined ) {
  19581. textureGPU = gl.createTexture();
  19582. backend.state.bindTexture( glTextureType, textureGPU );
  19583. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  19584. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  19585. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  19586. defaultTextures[ glTextureType ] = textureGPU;
  19587. }
  19588. backend.set( texture, {
  19589. textureGPU,
  19590. glTextureType,
  19591. isDefault: true
  19592. } );
  19593. }
  19594. createTexture( texture, options ) {
  19595. const { gl, backend } = this;
  19596. const { levels, width, height, depth } = options;
  19597. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  19598. const glType = backend.utils.convert( texture.type );
  19599. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  19600. const textureGPU = gl.createTexture();
  19601. const glTextureType = this.getGLTextureType( texture );
  19602. backend.state.bindTexture( glTextureType, textureGPU );
  19603. this.setTextureParameters( glTextureType, texture );
  19604. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  19605. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  19606. } else if ( texture.isData3DTexture ) {
  19607. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  19608. } else if ( ! texture.isVideoTexture ) {
  19609. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  19610. }
  19611. backend.set( texture, {
  19612. textureGPU,
  19613. glTextureType,
  19614. glFormat,
  19615. glType,
  19616. glInternalFormat
  19617. } );
  19618. }
  19619. copyBufferToTexture( buffer, texture ) {
  19620. const { gl, backend } = this;
  19621. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  19622. const { width, height } = texture.source.data;
  19623. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  19624. backend.state.bindTexture( glTextureType, textureGPU );
  19625. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  19626. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  19627. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  19628. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  19629. backend.state.unbindTexture();
  19630. // debug
  19631. // const framebuffer = gl.createFramebuffer();
  19632. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  19633. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  19634. // const readout = new Float32Array( width * height * 4 );
  19635. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  19636. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  19637. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  19638. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  19639. // console.log( readout );
  19640. }
  19641. updateTexture( texture, options ) {
  19642. const { gl } = this;
  19643. const { width, height } = options;
  19644. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  19645. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  19646. return;
  19647. const getImage = ( source ) => {
  19648. if ( source.isDataTexture ) {
  19649. return source.image.data;
  19650. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  19651. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  19652. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  19653. source instanceof OffscreenCanvas ) {
  19654. return source;
  19655. }
  19656. return source.data;
  19657. };
  19658. this.backend.state.bindTexture( glTextureType, textureGPU );
  19659. this.setTextureParameters( glTextureType, texture );
  19660. if ( texture.isCompressedTexture ) {
  19661. const mipmaps = texture.mipmaps;
  19662. const image = options.image;
  19663. for ( let i = 0; i < mipmaps.length; i ++ ) {
  19664. const mipmap = mipmaps[ i ];
  19665. if ( texture.isCompressedArrayTexture ) {
  19666. if ( texture.format !== gl.RGBA ) {
  19667. if ( glFormat !== null ) {
  19668. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  19669. } else {
  19670. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  19671. }
  19672. } else {
  19673. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  19674. }
  19675. } else {
  19676. if ( glFormat !== null ) {
  19677. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  19678. } else {
  19679. console.warn( 'Unsupported compressed texture format' );
  19680. }
  19681. }
  19682. }
  19683. } else if ( texture.isCubeTexture ) {
  19684. const images = options.images;
  19685. for ( let i = 0; i < 6; i ++ ) {
  19686. const image = getImage( images[ i ] );
  19687. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  19688. }
  19689. } else if ( texture.isDataArrayTexture ) {
  19690. const image = options.image;
  19691. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  19692. } else if ( texture.isData3DTexture ) {
  19693. const image = options.image;
  19694. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  19695. } else if ( texture.isVideoTexture ) {
  19696. texture.update();
  19697. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  19698. } else {
  19699. const image = getImage( options.image );
  19700. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  19701. }
  19702. }
  19703. generateMipmaps( texture ) {
  19704. const { gl, backend } = this;
  19705. const { textureGPU, glTextureType } = backend.get( texture );
  19706. backend.state.bindTexture( glTextureType, textureGPU );
  19707. gl.generateMipmap( glTextureType );
  19708. }
  19709. deallocateRenderBuffers( renderTarget ) {
  19710. const { gl, backend } = this;
  19711. // remove framebuffer reference
  19712. if ( renderTarget ) {
  19713. const renderContextData = backend.get( renderTarget );
  19714. renderContextData.renderBufferStorageSetup = undefined;
  19715. if ( renderContextData.framebuffers ) {
  19716. for ( const cacheKey in renderContextData.framebuffers ) {
  19717. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  19718. }
  19719. delete renderContextData.framebuffers;
  19720. }
  19721. if ( renderContextData.depthRenderbuffer ) {
  19722. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  19723. delete renderContextData.depthRenderbuffer;
  19724. }
  19725. if ( renderContextData.stencilRenderbuffer ) {
  19726. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  19727. delete renderContextData.stencilRenderbuffer;
  19728. }
  19729. if ( renderContextData.msaaFrameBuffer ) {
  19730. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  19731. delete renderContextData.msaaFrameBuffer;
  19732. }
  19733. if ( renderContextData.msaaRenderbuffers ) {
  19734. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  19735. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  19736. }
  19737. delete renderContextData.msaaRenderbuffers;
  19738. }
  19739. }
  19740. }
  19741. destroyTexture( texture ) {
  19742. const { gl, backend } = this;
  19743. const { textureGPU, renderTarget } = backend.get( texture );
  19744. this.deallocateRenderBuffers( renderTarget );
  19745. gl.deleteTexture( textureGPU );
  19746. backend.delete( texture );
  19747. }
  19748. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  19749. const { gl, backend } = this;
  19750. const { state } = this.backend;
  19751. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  19752. let width, height, minX, minY;
  19753. let dstX, dstY;
  19754. if ( srcRegion !== null ) {
  19755. width = srcRegion.max.x - srcRegion.min.x;
  19756. height = srcRegion.max.y - srcRegion.min.y;
  19757. minX = srcRegion.min.x;
  19758. minY = srcRegion.min.y;
  19759. } else {
  19760. width = srcTexture.image.width;
  19761. height = srcTexture.image.height;
  19762. minX = 0;
  19763. minY = 0;
  19764. }
  19765. if ( dstPosition !== null ) {
  19766. dstX = dstPosition.x;
  19767. dstY = dstPosition.y;
  19768. } else {
  19769. dstX = 0;
  19770. dstY = 0;
  19771. }
  19772. state.bindTexture( glTextureType, dstTextureGPU );
  19773. // As another texture upload may have changed pixelStorei
  19774. // parameters, make sure they are correct for the dstTexture
  19775. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  19776. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  19777. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  19778. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  19779. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  19780. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  19781. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  19782. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  19783. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  19784. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  19785. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  19786. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  19787. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  19788. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  19789. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  19790. const srcTextureData = backend.get( srcTexture );
  19791. const dstTextureData = backend.get( dstTexture );
  19792. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  19793. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  19794. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  19795. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  19796. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  19797. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  19798. let mask = gl.COLOR_BUFFER_BIT;
  19799. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  19800. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  19801. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  19802. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  19803. } else {
  19804. if ( srcTexture.isDataTexture ) {
  19805. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  19806. } else {
  19807. if ( srcTexture.isCompressedTexture ) {
  19808. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  19809. } else {
  19810. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  19811. }
  19812. }
  19813. }
  19814. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  19815. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  19816. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  19817. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  19818. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  19819. // Generate mipmaps only when copying level 0
  19820. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  19821. state.unbindTexture();
  19822. }
  19823. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  19824. const { gl } = this;
  19825. const { state } = this.backend;
  19826. const { textureGPU } = this.backend.get( texture );
  19827. const { x, y, z: width, w: height } = rectangle;
  19828. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  19829. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.gerDrawingBufferSize().y;
  19830. if ( requireDrawFrameBuffer ) {
  19831. const partial = ( x !== 0 || y !== 0 );
  19832. let mask;
  19833. let attachment;
  19834. if ( texture.isDepthTexture === true ) {
  19835. mask = gl.DEPTH_BUFFER_BIT;
  19836. attachment = gl.DEPTH_ATTACHMENT;
  19837. if ( renderContext.stencil ) {
  19838. mask |= gl.STENCIL_BUFFER_BIT;
  19839. }
  19840. } else {
  19841. mask = gl.COLOR_BUFFER_BIT;
  19842. attachment = gl.COLOR_ATTACHMENT0;
  19843. }
  19844. if ( partial ) {
  19845. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  19846. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  19847. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  19848. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  19849. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  19850. const flippedY = srcHeight - y - height;
  19851. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  19852. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  19853. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  19854. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  19855. state.unbindTexture();
  19856. } else {
  19857. const fb = gl.createFramebuffer();
  19858. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  19859. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  19860. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  19861. gl.deleteFramebuffer( fb );
  19862. }
  19863. } else {
  19864. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  19865. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  19866. state.unbindTexture();
  19867. }
  19868. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  19869. this.backend._setFramebuffer( renderContext );
  19870. }
  19871. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  19872. setupRenderBufferStorage( renderbuffer, renderContext ) {
  19873. const { gl } = this;
  19874. const renderTarget = renderContext.renderTarget;
  19875. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  19876. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  19877. if ( depthBuffer && ! stencilBuffer ) {
  19878. let glInternalFormat = gl.DEPTH_COMPONENT24;
  19879. if ( samples > 0 ) {
  19880. if ( depthTexture && depthTexture.isDepthTexture ) {
  19881. if ( depthTexture.type === gl.FLOAT ) {
  19882. glInternalFormat = gl.DEPTH_COMPONENT32F;
  19883. }
  19884. }
  19885. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  19886. } else {
  19887. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  19888. }
  19889. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  19890. } else if ( depthBuffer && stencilBuffer ) {
  19891. if ( samples > 0 ) {
  19892. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  19893. } else {
  19894. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  19895. }
  19896. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  19897. }
  19898. }
  19899. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  19900. const { backend, gl } = this;
  19901. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  19902. const fb = gl.createFramebuffer();
  19903. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  19904. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  19905. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  19906. const typedArrayType = this._getTypedArrayType( glType );
  19907. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  19908. const elementCount = width * height;
  19909. const byteLength = elementCount * bytesPerTexel;
  19910. const buffer = gl.createBuffer();
  19911. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  19912. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  19913. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  19914. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  19915. await backend.utils._clientWaitAsync();
  19916. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  19917. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  19918. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  19919. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  19920. gl.deleteFramebuffer( fb );
  19921. return dstBuffer;
  19922. }
  19923. _getTypedArrayType( glType ) {
  19924. const { gl } = this;
  19925. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  19926. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  19927. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  19928. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  19929. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  19930. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  19931. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  19932. if ( glType === gl.FLOAT ) return Float32Array;
  19933. throw new Error( `Unsupported WebGL type: ${glType}` );
  19934. }
  19935. _getBytesPerTexel( glType, glFormat ) {
  19936. const { gl } = this;
  19937. let bytesPerComponent = 0;
  19938. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  19939. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  19940. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  19941. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  19942. glType === gl.UNSIGNED_SHORT ||
  19943. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  19944. if ( glType === gl.UNSIGNED_INT ||
  19945. glType === gl.FLOAT ) bytesPerComponent = 4;
  19946. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  19947. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  19948. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  19949. }
  19950. }
  19951. class WebGLExtensions {
  19952. constructor( backend ) {
  19953. this.backend = backend;
  19954. this.gl = this.backend.gl;
  19955. this.availableExtensions = this.gl.getSupportedExtensions();
  19956. this.extensions = {};
  19957. }
  19958. get( name ) {
  19959. let extension = this.extensions[ name ];
  19960. if ( extension === undefined ) {
  19961. extension = this.gl.getExtension( name );
  19962. this.extensions[ name ] = extension;
  19963. }
  19964. return extension;
  19965. }
  19966. has( name ) {
  19967. return this.availableExtensions.includes( name );
  19968. }
  19969. }
  19970. class WebGLCapabilities {
  19971. constructor( backend ) {
  19972. this.backend = backend;
  19973. this.maxAnisotropy = null;
  19974. }
  19975. getMaxAnisotropy() {
  19976. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  19977. const gl = this.backend.gl;
  19978. const extensions = this.backend.extensions;
  19979. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  19980. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  19981. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  19982. } else {
  19983. this.maxAnisotropy = 0;
  19984. }
  19985. return this.maxAnisotropy;
  19986. }
  19987. }
  19988. const GLFeatureName = {
  19989. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  19990. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  19991. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  19992. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  19993. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  19994. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  19995. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  19996. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  19997. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  19998. };
  19999. class WebGLBufferRenderer {
  20000. constructor( backend ) {
  20001. this.gl = backend.gl;
  20002. this.extensions = backend.extensions;
  20003. this.info = backend.renderer.info;
  20004. this.mode = null;
  20005. this.index = 0;
  20006. this.type = null;
  20007. this.object = null;
  20008. }
  20009. render( start, count ) {
  20010. const { gl, mode, object, type, info, index } = this;
  20011. if ( index !== 0 ) {
  20012. gl.drawElements( mode, count, type, start );
  20013. } else {
  20014. gl.drawArrays( mode, start, count );
  20015. }
  20016. info.update( object, count, mode, 1 );
  20017. }
  20018. renderInstances( start, count, primcount ) {
  20019. const { gl, mode, type, index, object, info } = this;
  20020. if ( primcount === 0 ) return;
  20021. if ( index !== 0 ) {
  20022. gl.drawElementsInstanced( mode, count, type, start, primcount );
  20023. } else {
  20024. gl.drawArraysInstanced( mode, start, count, primcount );
  20025. }
  20026. info.update( object, count, mode, primcount );
  20027. }
  20028. renderMultiDraw( starts, counts, drawCount ) {
  20029. const { extensions, mode, object, info } = this;
  20030. if ( drawCount === 0 ) return;
  20031. const extension = extensions.get( 'WEBGL_multi_draw' );
  20032. if ( extension === null ) {
  20033. for ( let i = 0; i < drawCount; i ++ ) {
  20034. this.render( starts[ i ], counts[ i ] );
  20035. }
  20036. } else {
  20037. if ( this.index !== 0 ) {
  20038. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  20039. } else {
  20040. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  20041. }
  20042. let elementCount = 0;
  20043. for ( let i = 0; i < drawCount; i ++ ) {
  20044. elementCount += counts[ i ];
  20045. }
  20046. info.update( object, elementCount, mode, 1 );
  20047. }
  20048. }
  20049. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  20050. const { extensions, mode, object, info } = this;
  20051. if ( drawCount === 0 ) return;
  20052. const extension = extensions.get( 'WEBGL_multi_draw' );
  20053. if ( extension === null ) {
  20054. for ( let i = 0; i < drawCount; i ++ ) {
  20055. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  20056. }
  20057. } else {
  20058. if ( this.index !== 0 ) {
  20059. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  20060. } else {
  20061. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  20062. }
  20063. let elementCount = 0;
  20064. for ( let i = 0; i < drawCount; i ++ ) {
  20065. elementCount += counts[ i ] * primcount[ i ];
  20066. }
  20067. info.update( object, elementCount, mode, 1 );
  20068. }
  20069. }
  20070. //
  20071. }
  20072. //
  20073. class WebGLBackend extends Backend {
  20074. constructor( parameters = {} ) {
  20075. super( parameters );
  20076. this.isWebGLBackend = true;
  20077. }
  20078. init( renderer ) {
  20079. super.init( renderer );
  20080. //
  20081. const parameters = this.parameters;
  20082. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  20083. function onContextLost( event ) {
  20084. event.preventDefault();
  20085. const contextLossInfo = {
  20086. api: 'WebGL',
  20087. message: event.statusMessage || 'Unknown reason',
  20088. reason: null,
  20089. originalEvent: event
  20090. };
  20091. renderer.onDeviceLost( contextLossInfo );
  20092. }
  20093. this._onContextLost = onContextLost;
  20094. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  20095. this.gl = glContext;
  20096. this.extensions = new WebGLExtensions( this );
  20097. this.capabilities = new WebGLCapabilities( this );
  20098. this.attributeUtils = new WebGLAttributeUtils( this );
  20099. this.textureUtils = new WebGLTextureUtils( this );
  20100. this.bufferRenderer = new WebGLBufferRenderer( this );
  20101. this.state = new WebGLState( this );
  20102. this.utils = new WebGLUtils( this );
  20103. this.vaoCache = {};
  20104. this.transformFeedbackCache = {};
  20105. this.discard = false;
  20106. this.trackTimestamp = ( parameters.trackTimestamp === true );
  20107. this.extensions.get( 'EXT_color_buffer_float' );
  20108. this.extensions.get( 'WEBGL_clip_cull_distance' );
  20109. this.extensions.get( 'OES_texture_float_linear' );
  20110. this.extensions.get( 'EXT_color_buffer_half_float' );
  20111. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  20112. this.extensions.get( 'WEBGL_render_shared_exponent' );
  20113. this.extensions.get( 'WEBGL_multi_draw' );
  20114. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  20115. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  20116. this._knownBindings = new WeakSet();
  20117. this._currentContext = null;
  20118. }
  20119. get coordinateSystem() {
  20120. return WebGLCoordinateSystem;
  20121. }
  20122. async getArrayBufferAsync( attribute ) {
  20123. return await this.attributeUtils.getArrayBufferAsync( attribute );
  20124. }
  20125. async waitForGPU() {
  20126. await this.utils._clientWaitAsync();
  20127. }
  20128. initTimestampQuery( renderContext ) {
  20129. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  20130. const renderContextData = this.get( renderContext );
  20131. if ( this.queryRunning ) {
  20132. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  20133. renderContextData.queryQueue.push( renderContext );
  20134. return;
  20135. }
  20136. if ( renderContextData.activeQuery ) {
  20137. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  20138. renderContextData.activeQuery = null;
  20139. }
  20140. renderContextData.activeQuery = this.gl.createQuery();
  20141. if ( renderContextData.activeQuery !== null ) {
  20142. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  20143. this.queryRunning = true;
  20144. }
  20145. }
  20146. // timestamp utils
  20147. prepareTimestampBuffer( renderContext ) {
  20148. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  20149. const renderContextData = this.get( renderContext );
  20150. if ( renderContextData.activeQuery ) {
  20151. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  20152. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  20153. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  20154. renderContextData.activeQuery = null;
  20155. this.queryRunning = false;
  20156. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  20157. const nextRenderContext = renderContextData.queryQueue.shift();
  20158. this.initTimestampQuery( nextRenderContext );
  20159. }
  20160. }
  20161. }
  20162. async resolveTimestampAsync( renderContext, type = 'render' ) {
  20163. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  20164. const renderContextData = this.get( renderContext );
  20165. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  20166. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  20167. const queryInfo = renderContextData.gpuQueries[ i ];
  20168. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  20169. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  20170. if ( available && ! disjoint ) {
  20171. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  20172. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  20173. this.gl.deleteQuery( queryInfo.query );
  20174. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  20175. i --;
  20176. this.renderer.info.updateTimestamp( type, duration );
  20177. }
  20178. }
  20179. }
  20180. getContext() {
  20181. return this.gl;
  20182. }
  20183. beginRender( renderContext ) {
  20184. const { gl } = this;
  20185. const renderContextData = this.get( renderContext );
  20186. //
  20187. //
  20188. this.initTimestampQuery( renderContext );
  20189. renderContextData.previousContext = this._currentContext;
  20190. this._currentContext = renderContext;
  20191. this._setFramebuffer( renderContext );
  20192. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  20193. //
  20194. if ( renderContext.viewport ) {
  20195. this.updateViewport( renderContext );
  20196. } else {
  20197. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  20198. }
  20199. if ( renderContext.scissor ) {
  20200. const { x, y, width, height } = renderContext.scissorValue;
  20201. gl.scissor( x, renderContext.height - height - y, width, height );
  20202. }
  20203. const occlusionQueryCount = renderContext.occlusionQueryCount;
  20204. if ( occlusionQueryCount > 0 ) {
  20205. // Get a reference to the array of objects with queries. The renderContextData property
  20206. // can be changed by another render pass before the async reading of all previous queries complete
  20207. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  20208. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  20209. renderContextData.lastOcclusionObject = null;
  20210. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  20211. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  20212. renderContextData.occlusionQueryIndex = 0;
  20213. }
  20214. }
  20215. finishRender( renderContext ) {
  20216. const { gl, state } = this;
  20217. const renderContextData = this.get( renderContext );
  20218. const previousContext = renderContextData.previousContext;
  20219. const occlusionQueryCount = renderContext.occlusionQueryCount;
  20220. if ( occlusionQueryCount > 0 ) {
  20221. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  20222. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  20223. }
  20224. this.resolveOccludedAsync( renderContext );
  20225. }
  20226. const textures = renderContext.textures;
  20227. if ( textures !== null ) {
  20228. for ( let i = 0; i < textures.length; i ++ ) {
  20229. const texture = textures[ i ];
  20230. if ( texture.generateMipmaps ) {
  20231. this.generateMipmaps( texture );
  20232. }
  20233. }
  20234. }
  20235. this._currentContext = previousContext;
  20236. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  20237. const renderTargetContextData = this.get( renderContext.renderTarget );
  20238. const { samples } = renderContext.renderTarget;
  20239. if ( samples > 0 ) {
  20240. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  20241. const mask = gl.COLOR_BUFFER_BIT;
  20242. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  20243. const textures = renderContext.textures;
  20244. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  20245. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  20246. for ( let i = 0; i < textures.length; i ++ ) {
  20247. // TODO Add support for MRT
  20248. if ( renderContext.scissor ) {
  20249. const { x, y, width, height } = renderContext.scissorValue;
  20250. const viewY = renderContext.height - height - y;
  20251. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  20252. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  20253. } else {
  20254. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  20255. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  20256. }
  20257. }
  20258. }
  20259. }
  20260. if ( previousContext !== null ) {
  20261. this._setFramebuffer( previousContext );
  20262. if ( previousContext.viewport ) {
  20263. this.updateViewport( previousContext );
  20264. } else {
  20265. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  20266. }
  20267. }
  20268. this.prepareTimestampBuffer( renderContext );
  20269. }
  20270. resolveOccludedAsync( renderContext ) {
  20271. const renderContextData = this.get( renderContext );
  20272. // handle occlusion query results
  20273. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  20274. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  20275. const occluded = new WeakSet();
  20276. const { gl } = this;
  20277. renderContextData.currentOcclusionQueryObjects = null;
  20278. renderContextData.currentOcclusionQueries = null;
  20279. const check = () => {
  20280. let completed = 0;
  20281. // check all queries and requeue as appropriate
  20282. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  20283. const query = currentOcclusionQueries[ i ];
  20284. if ( query === null ) continue;
  20285. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  20286. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  20287. currentOcclusionQueries[ i ] = null;
  20288. gl.deleteQuery( query );
  20289. completed ++;
  20290. }
  20291. }
  20292. if ( completed < currentOcclusionQueries.length ) {
  20293. requestAnimationFrame( check );
  20294. } else {
  20295. renderContextData.occluded = occluded;
  20296. }
  20297. };
  20298. check();
  20299. }
  20300. }
  20301. isOccluded( renderContext, object ) {
  20302. const renderContextData = this.get( renderContext );
  20303. return renderContextData.occluded && renderContextData.occluded.has( object );
  20304. }
  20305. updateViewport( renderContext ) {
  20306. const gl = this.gl;
  20307. const { x, y, width, height } = renderContext.viewportValue;
  20308. gl.viewport( x, renderContext.height - height - y, width, height );
  20309. }
  20310. setScissorTest( boolean ) {
  20311. const gl = this.gl;
  20312. if ( boolean ) {
  20313. gl.enable( gl.SCISSOR_TEST );
  20314. } else {
  20315. gl.disable( gl.SCISSOR_TEST );
  20316. }
  20317. }
  20318. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  20319. const { gl } = this;
  20320. if ( descriptor === null ) {
  20321. const clearColor = this.getClearColor();
  20322. // premultiply alpha
  20323. clearColor.r *= clearColor.a;
  20324. clearColor.g *= clearColor.a;
  20325. clearColor.b *= clearColor.a;
  20326. descriptor = {
  20327. textures: null,
  20328. clearColorValue: clearColor
  20329. };
  20330. }
  20331. //
  20332. let clear = 0;
  20333. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  20334. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  20335. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  20336. if ( clear !== 0 ) {
  20337. let clearColor;
  20338. if ( descriptor.clearColorValue ) {
  20339. clearColor = descriptor.clearColorValue;
  20340. } else {
  20341. clearColor = this.getClearColor();
  20342. // premultiply alpha
  20343. clearColor.r *= clearColor.a;
  20344. clearColor.g *= clearColor.a;
  20345. clearColor.b *= clearColor.a;
  20346. }
  20347. if ( depth ) this.state.setDepthMask( true );
  20348. if ( descriptor.textures === null ) {
  20349. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  20350. gl.clear( clear );
  20351. } else {
  20352. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  20353. if ( color ) {
  20354. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  20355. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  20356. }
  20357. }
  20358. if ( depth && stencil ) {
  20359. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  20360. } else if ( depth ) {
  20361. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  20362. } else if ( stencil ) {
  20363. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  20364. }
  20365. }
  20366. }
  20367. }
  20368. beginCompute( computeGroup ) {
  20369. const { state, gl } = this;
  20370. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  20371. this.initTimestampQuery( computeGroup );
  20372. }
  20373. compute( computeGroup, computeNode, bindings, pipeline ) {
  20374. const { state, gl } = this;
  20375. if ( ! this.discard ) {
  20376. // required here to handle async behaviour of render.compute()
  20377. gl.enable( gl.RASTERIZER_DISCARD );
  20378. this.discard = true;
  20379. }
  20380. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  20381. const vaoKey = this._getVaoKey( null, attributes );
  20382. const vaoGPU = this.vaoCache[ vaoKey ];
  20383. if ( vaoGPU === undefined ) {
  20384. this._createVao( null, attributes );
  20385. } else {
  20386. gl.bindVertexArray( vaoGPU );
  20387. }
  20388. state.useProgram( programGPU );
  20389. this._bindUniforms( bindings );
  20390. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  20391. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  20392. gl.beginTransformFeedback( gl.POINTS );
  20393. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  20394. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  20395. } else {
  20396. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  20397. }
  20398. gl.endTransformFeedback();
  20399. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  20400. // switch active buffers
  20401. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  20402. const dualAttributeData = transformBuffers[ i ];
  20403. if ( dualAttributeData.pbo ) {
  20404. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  20405. }
  20406. dualAttributeData.switchBuffers();
  20407. }
  20408. }
  20409. finishCompute( computeGroup ) {
  20410. const gl = this.gl;
  20411. this.discard = false;
  20412. gl.disable( gl.RASTERIZER_DISCARD );
  20413. this.prepareTimestampBuffer( computeGroup );
  20414. if ( this._currentContext ) {
  20415. this._setFramebuffer( this._currentContext );
  20416. }
  20417. }
  20418. draw( renderObject/*, info*/ ) {
  20419. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  20420. const { programGPU } = this.get( pipeline );
  20421. const { gl, state } = this;
  20422. const contextData = this.get( context );
  20423. const drawParams = renderObject.getDrawParameters();
  20424. if ( drawParams === null ) return;
  20425. //
  20426. this._bindUniforms( renderObject.getBindings() );
  20427. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  20428. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  20429. state.useProgram( programGPU );
  20430. //
  20431. const renderObjectData = this.get( renderObject );
  20432. let vaoGPU = renderObjectData.staticVao;
  20433. if ( vaoGPU === undefined || renderObjectData.geometryId !== renderObject.geometry.id ) {
  20434. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  20435. vaoGPU = this.vaoCache[ vaoKey ];
  20436. if ( vaoGPU === undefined ) {
  20437. let staticVao;
  20438. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  20439. if ( staticVao ) {
  20440. renderObjectData.staticVao = vaoGPU;
  20441. renderObjectData.geometryId = renderObject.geometry.id;
  20442. }
  20443. }
  20444. }
  20445. gl.bindVertexArray( vaoGPU );
  20446. //
  20447. const index = renderObject.getIndex();
  20448. //
  20449. const lastObject = contextData.lastOcclusionObject;
  20450. if ( lastObject !== object && lastObject !== undefined ) {
  20451. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  20452. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  20453. contextData.occlusionQueryIndex ++;
  20454. }
  20455. if ( object.occlusionTest === true ) {
  20456. const query = gl.createQuery();
  20457. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  20458. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  20459. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  20460. }
  20461. contextData.lastOcclusionObject = object;
  20462. }
  20463. //
  20464. const renderer = this.bufferRenderer;
  20465. if ( object.isPoints ) renderer.mode = gl.POINTS;
  20466. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  20467. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  20468. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  20469. else {
  20470. if ( material.wireframe === true ) {
  20471. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  20472. renderer.mode = gl.LINES;
  20473. } else {
  20474. renderer.mode = gl.TRIANGLES;
  20475. }
  20476. }
  20477. //
  20478. const { vertexCount, instanceCount } = drawParams;
  20479. let { firstVertex } = drawParams;
  20480. renderer.object = object;
  20481. if ( index !== null ) {
  20482. firstVertex *= index.array.BYTES_PER_ELEMENT;
  20483. const indexData = this.get( index );
  20484. renderer.index = index.count;
  20485. renderer.type = indexData.type;
  20486. } else {
  20487. renderer.index = 0;
  20488. }
  20489. if ( object.isBatchedMesh ) {
  20490. if ( object._multiDrawInstances !== null ) {
  20491. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  20492. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  20493. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  20494. } else {
  20495. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  20496. }
  20497. } else if ( instanceCount > 1 ) {
  20498. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  20499. } else {
  20500. renderer.render( firstVertex, vertexCount );
  20501. }
  20502. //
  20503. gl.bindVertexArray( null );
  20504. }
  20505. needsRenderUpdate( /*renderObject*/ ) {
  20506. return false;
  20507. }
  20508. getRenderCacheKey( /*renderObject*/ ) {
  20509. return '';
  20510. }
  20511. // textures
  20512. createDefaultTexture( texture ) {
  20513. this.textureUtils.createDefaultTexture( texture );
  20514. }
  20515. createTexture( texture, options ) {
  20516. this.textureUtils.createTexture( texture, options );
  20517. }
  20518. updateTexture( texture, options ) {
  20519. this.textureUtils.updateTexture( texture, options );
  20520. }
  20521. generateMipmaps( texture ) {
  20522. this.textureUtils.generateMipmaps( texture );
  20523. }
  20524. destroyTexture( texture ) {
  20525. this.textureUtils.destroyTexture( texture );
  20526. }
  20527. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  20528. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  20529. }
  20530. createSampler( /*texture*/ ) {
  20531. //console.warn( 'Abstract class.' );
  20532. }
  20533. destroySampler() {}
  20534. // node builder
  20535. createNodeBuilder( object, renderer ) {
  20536. return new GLSLNodeBuilder( object, renderer );
  20537. }
  20538. // program
  20539. createProgram( program ) {
  20540. const gl = this.gl;
  20541. const { stage, code } = program;
  20542. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  20543. gl.shaderSource( shader, code );
  20544. gl.compileShader( shader );
  20545. this.set( program, {
  20546. shaderGPU: shader
  20547. } );
  20548. }
  20549. destroyProgram( /*program*/ ) {
  20550. console.warn( 'Abstract class.' );
  20551. }
  20552. createRenderPipeline( renderObject, promises ) {
  20553. const gl = this.gl;
  20554. const pipeline = renderObject.pipeline;
  20555. // Program
  20556. const { fragmentProgram, vertexProgram } = pipeline;
  20557. const programGPU = gl.createProgram();
  20558. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  20559. const vertexShader = this.get( vertexProgram ).shaderGPU;
  20560. gl.attachShader( programGPU, fragmentShader );
  20561. gl.attachShader( programGPU, vertexShader );
  20562. gl.linkProgram( programGPU );
  20563. this.set( pipeline, {
  20564. programGPU,
  20565. fragmentShader,
  20566. vertexShader
  20567. } );
  20568. if ( promises !== null && this.parallel ) {
  20569. const p = new Promise( ( resolve /*, reject*/ ) => {
  20570. const parallel = this.parallel;
  20571. const checkStatus = () => {
  20572. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  20573. this._completeCompile( renderObject, pipeline );
  20574. resolve();
  20575. } else {
  20576. requestAnimationFrame( checkStatus );
  20577. }
  20578. };
  20579. checkStatus();
  20580. } );
  20581. promises.push( p );
  20582. return;
  20583. }
  20584. this._completeCompile( renderObject, pipeline );
  20585. }
  20586. _handleSource( string, errorLine ) {
  20587. const lines = string.split( '\n' );
  20588. const lines2 = [];
  20589. const from = Math.max( errorLine - 6, 0 );
  20590. const to = Math.min( errorLine + 6, lines.length );
  20591. for ( let i = from; i < to; i ++ ) {
  20592. const line = i + 1;
  20593. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  20594. }
  20595. return lines2.join( '\n' );
  20596. }
  20597. _getShaderErrors( gl, shader, type ) {
  20598. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  20599. const errors = gl.getShaderInfoLog( shader ).trim();
  20600. if ( status && errors === '' ) return '';
  20601. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  20602. if ( errorMatches ) {
  20603. const errorLine = parseInt( errorMatches[ 1 ] );
  20604. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  20605. } else {
  20606. return errors;
  20607. }
  20608. }
  20609. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  20610. if ( this.renderer.debug.checkShaderErrors ) {
  20611. const gl = this.gl;
  20612. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  20613. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  20614. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  20615. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  20616. } else {
  20617. // default error reporting
  20618. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  20619. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  20620. console.error(
  20621. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  20622. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  20623. 'Program Info Log: ' + programLog + '\n' +
  20624. vertexErrors + '\n' +
  20625. fragmentErrors
  20626. );
  20627. }
  20628. } else if ( programLog !== '' ) {
  20629. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  20630. }
  20631. }
  20632. }
  20633. _completeCompile( renderObject, pipeline ) {
  20634. const { state, gl } = this;
  20635. const pipelineData = this.get( pipeline );
  20636. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  20637. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  20638. this._logProgramError( programGPU, fragmentShader, vertexShader );
  20639. }
  20640. state.useProgram( programGPU );
  20641. // Bindings
  20642. const bindings = renderObject.getBindings();
  20643. this._setupBindings( bindings, programGPU );
  20644. //
  20645. this.set( pipeline, {
  20646. programGPU
  20647. } );
  20648. }
  20649. createComputePipeline( computePipeline, bindings ) {
  20650. const { state, gl } = this;
  20651. // Program
  20652. const fragmentProgram = {
  20653. stage: 'fragment',
  20654. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  20655. };
  20656. this.createProgram( fragmentProgram );
  20657. const { computeProgram } = computePipeline;
  20658. const programGPU = gl.createProgram();
  20659. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  20660. const vertexShader = this.get( computeProgram ).shaderGPU;
  20661. const transforms = computeProgram.transforms;
  20662. const transformVaryingNames = [];
  20663. const transformAttributeNodes = [];
  20664. for ( let i = 0; i < transforms.length; i ++ ) {
  20665. const transform = transforms[ i ];
  20666. transformVaryingNames.push( transform.varyingName );
  20667. transformAttributeNodes.push( transform.attributeNode );
  20668. }
  20669. gl.attachShader( programGPU, fragmentShader );
  20670. gl.attachShader( programGPU, vertexShader );
  20671. gl.transformFeedbackVaryings(
  20672. programGPU,
  20673. transformVaryingNames,
  20674. gl.SEPARATE_ATTRIBS
  20675. );
  20676. gl.linkProgram( programGPU );
  20677. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  20678. this._logProgramError( programGPU, fragmentShader, vertexShader );
  20679. }
  20680. state.useProgram( programGPU );
  20681. // Bindings
  20682. this._setupBindings( bindings, programGPU );
  20683. const attributeNodes = computeProgram.attributes;
  20684. const attributes = [];
  20685. const transformBuffers = [];
  20686. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  20687. const attribute = attributeNodes[ i ].node.attribute;
  20688. attributes.push( attribute );
  20689. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  20690. }
  20691. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  20692. const attribute = transformAttributeNodes[ i ].attribute;
  20693. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  20694. const attributeData = this.get( attribute );
  20695. transformBuffers.push( attributeData );
  20696. }
  20697. //
  20698. this.set( computePipeline, {
  20699. programGPU,
  20700. transformBuffers,
  20701. attributes
  20702. } );
  20703. }
  20704. createBindings( bindGroup, bindings ) {
  20705. if ( this._knownBindings.has( bindings ) === false ) {
  20706. this._knownBindings.add( bindings );
  20707. let uniformBuffers = 0;
  20708. let textures = 0;
  20709. for ( const bindGroup of bindings ) {
  20710. this.set( bindGroup, {
  20711. textures: textures,
  20712. uniformBuffers: uniformBuffers
  20713. } );
  20714. for ( const binding of bindGroup.bindings ) {
  20715. if ( binding.isUniformBuffer ) uniformBuffers ++;
  20716. if ( binding.isSampledTexture ) textures ++;
  20717. }
  20718. }
  20719. }
  20720. this.updateBindings( bindGroup, bindings );
  20721. }
  20722. updateBindings( bindGroup /*, bindings*/ ) {
  20723. const { gl } = this;
  20724. const bindGroupData = this.get( bindGroup );
  20725. let i = bindGroupData.uniformBuffers;
  20726. let t = bindGroupData.textures;
  20727. for ( const binding of bindGroup.bindings ) {
  20728. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  20729. const data = binding.buffer;
  20730. const bufferGPU = gl.createBuffer();
  20731. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  20732. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  20733. this.set( binding, {
  20734. index: i ++,
  20735. bufferGPU
  20736. } );
  20737. } else if ( binding.isSampledTexture ) {
  20738. const { textureGPU, glTextureType } = this.get( binding.texture );
  20739. this.set( binding, {
  20740. index: t ++,
  20741. textureGPU,
  20742. glTextureType
  20743. } );
  20744. }
  20745. }
  20746. }
  20747. updateBinding( binding ) {
  20748. const gl = this.gl;
  20749. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  20750. const bindingData = this.get( binding );
  20751. const bufferGPU = bindingData.bufferGPU;
  20752. const data = binding.buffer;
  20753. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  20754. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  20755. }
  20756. }
  20757. // attributes
  20758. createIndexAttribute( attribute ) {
  20759. const gl = this.gl;
  20760. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  20761. }
  20762. createAttribute( attribute ) {
  20763. if ( this.has( attribute ) ) return;
  20764. const gl = this.gl;
  20765. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  20766. }
  20767. createStorageAttribute( attribute ) {
  20768. if ( this.has( attribute ) ) return;
  20769. const gl = this.gl;
  20770. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  20771. }
  20772. updateAttribute( attribute ) {
  20773. this.attributeUtils.updateAttribute( attribute );
  20774. }
  20775. destroyAttribute( attribute ) {
  20776. this.attributeUtils.destroyAttribute( attribute );
  20777. }
  20778. updateSize() {
  20779. //console.warn( 'Abstract class.' );
  20780. }
  20781. hasFeature( name ) {
  20782. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  20783. const extensions = this.extensions;
  20784. for ( let i = 0; i < keysMatching.length; i ++ ) {
  20785. if ( extensions.has( keysMatching[ i ] ) ) return true;
  20786. }
  20787. return false;
  20788. }
  20789. getMaxAnisotropy() {
  20790. return this.capabilities.getMaxAnisotropy();
  20791. }
  20792. copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level ) {
  20793. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  20794. }
  20795. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  20796. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  20797. }
  20798. _setFramebuffer( descriptor ) {
  20799. const { gl, state } = this;
  20800. let currentFrameBuffer = null;
  20801. if ( descriptor.textures !== null ) {
  20802. const renderTarget = descriptor.renderTarget;
  20803. const renderTargetContextData = this.get( renderTarget );
  20804. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  20805. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  20806. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  20807. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  20808. const cacheKey = getCacheKey( descriptor );
  20809. let fb;
  20810. if ( isCube ) {
  20811. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  20812. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  20813. } else {
  20814. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  20815. fb = renderTargetContextData.framebuffers[ cacheKey ];
  20816. }
  20817. if ( fb === undefined ) {
  20818. fb = gl.createFramebuffer();
  20819. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  20820. const textures = descriptor.textures;
  20821. if ( isCube ) {
  20822. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  20823. const { textureGPU } = this.get( textures[ 0 ] );
  20824. const cubeFace = this.renderer._activeCubeFace;
  20825. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  20826. } else {
  20827. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  20828. for ( let i = 0; i < textures.length; i ++ ) {
  20829. const texture = textures[ i ];
  20830. const textureData = this.get( texture );
  20831. textureData.renderTarget = descriptor.renderTarget;
  20832. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  20833. const attachment = gl.COLOR_ATTACHMENT0 + i;
  20834. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  20835. }
  20836. state.drawBuffers( descriptor, fb );
  20837. }
  20838. if ( descriptor.depthTexture !== null ) {
  20839. const textureData = this.get( descriptor.depthTexture );
  20840. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  20841. textureData.renderTarget = descriptor.renderTarget;
  20842. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  20843. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  20844. }
  20845. }
  20846. if ( samples > 0 ) {
  20847. if ( msaaFb === undefined ) {
  20848. const invalidationArray = [];
  20849. msaaFb = gl.createFramebuffer();
  20850. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  20851. const msaaRenderbuffers = [];
  20852. const textures = descriptor.textures;
  20853. for ( let i = 0; i < textures.length; i ++ ) {
  20854. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  20855. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  20856. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  20857. if ( depthBuffer ) {
  20858. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  20859. invalidationArray.push( depthStyle );
  20860. }
  20861. const texture = descriptor.textures[ i ];
  20862. const textureData = this.get( texture );
  20863. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  20864. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  20865. }
  20866. renderTargetContextData.msaaFrameBuffer = msaaFb;
  20867. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  20868. if ( depthRenderbuffer === undefined ) {
  20869. depthRenderbuffer = gl.createRenderbuffer();
  20870. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor );
  20871. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  20872. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  20873. invalidationArray.push( depthStyle );
  20874. }
  20875. renderTargetContextData.invalidationArray = invalidationArray;
  20876. }
  20877. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  20878. } else {
  20879. currentFrameBuffer = fb;
  20880. }
  20881. }
  20882. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  20883. }
  20884. _getVaoKey( index, attributes ) {
  20885. let key = [];
  20886. if ( index !== null ) {
  20887. const indexData = this.get( index );
  20888. key += ':' + indexData.id;
  20889. }
  20890. for ( let i = 0; i < attributes.length; i ++ ) {
  20891. const attributeData = this.get( attributes[ i ] );
  20892. key += ':' + attributeData.id;
  20893. }
  20894. return key;
  20895. }
  20896. _createVao( index, attributes ) {
  20897. const { gl } = this;
  20898. const vaoGPU = gl.createVertexArray();
  20899. let key = '';
  20900. let staticVao = true;
  20901. gl.bindVertexArray( vaoGPU );
  20902. if ( index !== null ) {
  20903. const indexData = this.get( index );
  20904. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  20905. key += ':' + indexData.id;
  20906. }
  20907. for ( let i = 0; i < attributes.length; i ++ ) {
  20908. const attribute = attributes[ i ];
  20909. const attributeData = this.get( attribute );
  20910. key += ':' + attributeData.id;
  20911. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  20912. gl.enableVertexAttribArray( i );
  20913. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  20914. let stride, offset;
  20915. if ( attribute.isInterleavedBufferAttribute === true ) {
  20916. stride = attribute.data.stride * attributeData.bytesPerElement;
  20917. offset = attribute.offset * attributeData.bytesPerElement;
  20918. } else {
  20919. stride = 0;
  20920. offset = 0;
  20921. }
  20922. if ( attributeData.isInteger ) {
  20923. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  20924. } else {
  20925. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  20926. }
  20927. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  20928. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  20929. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  20930. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  20931. }
  20932. }
  20933. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  20934. this.vaoCache[ key ] = vaoGPU;
  20935. return { vaoGPU, staticVao };
  20936. }
  20937. _getTransformFeedback( transformBuffers ) {
  20938. let key = '';
  20939. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  20940. key += ':' + transformBuffers[ i ].id;
  20941. }
  20942. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  20943. if ( transformFeedbackGPU !== undefined ) {
  20944. return transformFeedbackGPU;
  20945. }
  20946. const { gl } = this;
  20947. transformFeedbackGPU = gl.createTransformFeedback();
  20948. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  20949. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  20950. const attributeData = transformBuffers[ i ];
  20951. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  20952. }
  20953. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  20954. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  20955. return transformFeedbackGPU;
  20956. }
  20957. _setupBindings( bindings, programGPU ) {
  20958. const gl = this.gl;
  20959. for ( const bindGroup of bindings ) {
  20960. for ( const binding of bindGroup.bindings ) {
  20961. const bindingData = this.get( binding );
  20962. const index = bindingData.index;
  20963. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  20964. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  20965. gl.uniformBlockBinding( programGPU, location, index );
  20966. } else if ( binding.isSampledTexture ) {
  20967. const location = gl.getUniformLocation( programGPU, binding.name );
  20968. gl.uniform1i( location, index );
  20969. }
  20970. }
  20971. }
  20972. }
  20973. _bindUniforms( bindings ) {
  20974. const { gl, state } = this;
  20975. for ( const bindGroup of bindings ) {
  20976. for ( const binding of bindGroup.bindings ) {
  20977. const bindingData = this.get( binding );
  20978. const index = bindingData.index;
  20979. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  20980. // TODO USE bindBufferRange to group multiple uniform buffers
  20981. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  20982. } else if ( binding.isSampledTexture ) {
  20983. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  20984. }
  20985. }
  20986. }
  20987. }
  20988. dispose() {
  20989. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  20990. }
  20991. }
  20992. const GPUPrimitiveTopology = {
  20993. PointList: 'point-list',
  20994. LineList: 'line-list',
  20995. LineStrip: 'line-strip',
  20996. TriangleList: 'triangle-list',
  20997. TriangleStrip: 'triangle-strip',
  20998. };
  20999. const GPUCompareFunction = {
  21000. Never: 'never',
  21001. Less: 'less',
  21002. Equal: 'equal',
  21003. LessEqual: 'less-equal',
  21004. Greater: 'greater',
  21005. NotEqual: 'not-equal',
  21006. GreaterEqual: 'greater-equal',
  21007. Always: 'always'
  21008. };
  21009. const GPUStoreOp = {
  21010. Store: 'store',
  21011. Discard: 'discard'
  21012. };
  21013. const GPULoadOp = {
  21014. Load: 'load',
  21015. Clear: 'clear'
  21016. };
  21017. const GPUFrontFace = {
  21018. CCW: 'ccw',
  21019. CW: 'cw'
  21020. };
  21021. const GPUCullMode = {
  21022. None: 'none',
  21023. Front: 'front',
  21024. Back: 'back'
  21025. };
  21026. const GPUIndexFormat = {
  21027. Uint16: 'uint16',
  21028. Uint32: 'uint32'
  21029. };
  21030. const GPUTextureFormat = {
  21031. // 8-bit formats
  21032. R8Unorm: 'r8unorm',
  21033. R8Snorm: 'r8snorm',
  21034. R8Uint: 'r8uint',
  21035. R8Sint: 'r8sint',
  21036. // 16-bit formats
  21037. R16Uint: 'r16uint',
  21038. R16Sint: 'r16sint',
  21039. R16Float: 'r16float',
  21040. RG8Unorm: 'rg8unorm',
  21041. RG8Snorm: 'rg8snorm',
  21042. RG8Uint: 'rg8uint',
  21043. RG8Sint: 'rg8sint',
  21044. // 32-bit formats
  21045. R32Uint: 'r32uint',
  21046. R32Sint: 'r32sint',
  21047. R32Float: 'r32float',
  21048. RG16Uint: 'rg16uint',
  21049. RG16Sint: 'rg16sint',
  21050. RG16Float: 'rg16float',
  21051. RGBA8Unorm: 'rgba8unorm',
  21052. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  21053. RGBA8Snorm: 'rgba8snorm',
  21054. RGBA8Uint: 'rgba8uint',
  21055. RGBA8Sint: 'rgba8sint',
  21056. BGRA8Unorm: 'bgra8unorm',
  21057. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  21058. // Packed 32-bit formats
  21059. RGB9E5UFloat: 'rgb9e5ufloat',
  21060. RGB10A2Unorm: 'rgb10a2unorm',
  21061. RG11B10uFloat: 'rgb10a2unorm',
  21062. // 64-bit formats
  21063. RG32Uint: 'rg32uint',
  21064. RG32Sint: 'rg32sint',
  21065. RG32Float: 'rg32float',
  21066. RGBA16Uint: 'rgba16uint',
  21067. RGBA16Sint: 'rgba16sint',
  21068. RGBA16Float: 'rgba16float',
  21069. // 128-bit formats
  21070. RGBA32Uint: 'rgba32uint',
  21071. RGBA32Sint: 'rgba32sint',
  21072. RGBA32Float: 'rgba32float',
  21073. // Depth and stencil formats
  21074. Stencil8: 'stencil8',
  21075. Depth16Unorm: 'depth16unorm',
  21076. Depth24Plus: 'depth24plus',
  21077. Depth24PlusStencil8: 'depth24plus-stencil8',
  21078. Depth32Float: 'depth32float',
  21079. // 'depth32float-stencil8' extension
  21080. Depth32FloatStencil8: 'depth32float-stencil8',
  21081. // BC compressed formats usable if 'texture-compression-bc' is both
  21082. // supported by the device/user agent and enabled in requestDevice.
  21083. BC1RGBAUnorm: 'bc1-rgba-unorm',
  21084. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  21085. BC2RGBAUnorm: 'bc2-rgba-unorm',
  21086. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  21087. BC3RGBAUnorm: 'bc3-rgba-unorm',
  21088. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  21089. BC4RUnorm: 'bc4-r-unorm',
  21090. BC4RSnorm: 'bc4-r-snorm',
  21091. BC5RGUnorm: 'bc5-rg-unorm',
  21092. BC5RGSnorm: 'bc5-rg-snorm',
  21093. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  21094. BC6HRGBFloat: 'bc6h-rgb-float',
  21095. BC7RGBAUnorm: 'bc7-rgba-unorm',
  21096. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  21097. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  21098. // supported by the device/user agent and enabled in requestDevice.
  21099. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  21100. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  21101. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  21102. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  21103. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  21104. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  21105. EACR11Unorm: 'eac-r11unorm',
  21106. EACR11Snorm: 'eac-r11snorm',
  21107. EACRG11Unorm: 'eac-rg11unorm',
  21108. EACRG11Snorm: 'eac-rg11snorm',
  21109. // ASTC compressed formats usable if 'texture-compression-astc' is both
  21110. // supported by the device/user agent and enabled in requestDevice.
  21111. ASTC4x4Unorm: 'astc-4x4-unorm',
  21112. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  21113. ASTC5x4Unorm: 'astc-5x4-unorm',
  21114. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  21115. ASTC5x5Unorm: 'astc-5x5-unorm',
  21116. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  21117. ASTC6x5Unorm: 'astc-6x5-unorm',
  21118. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  21119. ASTC6x6Unorm: 'astc-6x6-unorm',
  21120. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  21121. ASTC8x5Unorm: 'astc-8x5-unorm',
  21122. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  21123. ASTC8x6Unorm: 'astc-8x6-unorm',
  21124. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  21125. ASTC8x8Unorm: 'astc-8x8-unorm',
  21126. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  21127. ASTC10x5Unorm: 'astc-10x5-unorm',
  21128. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  21129. ASTC10x6Unorm: 'astc-10x6-unorm',
  21130. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  21131. ASTC10x8Unorm: 'astc-10x8-unorm',
  21132. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  21133. ASTC10x10Unorm: 'astc-10x10-unorm',
  21134. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  21135. ASTC12x10Unorm: 'astc-12x10-unorm',
  21136. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  21137. ASTC12x12Unorm: 'astc-12x12-unorm',
  21138. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  21139. };
  21140. const GPUAddressMode = {
  21141. ClampToEdge: 'clamp-to-edge',
  21142. Repeat: 'repeat',
  21143. MirrorRepeat: 'mirror-repeat'
  21144. };
  21145. const GPUFilterMode = {
  21146. Linear: 'linear',
  21147. Nearest: 'nearest'
  21148. };
  21149. const GPUBlendFactor = {
  21150. Zero: 'zero',
  21151. One: 'one',
  21152. Src: 'src',
  21153. OneMinusSrc: 'one-minus-src',
  21154. SrcAlpha: 'src-alpha',
  21155. OneMinusSrcAlpha: 'one-minus-src-alpha',
  21156. Dst: 'dst',
  21157. OneMinusDstColor: 'one-minus-dst',
  21158. DstAlpha: 'dst-alpha',
  21159. OneMinusDstAlpha: 'one-minus-dst-alpha',
  21160. SrcAlphaSaturated: 'src-alpha-saturated',
  21161. Constant: 'constant',
  21162. OneMinusConstant: 'one-minus-constant'
  21163. };
  21164. const GPUBlendOperation = {
  21165. Add: 'add',
  21166. Subtract: 'subtract',
  21167. ReverseSubtract: 'reverse-subtract',
  21168. Min: 'min',
  21169. Max: 'max'
  21170. };
  21171. const GPUColorWriteFlags = {
  21172. None: 0,
  21173. Red: 0x1,
  21174. Green: 0x2,
  21175. Blue: 0x4,
  21176. Alpha: 0x8,
  21177. All: 0xF
  21178. };
  21179. const GPUStencilOperation = {
  21180. Keep: 'keep',
  21181. Zero: 'zero',
  21182. Replace: 'replace',
  21183. Invert: 'invert',
  21184. IncrementClamp: 'increment-clamp',
  21185. DecrementClamp: 'decrement-clamp',
  21186. IncrementWrap: 'increment-wrap',
  21187. DecrementWrap: 'decrement-wrap'
  21188. };
  21189. const GPUBufferBindingType = {
  21190. Uniform: 'uniform',
  21191. Storage: 'storage',
  21192. ReadOnlyStorage: 'read-only-storage'
  21193. };
  21194. const GPUStorageTextureAccess = {
  21195. WriteOnly: 'write-only',
  21196. ReadOnly: 'read-only',
  21197. ReadWrite: 'read-write',
  21198. };
  21199. const GPUTextureSampleType = {
  21200. Float: 'float',
  21201. UnfilterableFloat: 'unfilterable-float',
  21202. Depth: 'depth',
  21203. SInt: 'sint',
  21204. UInt: 'uint'
  21205. };
  21206. const GPUTextureDimension = {
  21207. OneD: '1d',
  21208. TwoD: '2d',
  21209. ThreeD: '3d'
  21210. };
  21211. const GPUTextureViewDimension = {
  21212. OneD: '1d',
  21213. TwoD: '2d',
  21214. TwoDArray: '2d-array',
  21215. Cube: 'cube',
  21216. CubeArray: 'cube-array',
  21217. ThreeD: '3d'
  21218. };
  21219. const GPUTextureAspect = {
  21220. All: 'all',
  21221. StencilOnly: 'stencil-only',
  21222. DepthOnly: 'depth-only'
  21223. };
  21224. const GPUInputStepMode = {
  21225. Vertex: 'vertex',
  21226. Instance: 'instance'
  21227. };
  21228. const GPUFeatureName = {
  21229. DepthClipControl: 'depth-clip-control',
  21230. Depth32FloatStencil8: 'depth32float-stencil8',
  21231. TextureCompressionBC: 'texture-compression-bc',
  21232. TextureCompressionETC2: 'texture-compression-etc2',
  21233. TextureCompressionASTC: 'texture-compression-astc',
  21234. TimestampQuery: 'timestamp-query',
  21235. IndirectFirstInstance: 'indirect-first-instance',
  21236. ShaderF16: 'shader-f16',
  21237. RG11B10UFloat: 'rg11b10ufloat-renderable',
  21238. BGRA8UNormStorage: 'bgra8unorm-storage',
  21239. Float32Filterable: 'float32-filterable',
  21240. ClipDistances: 'clip-distances',
  21241. DualSourceBlending: 'dual-source-blending',
  21242. Subgroups: 'subgroups'
  21243. };
  21244. class Sampler extends Binding {
  21245. constructor( name, texture ) {
  21246. super( name );
  21247. this.texture = texture;
  21248. this.version = texture ? texture.version : 0;
  21249. this.isSampler = true;
  21250. }
  21251. }
  21252. class NodeSampler extends Sampler {
  21253. constructor( name, textureNode, groupNode ) {
  21254. super( name, textureNode ? textureNode.value : null );
  21255. this.textureNode = textureNode;
  21256. this.groupNode = groupNode;
  21257. }
  21258. update() {
  21259. this.texture = this.textureNode.value;
  21260. }
  21261. }
  21262. class StorageBuffer extends Buffer {
  21263. constructor( name, attribute ) {
  21264. super( name, attribute ? attribute.array : null );
  21265. this.attribute = attribute;
  21266. this.isStorageBuffer = true;
  21267. }
  21268. }
  21269. let _id = 0;
  21270. class NodeStorageBuffer extends StorageBuffer {
  21271. constructor( nodeUniform, groupNode ) {
  21272. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  21273. this.nodeUniform = nodeUniform;
  21274. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  21275. this.groupNode = groupNode;
  21276. }
  21277. get buffer() {
  21278. return this.nodeUniform.value;
  21279. }
  21280. }
  21281. class WebGPUTexturePassUtils extends DataMap {
  21282. constructor( device ) {
  21283. super();
  21284. this.device = device;
  21285. const mipmapVertexSource = `
  21286. struct VarysStruct {
  21287. @builtin( position ) Position: vec4<f32>,
  21288. @location( 0 ) vTex : vec2<f32>
  21289. };
  21290. @vertex
  21291. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  21292. var Varys : VarysStruct;
  21293. var pos = array< vec2<f32>, 4 >(
  21294. vec2<f32>( -1.0, 1.0 ),
  21295. vec2<f32>( 1.0, 1.0 ),
  21296. vec2<f32>( -1.0, -1.0 ),
  21297. vec2<f32>( 1.0, -1.0 )
  21298. );
  21299. var tex = array< vec2<f32>, 4 >(
  21300. vec2<f32>( 0.0, 0.0 ),
  21301. vec2<f32>( 1.0, 0.0 ),
  21302. vec2<f32>( 0.0, 1.0 ),
  21303. vec2<f32>( 1.0, 1.0 )
  21304. );
  21305. Varys.vTex = tex[ vertexIndex ];
  21306. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  21307. return Varys;
  21308. }
  21309. `;
  21310. const mipmapFragmentSource = `
  21311. @group( 0 ) @binding( 0 )
  21312. var imgSampler : sampler;
  21313. @group( 0 ) @binding( 1 )
  21314. var img : texture_2d<f32>;
  21315. @fragment
  21316. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  21317. return textureSample( img, imgSampler, vTex );
  21318. }
  21319. `;
  21320. const flipYFragmentSource = `
  21321. @group( 0 ) @binding( 0 )
  21322. var imgSampler : sampler;
  21323. @group( 0 ) @binding( 1 )
  21324. var img : texture_2d<f32>;
  21325. @fragment
  21326. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  21327. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  21328. }
  21329. `;
  21330. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  21331. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  21332. // We'll need a new pipeline for every texture format used.
  21333. this.transferPipelines = {};
  21334. this.flipYPipelines = {};
  21335. this.mipmapVertexShaderModule = device.createShaderModule( {
  21336. label: 'mipmapVertex',
  21337. code: mipmapVertexSource
  21338. } );
  21339. this.mipmapFragmentShaderModule = device.createShaderModule( {
  21340. label: 'mipmapFragment',
  21341. code: mipmapFragmentSource
  21342. } );
  21343. this.flipYFragmentShaderModule = device.createShaderModule( {
  21344. label: 'flipYFragment',
  21345. code: flipYFragmentSource
  21346. } );
  21347. }
  21348. getTransferPipeline( format ) {
  21349. let pipeline = this.transferPipelines[ format ];
  21350. if ( pipeline === undefined ) {
  21351. pipeline = this.device.createRenderPipeline( {
  21352. label: `mipmap-${ format }`,
  21353. vertex: {
  21354. module: this.mipmapVertexShaderModule,
  21355. entryPoint: 'main'
  21356. },
  21357. fragment: {
  21358. module: this.mipmapFragmentShaderModule,
  21359. entryPoint: 'main',
  21360. targets: [ { format } ]
  21361. },
  21362. primitive: {
  21363. topology: GPUPrimitiveTopology.TriangleStrip,
  21364. stripIndexFormat: GPUIndexFormat.Uint32
  21365. },
  21366. layout: 'auto'
  21367. } );
  21368. this.transferPipelines[ format ] = pipeline;
  21369. }
  21370. return pipeline;
  21371. }
  21372. getFlipYPipeline( format ) {
  21373. let pipeline = this.flipYPipelines[ format ];
  21374. if ( pipeline === undefined ) {
  21375. pipeline = this.device.createRenderPipeline( {
  21376. label: `flipY-${ format }`,
  21377. vertex: {
  21378. module: this.mipmapVertexShaderModule,
  21379. entryPoint: 'main'
  21380. },
  21381. fragment: {
  21382. module: this.flipYFragmentShaderModule,
  21383. entryPoint: 'main',
  21384. targets: [ { format } ]
  21385. },
  21386. primitive: {
  21387. topology: GPUPrimitiveTopology.TriangleStrip,
  21388. stripIndexFormat: GPUIndexFormat.Uint32
  21389. },
  21390. layout: 'auto'
  21391. } );
  21392. this.flipYPipelines[ format ] = pipeline;
  21393. }
  21394. return pipeline;
  21395. }
  21396. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  21397. const format = textureGPUDescriptor.format;
  21398. const { width, height } = textureGPUDescriptor.size;
  21399. const transferPipeline = this.getTransferPipeline( format );
  21400. const flipYPipeline = this.getFlipYPipeline( format );
  21401. const tempTexture = this.device.createTexture( {
  21402. size: { width, height, depthOrArrayLayers: 1 },
  21403. format,
  21404. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  21405. } );
  21406. const srcView = textureGPU.createView( {
  21407. baseMipLevel: 0,
  21408. mipLevelCount: 1,
  21409. dimension: GPUTextureViewDimension.TwoD,
  21410. baseArrayLayer
  21411. } );
  21412. const dstView = tempTexture.createView( {
  21413. baseMipLevel: 0,
  21414. mipLevelCount: 1,
  21415. dimension: GPUTextureViewDimension.TwoD,
  21416. baseArrayLayer: 0
  21417. } );
  21418. const commandEncoder = this.device.createCommandEncoder( {} );
  21419. const pass = ( pipeline, sourceView, destinationView ) => {
  21420. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  21421. const bindGroup = this.device.createBindGroup( {
  21422. layout: bindGroupLayout,
  21423. entries: [ {
  21424. binding: 0,
  21425. resource: this.flipYSampler
  21426. }, {
  21427. binding: 1,
  21428. resource: sourceView
  21429. } ]
  21430. } );
  21431. const passEncoder = commandEncoder.beginRenderPass( {
  21432. colorAttachments: [ {
  21433. view: destinationView,
  21434. loadOp: GPULoadOp.Clear,
  21435. storeOp: GPUStoreOp.Store,
  21436. clearValue: [ 0, 0, 0, 0 ]
  21437. } ]
  21438. } );
  21439. passEncoder.setPipeline( pipeline );
  21440. passEncoder.setBindGroup( 0, bindGroup );
  21441. passEncoder.draw( 4, 1, 0, 0 );
  21442. passEncoder.end();
  21443. };
  21444. pass( transferPipeline, srcView, dstView );
  21445. pass( flipYPipeline, dstView, srcView );
  21446. this.device.queue.submit( [ commandEncoder.finish() ] );
  21447. tempTexture.destroy();
  21448. }
  21449. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  21450. const textureData = this.get( textureGPU );
  21451. if ( textureData.useCount === undefined ) {
  21452. textureData.useCount = 0;
  21453. textureData.layers = [];
  21454. }
  21455. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  21456. const commandEncoder = this.device.createCommandEncoder( {} );
  21457. this._mipmapRunBundles( commandEncoder, passes );
  21458. this.device.queue.submit( [ commandEncoder.finish() ] );
  21459. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  21460. textureData.useCount ++;
  21461. }
  21462. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  21463. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  21464. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  21465. let srcView = textureGPU.createView( {
  21466. baseMipLevel: 0,
  21467. mipLevelCount: 1,
  21468. dimension: GPUTextureViewDimension.TwoD,
  21469. baseArrayLayer
  21470. } );
  21471. const passes = [];
  21472. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  21473. const bindGroup = this.device.createBindGroup( {
  21474. layout: bindGroupLayout,
  21475. entries: [ {
  21476. binding: 0,
  21477. resource: this.mipmapSampler
  21478. }, {
  21479. binding: 1,
  21480. resource: srcView
  21481. } ]
  21482. } );
  21483. const dstView = textureGPU.createView( {
  21484. baseMipLevel: i,
  21485. mipLevelCount: 1,
  21486. dimension: GPUTextureViewDimension.TwoD,
  21487. baseArrayLayer
  21488. } );
  21489. const passDescriptor = {
  21490. colorAttachments: [ {
  21491. view: dstView,
  21492. loadOp: GPULoadOp.Clear,
  21493. storeOp: GPUStoreOp.Store,
  21494. clearValue: [ 0, 0, 0, 0 ]
  21495. } ]
  21496. };
  21497. const passEncoder = this.device.createRenderBundleEncoder( {
  21498. colorFormats: [ textureGPUDescriptor.format ]
  21499. } );
  21500. passEncoder.setPipeline( pipeline );
  21501. passEncoder.setBindGroup( 0, bindGroup );
  21502. passEncoder.draw( 4, 1, 0, 0 );
  21503. passes.push( {
  21504. renderBundles: [ passEncoder.finish() ],
  21505. passDescriptor
  21506. } );
  21507. srcView = dstView;
  21508. }
  21509. return passes;
  21510. }
  21511. _mipmapRunBundles( commandEncoder, passes ) {
  21512. const levels = passes.length;
  21513. for ( let i = 0; i < levels; i ++ ) {
  21514. const pass = passes[ i ];
  21515. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  21516. passEncoder.executeBundles( pass.renderBundles );
  21517. passEncoder.end();
  21518. }
  21519. }
  21520. }
  21521. const _compareToWebGPU = {
  21522. [ NeverCompare ]: 'never',
  21523. [ LessCompare ]: 'less',
  21524. [ EqualCompare ]: 'equal',
  21525. [ LessEqualCompare ]: 'less-equal',
  21526. [ GreaterCompare ]: 'greater',
  21527. [ GreaterEqualCompare ]: 'greater-equal',
  21528. [ AlwaysCompare ]: 'always',
  21529. [ NotEqualCompare ]: 'not-equal'
  21530. };
  21531. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  21532. class WebGPUTextureUtils {
  21533. constructor( backend ) {
  21534. this.backend = backend;
  21535. this._passUtils = null;
  21536. this.defaultTexture = {};
  21537. this.defaultCubeTexture = {};
  21538. this.defaultVideoFrame = null;
  21539. this.colorBuffer = null;
  21540. this.depthTexture = new DepthTexture();
  21541. this.depthTexture.name = 'depthBuffer';
  21542. }
  21543. createSampler( texture ) {
  21544. const backend = this.backend;
  21545. const device = backend.device;
  21546. const textureGPU = backend.get( texture );
  21547. const samplerDescriptorGPU = {
  21548. addressModeU: this._convertAddressMode( texture.wrapS ),
  21549. addressModeV: this._convertAddressMode( texture.wrapT ),
  21550. addressModeW: this._convertAddressMode( texture.wrapR ),
  21551. magFilter: this._convertFilterMode( texture.magFilter ),
  21552. minFilter: this._convertFilterMode( texture.minFilter ),
  21553. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  21554. maxAnisotropy: 1
  21555. };
  21556. // anisotropy can only be used when all filter modes are set to linear.
  21557. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  21558. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  21559. }
  21560. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  21561. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  21562. }
  21563. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  21564. }
  21565. createDefaultTexture( texture ) {
  21566. let textureGPU;
  21567. const format = getFormat( texture );
  21568. if ( texture.isCubeTexture ) {
  21569. textureGPU = this._getDefaultCubeTextureGPU( format );
  21570. } else if ( texture.isVideoTexture ) {
  21571. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  21572. } else {
  21573. textureGPU = this._getDefaultTextureGPU( format );
  21574. }
  21575. this.backend.get( texture ).texture = textureGPU;
  21576. }
  21577. createTexture( texture, options = {} ) {
  21578. const backend = this.backend;
  21579. const textureData = backend.get( texture );
  21580. if ( textureData.initialized ) {
  21581. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  21582. }
  21583. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  21584. if ( options.levels === undefined ) options.levels = 1;
  21585. if ( options.depth === undefined ) options.depth = 1;
  21586. const { width, height, depth, levels } = options;
  21587. if ( texture.isFramebufferTexture ) {
  21588. if ( options.renderTarget ) {
  21589. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  21590. } else {
  21591. options.format = this.backend.utils.getPreferredCanvasFormat();
  21592. }
  21593. }
  21594. const dimension = this._getDimension( texture );
  21595. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  21596. textureData.format = format;
  21597. let sampleCount = options.sampleCount !== undefined ? options.sampleCount : 1;
  21598. sampleCount = backend.utils.getSampleCount( sampleCount );
  21599. const primarySampleCount = texture.isRenderTargetTexture && ! texture.isMultisampleRenderTargetTexture ? 1 : sampleCount;
  21600. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  21601. if ( texture.isStorageTexture === true ) {
  21602. usage |= GPUTextureUsage.STORAGE_BINDING;
  21603. }
  21604. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  21605. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  21606. }
  21607. const textureDescriptorGPU = {
  21608. label: texture.name,
  21609. size: {
  21610. width: width,
  21611. height: height,
  21612. depthOrArrayLayers: depth,
  21613. },
  21614. mipLevelCount: levels,
  21615. sampleCount: primarySampleCount,
  21616. dimension: dimension,
  21617. format: format,
  21618. usage: usage
  21619. };
  21620. // texture creation
  21621. if ( texture.isVideoTexture ) {
  21622. const video = texture.source.data;
  21623. const videoFrame = new VideoFrame( video );
  21624. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  21625. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  21626. videoFrame.close();
  21627. textureData.externalTexture = video;
  21628. } else {
  21629. if ( format === undefined ) {
  21630. console.warn( 'WebGPURenderer: Texture format not supported.' );
  21631. return this.createDefaultTexture( texture );
  21632. }
  21633. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  21634. }
  21635. if ( texture.isRenderTargetTexture && sampleCount > 1 && ! texture.isMultisampleRenderTargetTexture ) {
  21636. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  21637. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  21638. msaaTextureDescriptorGPU.sampleCount = sampleCount;
  21639. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  21640. }
  21641. textureData.initialized = true;
  21642. textureData.textureDescriptorGPU = textureDescriptorGPU;
  21643. }
  21644. destroyTexture( texture ) {
  21645. const backend = this.backend;
  21646. const textureData = backend.get( texture );
  21647. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  21648. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  21649. backend.delete( texture );
  21650. }
  21651. destroySampler( texture ) {
  21652. const backend = this.backend;
  21653. const textureData = backend.get( texture );
  21654. delete textureData.sampler;
  21655. }
  21656. generateMipmaps( texture ) {
  21657. const textureData = this.backend.get( texture );
  21658. if ( texture.isCubeTexture ) {
  21659. for ( let i = 0; i < 6; i ++ ) {
  21660. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  21661. }
  21662. } else {
  21663. const depth = texture.image.depth || 1;
  21664. for ( let i = 0; i < depth; i ++ ) {
  21665. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  21666. }
  21667. }
  21668. }
  21669. getColorBuffer() {
  21670. if ( this.colorBuffer ) this.colorBuffer.destroy();
  21671. const backend = this.backend;
  21672. const { width, height } = backend.getDrawingBufferSize();
  21673. this.colorBuffer = backend.device.createTexture( {
  21674. label: 'colorBuffer',
  21675. size: {
  21676. width: width,
  21677. height: height,
  21678. depthOrArrayLayers: 1
  21679. },
  21680. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  21681. format: backend.utils.getPreferredCanvasFormat(),
  21682. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  21683. } );
  21684. return this.colorBuffer;
  21685. }
  21686. getDepthBuffer( depth = true, stencil = false ) {
  21687. const backend = this.backend;
  21688. const { width, height } = backend.getDrawingBufferSize();
  21689. const depthTexture = this.depthTexture;
  21690. const depthTextureGPU = backend.get( depthTexture ).texture;
  21691. let format, type;
  21692. if ( stencil ) {
  21693. format = DepthStencilFormat;
  21694. type = UnsignedInt248Type;
  21695. } else if ( depth ) {
  21696. format = DepthFormat;
  21697. type = UnsignedIntType;
  21698. }
  21699. if ( depthTextureGPU !== undefined ) {
  21700. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  21701. return depthTextureGPU;
  21702. }
  21703. this.destroyTexture( depthTexture );
  21704. }
  21705. depthTexture.name = 'depthBuffer';
  21706. depthTexture.format = format;
  21707. depthTexture.type = type;
  21708. depthTexture.image.width = width;
  21709. depthTexture.image.height = height;
  21710. this.createTexture( depthTexture, { sampleCount: backend.utils.getSampleCount( backend.renderer.samples ), width, height } );
  21711. return backend.get( depthTexture ).texture;
  21712. }
  21713. updateTexture( texture, options ) {
  21714. const textureData = this.backend.get( texture );
  21715. const { textureDescriptorGPU } = textureData;
  21716. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  21717. return;
  21718. // transfer texture data
  21719. if ( texture.isDataTexture ) {
  21720. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  21721. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  21722. for ( let i = 0; i < options.image.depth; i ++ ) {
  21723. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  21724. }
  21725. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  21726. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  21727. } else if ( texture.isCubeTexture ) {
  21728. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  21729. } else if ( texture.isVideoTexture ) {
  21730. const video = texture.source.data;
  21731. textureData.externalTexture = video;
  21732. } else {
  21733. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  21734. }
  21735. //
  21736. textureData.version = texture.version;
  21737. if ( texture.onUpdate ) texture.onUpdate( texture );
  21738. }
  21739. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  21740. const device = this.backend.device;
  21741. const textureData = this.backend.get( texture );
  21742. const textureGPU = textureData.texture;
  21743. const format = textureData.textureDescriptorGPU.format;
  21744. const bytesPerTexel = this._getBytesPerTexel( format );
  21745. let bytesPerRow = width * bytesPerTexel;
  21746. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  21747. const readBuffer = device.createBuffer(
  21748. {
  21749. size: width * height * bytesPerTexel,
  21750. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  21751. }
  21752. );
  21753. const encoder = device.createCommandEncoder();
  21754. encoder.copyTextureToBuffer(
  21755. {
  21756. texture: textureGPU,
  21757. origin: { x, y, z: faceIndex },
  21758. },
  21759. {
  21760. buffer: readBuffer,
  21761. bytesPerRow: bytesPerRow
  21762. },
  21763. {
  21764. width: width,
  21765. height: height
  21766. }
  21767. );
  21768. const typedArrayType = this._getTypedArrayType( format );
  21769. device.queue.submit( [ encoder.finish() ] );
  21770. await readBuffer.mapAsync( GPUMapMode.READ );
  21771. const buffer = readBuffer.getMappedRange();
  21772. return new typedArrayType( buffer );
  21773. }
  21774. _isEnvironmentTexture( texture ) {
  21775. const mapping = texture.mapping;
  21776. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  21777. }
  21778. _getDefaultTextureGPU( format ) {
  21779. let defaultTexture = this.defaultTexture[ format ];
  21780. if ( defaultTexture === undefined ) {
  21781. const texture = new Texture();
  21782. texture.minFilter = NearestFilter;
  21783. texture.magFilter = NearestFilter;
  21784. this.createTexture( texture, { width: 1, height: 1, format } );
  21785. this.defaultTexture[ format ] = defaultTexture = texture;
  21786. }
  21787. return this.backend.get( defaultTexture ).texture;
  21788. }
  21789. _getDefaultCubeTextureGPU( format ) {
  21790. let defaultCubeTexture = this.defaultTexture[ format ];
  21791. if ( defaultCubeTexture === undefined ) {
  21792. const texture = new CubeTexture();
  21793. texture.minFilter = NearestFilter;
  21794. texture.magFilter = NearestFilter;
  21795. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  21796. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  21797. }
  21798. return this.backend.get( defaultCubeTexture ).texture;
  21799. }
  21800. _getDefaultVideoFrame() {
  21801. let defaultVideoFrame = this.defaultVideoFrame;
  21802. if ( defaultVideoFrame === null ) {
  21803. const init = {
  21804. timestamp: 0,
  21805. codedWidth: 1,
  21806. codedHeight: 1,
  21807. format: 'RGBA',
  21808. };
  21809. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  21810. }
  21811. return defaultVideoFrame;
  21812. }
  21813. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  21814. for ( let i = 0; i < 6; i ++ ) {
  21815. const image = images[ i ];
  21816. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  21817. if ( image.isDataTexture ) {
  21818. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  21819. } else {
  21820. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  21821. }
  21822. }
  21823. }
  21824. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  21825. const device = this.backend.device;
  21826. device.queue.copyExternalImageToTexture(
  21827. {
  21828. source: image
  21829. }, {
  21830. texture: textureGPU,
  21831. mipLevel: 0,
  21832. origin: { x: 0, y: 0, z: originDepth }
  21833. }, {
  21834. width: image.width,
  21835. height: image.height,
  21836. depthOrArrayLayers: 1
  21837. }
  21838. );
  21839. if ( flipY === true ) {
  21840. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  21841. }
  21842. }
  21843. _getPassUtils() {
  21844. let passUtils = this._passUtils;
  21845. if ( passUtils === null ) {
  21846. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  21847. }
  21848. return passUtils;
  21849. }
  21850. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  21851. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  21852. }
  21853. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  21854. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  21855. }
  21856. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  21857. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  21858. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  21859. const device = this.backend.device;
  21860. const data = image.data;
  21861. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  21862. const bytesPerRow = image.width * bytesPerTexel;
  21863. device.queue.writeTexture(
  21864. {
  21865. texture: textureGPU,
  21866. mipLevel: 0,
  21867. origin: { x: 0, y: 0, z: originDepth }
  21868. },
  21869. data,
  21870. {
  21871. offset: image.width * image.height * bytesPerTexel * depth,
  21872. bytesPerRow
  21873. },
  21874. {
  21875. width: image.width,
  21876. height: image.height,
  21877. depthOrArrayLayers: 1
  21878. } );
  21879. if ( flipY === true ) {
  21880. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  21881. }
  21882. }
  21883. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  21884. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  21885. const device = this.backend.device;
  21886. const blockData = this._getBlockData( textureDescriptorGPU.format );
  21887. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  21888. for ( let i = 0; i < mipmaps.length; i ++ ) {
  21889. const mipmap = mipmaps[ i ];
  21890. const width = mipmap.width;
  21891. const height = mipmap.height;
  21892. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  21893. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  21894. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  21895. for ( let j = 0; j < depth; j ++ ) {
  21896. device.queue.writeTexture(
  21897. {
  21898. texture: textureGPU,
  21899. mipLevel: i,
  21900. origin: { x: 0, y: 0, z: j }
  21901. },
  21902. mipmap.data,
  21903. {
  21904. offset: j * bytesPerImage,
  21905. bytesPerRow,
  21906. rowsPerImage: Math.ceil( height / blockData.height )
  21907. },
  21908. {
  21909. width: Math.ceil( width / blockData.width ) * blockData.width,
  21910. height: Math.ceil( height / blockData.height ) * blockData.height,
  21911. depthOrArrayLayers: 1
  21912. }
  21913. );
  21914. }
  21915. }
  21916. }
  21917. _getBlockData( format ) {
  21918. // this method is only relevant for compressed texture formats
  21919. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  21920. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  21921. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  21922. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  21923. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  21924. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  21925. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  21926. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  21927. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  21928. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  21929. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  21930. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  21931. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  21932. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  21933. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  21934. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  21935. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  21936. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  21937. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  21938. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  21939. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  21940. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  21941. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  21942. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  21943. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  21944. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  21945. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  21946. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  21947. }
  21948. _convertAddressMode( value ) {
  21949. let addressMode = GPUAddressMode.ClampToEdge;
  21950. if ( value === RepeatWrapping ) {
  21951. addressMode = GPUAddressMode.Repeat;
  21952. } else if ( value === MirroredRepeatWrapping ) {
  21953. addressMode = GPUAddressMode.MirrorRepeat;
  21954. }
  21955. return addressMode;
  21956. }
  21957. _convertFilterMode( value ) {
  21958. let filterMode = GPUFilterMode.Linear;
  21959. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  21960. filterMode = GPUFilterMode.Nearest;
  21961. }
  21962. return filterMode;
  21963. }
  21964. _getBytesPerTexel( format ) {
  21965. // 8-bit formats
  21966. if ( format === GPUTextureFormat.R8Unorm ||
  21967. format === GPUTextureFormat.R8Snorm ||
  21968. format === GPUTextureFormat.R8Uint ||
  21969. format === GPUTextureFormat.R8Sint ) return 1;
  21970. // 16-bit formats
  21971. if ( format === GPUTextureFormat.R16Uint ||
  21972. format === GPUTextureFormat.R16Sint ||
  21973. format === GPUTextureFormat.R16Float ||
  21974. format === GPUTextureFormat.RG8Unorm ||
  21975. format === GPUTextureFormat.RG8Snorm ||
  21976. format === GPUTextureFormat.RG8Uint ||
  21977. format === GPUTextureFormat.RG8Sint ) return 2;
  21978. // 32-bit formats
  21979. if ( format === GPUTextureFormat.R32Uint ||
  21980. format === GPUTextureFormat.R32Sint ||
  21981. format === GPUTextureFormat.R32Float ||
  21982. format === GPUTextureFormat.RG16Uint ||
  21983. format === GPUTextureFormat.RG16Sint ||
  21984. format === GPUTextureFormat.RG16Float ||
  21985. format === GPUTextureFormat.RGBA8Unorm ||
  21986. format === GPUTextureFormat.RGBA8UnormSRGB ||
  21987. format === GPUTextureFormat.RGBA8Snorm ||
  21988. format === GPUTextureFormat.RGBA8Uint ||
  21989. format === GPUTextureFormat.RGBA8Sint ||
  21990. format === GPUTextureFormat.BGRA8Unorm ||
  21991. format === GPUTextureFormat.BGRA8UnormSRGB ||
  21992. // Packed 32-bit formats
  21993. format === GPUTextureFormat.RGB9E5UFloat ||
  21994. format === GPUTextureFormat.RGB10A2Unorm ||
  21995. format === GPUTextureFormat.RG11B10UFloat ||
  21996. format === GPUTextureFormat.Depth32Float ||
  21997. format === GPUTextureFormat.Depth24Plus ||
  21998. format === GPUTextureFormat.Depth24PlusStencil8 ||
  21999. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  22000. // 64-bit formats
  22001. if ( format === GPUTextureFormat.RG32Uint ||
  22002. format === GPUTextureFormat.RG32Sint ||
  22003. format === GPUTextureFormat.RG32Float ||
  22004. format === GPUTextureFormat.RGBA16Uint ||
  22005. format === GPUTextureFormat.RGBA16Sint ||
  22006. format === GPUTextureFormat.RGBA16Float ) return 8;
  22007. // 128-bit formats
  22008. if ( format === GPUTextureFormat.RGBA32Uint ||
  22009. format === GPUTextureFormat.RGBA32Sint ||
  22010. format === GPUTextureFormat.RGBA32Float ) return 16;
  22011. }
  22012. _getTypedArrayType( format ) {
  22013. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  22014. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  22015. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  22016. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  22017. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  22018. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  22019. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  22020. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  22021. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  22022. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  22023. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  22024. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  22025. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  22026. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  22027. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  22028. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  22029. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  22030. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  22031. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  22032. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  22033. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  22034. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  22035. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  22036. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  22037. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  22038. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  22039. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  22040. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  22041. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  22042. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  22043. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  22044. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  22045. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  22046. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  22047. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  22048. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  22049. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  22050. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  22051. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  22052. }
  22053. _getDimension( texture ) {
  22054. let dimension;
  22055. if ( texture.isData3DTexture ) {
  22056. dimension = GPUTextureDimension.ThreeD;
  22057. } else {
  22058. dimension = GPUTextureDimension.TwoD;
  22059. }
  22060. return dimension;
  22061. }
  22062. }
  22063. function getFormat( texture, device = null ) {
  22064. const format = texture.format;
  22065. const type = texture.type;
  22066. const colorSpace = texture.colorSpace;
  22067. let formatGPU;
  22068. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  22069. switch ( format ) {
  22070. case RGBA_S3TC_DXT1_Format:
  22071. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  22072. break;
  22073. case RGBA_S3TC_DXT3_Format:
  22074. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  22075. break;
  22076. case RGBA_S3TC_DXT5_Format:
  22077. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  22078. break;
  22079. case RGB_ETC2_Format:
  22080. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  22081. break;
  22082. case RGBA_ETC2_EAC_Format:
  22083. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  22084. break;
  22085. case RGBA_ASTC_4x4_Format:
  22086. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  22087. break;
  22088. case RGBA_ASTC_5x4_Format:
  22089. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  22090. break;
  22091. case RGBA_ASTC_5x5_Format:
  22092. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  22093. break;
  22094. case RGBA_ASTC_6x5_Format:
  22095. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  22096. break;
  22097. case RGBA_ASTC_6x6_Format:
  22098. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  22099. break;
  22100. case RGBA_ASTC_8x5_Format:
  22101. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  22102. break;
  22103. case RGBA_ASTC_8x6_Format:
  22104. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  22105. break;
  22106. case RGBA_ASTC_8x8_Format:
  22107. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  22108. break;
  22109. case RGBA_ASTC_10x5_Format:
  22110. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  22111. break;
  22112. case RGBA_ASTC_10x6_Format:
  22113. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  22114. break;
  22115. case RGBA_ASTC_10x8_Format:
  22116. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  22117. break;
  22118. case RGBA_ASTC_10x10_Format:
  22119. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  22120. break;
  22121. case RGBA_ASTC_12x10_Format:
  22122. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  22123. break;
  22124. case RGBA_ASTC_12x12_Format:
  22125. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  22126. break;
  22127. case RGBAFormat:
  22128. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  22129. break;
  22130. default:
  22131. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  22132. }
  22133. } else {
  22134. switch ( format ) {
  22135. case RGBAFormat:
  22136. switch ( type ) {
  22137. case ByteType:
  22138. formatGPU = GPUTextureFormat.RGBA8Snorm;
  22139. break;
  22140. case ShortType:
  22141. formatGPU = GPUTextureFormat.RGBA16Sint;
  22142. break;
  22143. case UnsignedShortType:
  22144. formatGPU = GPUTextureFormat.RGBA16Uint;
  22145. break;
  22146. case UnsignedIntType:
  22147. formatGPU = GPUTextureFormat.RGBA32Uint;
  22148. break;
  22149. case IntType:
  22150. formatGPU = GPUTextureFormat.RGBA32Sint;
  22151. break;
  22152. case UnsignedByteType:
  22153. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  22154. break;
  22155. case HalfFloatType:
  22156. formatGPU = GPUTextureFormat.RGBA16Float;
  22157. break;
  22158. case FloatType:
  22159. formatGPU = GPUTextureFormat.RGBA32Float;
  22160. break;
  22161. default:
  22162. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  22163. }
  22164. break;
  22165. case RGBFormat:
  22166. switch ( type ) {
  22167. case UnsignedInt5999Type:
  22168. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  22169. break;
  22170. default:
  22171. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  22172. }
  22173. break;
  22174. case RedFormat:
  22175. switch ( type ) {
  22176. case ByteType:
  22177. formatGPU = GPUTextureFormat.R8Snorm;
  22178. break;
  22179. case ShortType:
  22180. formatGPU = GPUTextureFormat.R16Sint;
  22181. break;
  22182. case UnsignedShortType:
  22183. formatGPU = GPUTextureFormat.R16Uint;
  22184. break;
  22185. case UnsignedIntType:
  22186. formatGPU = GPUTextureFormat.R32Uint;
  22187. break;
  22188. case IntType:
  22189. formatGPU = GPUTextureFormat.R32Sint;
  22190. break;
  22191. case UnsignedByteType:
  22192. formatGPU = GPUTextureFormat.R8Unorm;
  22193. break;
  22194. case HalfFloatType:
  22195. formatGPU = GPUTextureFormat.R16Float;
  22196. break;
  22197. case FloatType:
  22198. formatGPU = GPUTextureFormat.R32Float;
  22199. break;
  22200. default:
  22201. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  22202. }
  22203. break;
  22204. case RGFormat:
  22205. switch ( type ) {
  22206. case ByteType:
  22207. formatGPU = GPUTextureFormat.RG8Snorm;
  22208. break;
  22209. case ShortType:
  22210. formatGPU = GPUTextureFormat.RG16Sint;
  22211. break;
  22212. case UnsignedShortType:
  22213. formatGPU = GPUTextureFormat.RG16Uint;
  22214. break;
  22215. case UnsignedIntType:
  22216. formatGPU = GPUTextureFormat.RG32Uint;
  22217. break;
  22218. case IntType:
  22219. formatGPU = GPUTextureFormat.RG32Sint;
  22220. break;
  22221. case UnsignedByteType:
  22222. formatGPU = GPUTextureFormat.RG8Unorm;
  22223. break;
  22224. case HalfFloatType:
  22225. formatGPU = GPUTextureFormat.RG16Float;
  22226. break;
  22227. case FloatType:
  22228. formatGPU = GPUTextureFormat.RG32Float;
  22229. break;
  22230. default:
  22231. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  22232. }
  22233. break;
  22234. case DepthFormat:
  22235. switch ( type ) {
  22236. case UnsignedShortType:
  22237. formatGPU = GPUTextureFormat.Depth16Unorm;
  22238. break;
  22239. case UnsignedIntType:
  22240. formatGPU = GPUTextureFormat.Depth24Plus;
  22241. break;
  22242. case FloatType:
  22243. formatGPU = GPUTextureFormat.Depth32Float;
  22244. break;
  22245. default:
  22246. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  22247. }
  22248. break;
  22249. case DepthStencilFormat:
  22250. switch ( type ) {
  22251. case UnsignedInt248Type:
  22252. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  22253. break;
  22254. case FloatType:
  22255. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  22256. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  22257. }
  22258. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  22259. break;
  22260. default:
  22261. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  22262. }
  22263. break;
  22264. case RedIntegerFormat:
  22265. switch ( type ) {
  22266. case IntType:
  22267. formatGPU = GPUTextureFormat.R32Sint;
  22268. break;
  22269. case UnsignedIntType:
  22270. formatGPU = GPUTextureFormat.R32Uint;
  22271. break;
  22272. default:
  22273. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  22274. }
  22275. break;
  22276. case RGIntegerFormat:
  22277. switch ( type ) {
  22278. case IntType:
  22279. formatGPU = GPUTextureFormat.RG32Sint;
  22280. break;
  22281. case UnsignedIntType:
  22282. formatGPU = GPUTextureFormat.RG32Uint;
  22283. break;
  22284. default:
  22285. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  22286. }
  22287. break;
  22288. case RGBAIntegerFormat:
  22289. switch ( type ) {
  22290. case IntType:
  22291. formatGPU = GPUTextureFormat.RGBA32Sint;
  22292. break;
  22293. case UnsignedIntType:
  22294. formatGPU = GPUTextureFormat.RGBA32Uint;
  22295. break;
  22296. default:
  22297. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  22298. }
  22299. break;
  22300. default:
  22301. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  22302. }
  22303. }
  22304. return formatGPU;
  22305. }
  22306. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  22307. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  22308. const wgslTypeLib$1 = {
  22309. 'f32': 'float',
  22310. 'i32': 'int',
  22311. 'u32': 'uint',
  22312. 'bool': 'bool',
  22313. 'vec2<f32>': 'vec2',
  22314. 'vec2<i32>': 'ivec2',
  22315. 'vec2<u32>': 'uvec2',
  22316. 'vec2<bool>': 'bvec2',
  22317. 'vec2f': 'vec2',
  22318. 'vec2i': 'ivec2',
  22319. 'vec2u': 'uvec2',
  22320. 'vec2b': 'bvec2',
  22321. 'vec3<f32>': 'vec3',
  22322. 'vec3<i32>': 'ivec3',
  22323. 'vec3<u32>': 'uvec3',
  22324. 'vec3<bool>': 'bvec3',
  22325. 'vec3f': 'vec3',
  22326. 'vec3i': 'ivec3',
  22327. 'vec3u': 'uvec3',
  22328. 'vec3b': 'bvec3',
  22329. 'vec4<f32>': 'vec4',
  22330. 'vec4<i32>': 'ivec4',
  22331. 'vec4<u32>': 'uvec4',
  22332. 'vec4<bool>': 'bvec4',
  22333. 'vec4f': 'vec4',
  22334. 'vec4i': 'ivec4',
  22335. 'vec4u': 'uvec4',
  22336. 'vec4b': 'bvec4',
  22337. 'mat2x2<f32>': 'mat2',
  22338. 'mat2x2f': 'mat2',
  22339. 'mat3x3<f32>': 'mat3',
  22340. 'mat3x3f': 'mat3',
  22341. 'mat4x4<f32>': 'mat4',
  22342. 'mat4x4f': 'mat4',
  22343. 'sampler': 'sampler',
  22344. 'texture_1d': 'texture',
  22345. 'texture_2d': 'texture',
  22346. 'texture_2d_array': 'texture',
  22347. 'texture_multisampled_2d': 'cubeTexture',
  22348. 'texture_depth_2d': 'depthTexture',
  22349. 'texture_3d': 'texture3D',
  22350. 'texture_cube': 'cubeTexture',
  22351. 'texture_cube_array': 'cubeTexture',
  22352. 'texture_storage_1d': 'storageTexture',
  22353. 'texture_storage_2d': 'storageTexture',
  22354. 'texture_storage_2d_array': 'storageTexture',
  22355. 'texture_storage_3d': 'storageTexture'
  22356. };
  22357. const parse = ( source ) => {
  22358. source = source.trim();
  22359. const declaration = source.match( declarationRegexp );
  22360. if ( declaration !== null && declaration.length === 4 ) {
  22361. const inputsCode = declaration[ 2 ];
  22362. const propsMatches = [];
  22363. let match = null;
  22364. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  22365. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  22366. }
  22367. // Process matches to correctly pair names and types
  22368. const inputs = [];
  22369. for ( let i = 0; i < propsMatches.length; i ++ ) {
  22370. const { name, type } = propsMatches[ i ];
  22371. let resolvedType = type;
  22372. if ( resolvedType.startsWith( 'ptr' ) ) {
  22373. resolvedType = 'pointer';
  22374. } else {
  22375. if ( resolvedType.startsWith( 'texture' ) ) {
  22376. resolvedType = type.split( '<' )[ 0 ];
  22377. }
  22378. resolvedType = wgslTypeLib$1[ resolvedType ];
  22379. }
  22380. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  22381. }
  22382. const blockCode = source.substring( declaration[ 0 ].length );
  22383. const outputType = declaration[ 3 ] || 'void';
  22384. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  22385. const type = wgslTypeLib$1[ outputType ] || outputType;
  22386. return {
  22387. type,
  22388. inputs,
  22389. name,
  22390. inputsCode,
  22391. blockCode,
  22392. outputType
  22393. };
  22394. } else {
  22395. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  22396. }
  22397. };
  22398. class WGSLNodeFunction extends NodeFunction {
  22399. constructor( source ) {
  22400. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  22401. super( type, inputs, name );
  22402. this.inputsCode = inputsCode;
  22403. this.blockCode = blockCode;
  22404. this.outputType = outputType;
  22405. }
  22406. getCode( name = this.name ) {
  22407. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  22408. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  22409. }
  22410. }
  22411. class WGSLNodeParser extends NodeParser {
  22412. parseFunction( source ) {
  22413. return new WGSLNodeFunction( source );
  22414. }
  22415. }
  22416. // GPUShaderStage is not defined in browsers not supporting WebGPU
  22417. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  22418. const accessNames = {
  22419. [ NodeAccess.READ_ONLY ]: 'read',
  22420. [ NodeAccess.WRITE_ONLY ]: 'write',
  22421. [ NodeAccess.READ_WRITE ]: 'read_write'
  22422. };
  22423. const wrapNames = {
  22424. [ RepeatWrapping ]: 'repeat',
  22425. [ ClampToEdgeWrapping ]: 'clamp',
  22426. [ MirroredRepeatWrapping ]: 'mirror'
  22427. };
  22428. const gpuShaderStageLib = {
  22429. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  22430. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  22431. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  22432. };
  22433. const supports = {
  22434. instance: true,
  22435. swizzleAssign: false,
  22436. storageBuffer: true
  22437. };
  22438. const wgslFnOpLib = {
  22439. '^^': 'tsl_xor'
  22440. };
  22441. const wgslTypeLib = {
  22442. float: 'f32',
  22443. int: 'i32',
  22444. uint: 'u32',
  22445. bool: 'bool',
  22446. color: 'vec3<f32>',
  22447. vec2: 'vec2<f32>',
  22448. ivec2: 'vec2<i32>',
  22449. uvec2: 'vec2<u32>',
  22450. bvec2: 'vec2<bool>',
  22451. vec3: 'vec3<f32>',
  22452. ivec3: 'vec3<i32>',
  22453. uvec3: 'vec3<u32>',
  22454. bvec3: 'vec3<bool>',
  22455. vec4: 'vec4<f32>',
  22456. ivec4: 'vec4<i32>',
  22457. uvec4: 'vec4<u32>',
  22458. bvec4: 'vec4<bool>',
  22459. mat2: 'mat2x2<f32>',
  22460. mat3: 'mat3x3<f32>',
  22461. mat4: 'mat4x4<f32>'
  22462. };
  22463. const wgslCodeCache = {};
  22464. const wgslPolyfill = {
  22465. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  22466. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  22467. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  22468. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  22469. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  22470. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  22471. 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 ); }' ),
  22472. 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 ); }' ),
  22473. 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 ); }' ),
  22474. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  22475. 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 ); }' ),
  22476. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  22477. biquadraticTexture: new CodeNode( /* wgsl */`
  22478. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  22479. let res = vec2f( iRes );
  22480. let uvScaled = coord * res;
  22481. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  22482. // https://www.shadertoy.com/view/WtyXRy
  22483. let uv = uvWrapping - 0.5;
  22484. let iuv = floor( uv );
  22485. let f = fract( uv );
  22486. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  22487. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  22488. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  22489. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  22490. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  22491. }
  22492. ` )
  22493. };
  22494. const wgslMethods = {
  22495. dFdx: 'dpdx',
  22496. dFdy: '- dpdy',
  22497. mod_float: 'tsl_mod_float',
  22498. mod_vec2: 'tsl_mod_vec2',
  22499. mod_vec3: 'tsl_mod_vec3',
  22500. mod_vec4: 'tsl_mod_vec4',
  22501. equals_bool: 'tsl_equals_bool',
  22502. equals_bvec2: 'tsl_equals_bvec2',
  22503. equals_bvec3: 'tsl_equals_bvec3',
  22504. equals_bvec4: 'tsl_equals_bvec4',
  22505. inversesqrt: 'inverseSqrt',
  22506. bitcast: 'bitcast<f32>'
  22507. };
  22508. // WebGPU issue: does not support pow() with negative base on Windows
  22509. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  22510. 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 ); }' );
  22511. 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 ] );
  22512. 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 ] );
  22513. 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 ] );
  22514. wgslMethods.pow_float = 'tsl_pow_float';
  22515. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  22516. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  22517. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  22518. }
  22519. //
  22520. let diagnostics = '';
  22521. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  22522. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  22523. }
  22524. //
  22525. class WGSLNodeBuilder extends NodeBuilder {
  22526. constructor( object, renderer ) {
  22527. super( object, renderer, new WGSLNodeParser() );
  22528. this.uniformGroups = {};
  22529. this.builtins = {};
  22530. this.directives = {};
  22531. this.scopedArrays = new Map();
  22532. }
  22533. needsToWorkingColorSpace( texture ) {
  22534. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  22535. }
  22536. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  22537. if ( shaderStage === 'fragment' ) {
  22538. if ( depthSnippet ) {
  22539. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  22540. } else {
  22541. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  22542. }
  22543. } else if ( this.isFilteredTexture( texture ) ) {
  22544. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  22545. } else {
  22546. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0' );
  22547. }
  22548. }
  22549. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  22550. if ( shaderStage === 'fragment' ) {
  22551. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  22552. } else {
  22553. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  22554. }
  22555. }
  22556. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  22557. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false ) {
  22558. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  22559. } else if ( this.isFilteredTexture( texture ) ) {
  22560. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  22561. } else {
  22562. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  22563. }
  22564. }
  22565. generateWrapFunction( texture ) {
  22566. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }T`;
  22567. let nodeCode = wgslCodeCache[ functionName ];
  22568. if ( nodeCode === undefined ) {
  22569. const includes = [];
  22570. let code = `fn ${ functionName }( coord : vec2f ) -> vec2f {\n\n\treturn vec2f(\n`;
  22571. const addWrapSnippet = ( wrap, axis ) => {
  22572. if ( wrap === RepeatWrapping ) {
  22573. includes.push( wgslPolyfill.repeatWrapping_float );
  22574. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  22575. } else if ( wrap === ClampToEdgeWrapping ) {
  22576. includes.push( wgslPolyfill.clampWrapping_float );
  22577. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  22578. } else if ( wrap === MirroredRepeatWrapping ) {
  22579. includes.push( wgslPolyfill.mirrorWrapping_float );
  22580. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  22581. } else {
  22582. code += `\t\tcoord.${ axis }`;
  22583. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  22584. }
  22585. };
  22586. addWrapSnippet( texture.wrapS, 'x' );
  22587. code += ',\n';
  22588. addWrapSnippet( texture.wrapT, 'y' );
  22589. code += '\n\t);\n\n}\n';
  22590. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  22591. }
  22592. nodeCode.build( this );
  22593. return functionName;
  22594. }
  22595. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  22596. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  22597. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  22598. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  22599. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  22600. let textureDimensionsParams;
  22601. if ( texture.isMultisampleRenderTargetTexture === true ) {
  22602. textureDimensionsParams = textureProperty;
  22603. } else {
  22604. textureDimensionsParams = `${ textureProperty }, u32( ${ levelSnippet } )`;
  22605. }
  22606. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, 'uvec2' ) );
  22607. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  22608. }
  22609. return textureDimensionNode.build( this );
  22610. }
  22611. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  22612. this._include( 'biquadraticTexture' );
  22613. const wrapFunction = this.generateWrapFunction( texture );
  22614. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  22615. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  22616. }
  22617. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  22618. const wrapFunction = this.generateWrapFunction( texture );
  22619. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  22620. const coordSnippet = `vec2u( ${ wrapFunction }( ${ uvSnippet } ) * vec2f( ${ textureDimension } ) )`;
  22621. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  22622. }
  22623. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  22624. if ( depthSnippet ) {
  22625. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  22626. } else {
  22627. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  22628. }
  22629. }
  22630. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  22631. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  22632. }
  22633. isSampleCompare( texture ) {
  22634. return texture.isDepthTexture === true && texture.compareFunction !== null;
  22635. }
  22636. isUnfilterable( texture ) {
  22637. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  22638. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  22639. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  22640. texture.isMultisampleRenderTargetTexture === true;
  22641. }
  22642. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  22643. let snippet = null;
  22644. if ( texture.isVideoTexture === true ) {
  22645. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  22646. } else if ( this.isUnfilterable( texture ) ) {
  22647. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  22648. } else {
  22649. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  22650. }
  22651. return snippet;
  22652. }
  22653. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  22654. if ( shaderStage === 'fragment' ) {
  22655. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  22656. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  22657. } else {
  22658. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  22659. }
  22660. }
  22661. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  22662. if ( shaderStage === 'fragment' ) {
  22663. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  22664. } else {
  22665. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  22666. }
  22667. }
  22668. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  22669. let snippet = null;
  22670. if ( texture.isVideoTexture === true ) {
  22671. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  22672. } else {
  22673. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  22674. }
  22675. return snippet;
  22676. }
  22677. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  22678. if ( shaderStage === 'fragment' ) {
  22679. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  22680. } else {
  22681. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  22682. }
  22683. }
  22684. getPropertyName( node, shaderStage = this.shaderStage ) {
  22685. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  22686. if ( shaderStage === 'vertex' ) {
  22687. return `varyings.${ node.name }`;
  22688. }
  22689. } else if ( node.isNodeUniform === true ) {
  22690. const name = node.name;
  22691. const type = node.type;
  22692. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  22693. return name;
  22694. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  22695. return `NodeBuffer_${ node.id }.${name}`;
  22696. } else {
  22697. return node.groupNode.name + '.' + name;
  22698. }
  22699. }
  22700. return super.getPropertyName( node );
  22701. }
  22702. getOutputStructName() {
  22703. return 'output';
  22704. }
  22705. _getUniformGroupCount( shaderStage ) {
  22706. return Object.keys( this.uniforms[ shaderStage ] ).length;
  22707. }
  22708. getFunctionOperator( op ) {
  22709. const fnOp = wgslFnOpLib[ op ];
  22710. if ( fnOp !== undefined ) {
  22711. this._include( fnOp );
  22712. return fnOp;
  22713. }
  22714. return null;
  22715. }
  22716. getNodeAccess( node, shaderStage ) {
  22717. if ( shaderStage !== 'compute' )
  22718. return NodeAccess.READ_ONLY;
  22719. return node.access;
  22720. }
  22721. getStorageAccess( node, shaderStage ) {
  22722. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  22723. }
  22724. getUniformFromNode( node, type, shaderStage, name = null ) {
  22725. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  22726. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  22727. if ( nodeData.uniformGPU === undefined ) {
  22728. let uniformGPU;
  22729. const group = node.groupNode;
  22730. const groupName = group.name;
  22731. const bindings = this.getBindGroupArray( groupName, shaderStage );
  22732. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  22733. let texture = null;
  22734. const access = this.getNodeAccess( node, shaderStage );
  22735. if ( type === 'texture' || type === 'storageTexture' ) {
  22736. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  22737. } else if ( type === 'cubeTexture' ) {
  22738. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  22739. } else if ( type === 'texture3D' ) {
  22740. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  22741. }
  22742. texture.store = node.isStorageTextureNode === true;
  22743. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  22744. if ( shaderStage === 'fragment' && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  22745. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  22746. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  22747. bindings.push( sampler, texture );
  22748. uniformGPU = [ sampler, texture ];
  22749. } else {
  22750. bindings.push( texture );
  22751. uniformGPU = [ texture ];
  22752. }
  22753. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  22754. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  22755. const buffer = new bufferClass( node, group );
  22756. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  22757. bindings.push( buffer );
  22758. uniformGPU = buffer;
  22759. } else {
  22760. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  22761. let uniformsGroup = uniformsStage[ groupName ];
  22762. if ( uniformsGroup === undefined ) {
  22763. uniformsGroup = new NodeUniformsGroup( groupName, group );
  22764. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  22765. uniformsStage[ groupName ] = uniformsGroup;
  22766. bindings.push( uniformsGroup );
  22767. }
  22768. uniformGPU = this.getNodeUniform( uniformNode, type );
  22769. uniformsGroup.addUniform( uniformGPU );
  22770. }
  22771. nodeData.uniformGPU = uniformGPU;
  22772. }
  22773. return uniformNode;
  22774. }
  22775. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  22776. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  22777. if ( map.has( name ) === false ) {
  22778. map.set( name, {
  22779. name,
  22780. property,
  22781. type
  22782. } );
  22783. }
  22784. return property;
  22785. }
  22786. hasBuiltin( name, shaderStage = this.shaderStage ) {
  22787. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  22788. }
  22789. getVertexIndex() {
  22790. if ( this.shaderStage === 'vertex' ) {
  22791. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  22792. }
  22793. return 'vertexIndex';
  22794. }
  22795. buildFunctionCode( shaderNode ) {
  22796. const layout = shaderNode.layout;
  22797. const flowData = this.flowShaderNode( shaderNode );
  22798. const parameters = [];
  22799. for ( const input of layout.inputs ) {
  22800. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  22801. }
  22802. //
  22803. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  22804. ${ flowData.vars }
  22805. ${ flowData.code }
  22806. `;
  22807. if ( flowData.result ) {
  22808. code += `\treturn ${ flowData.result };\n`;
  22809. }
  22810. code += '\n}\n';
  22811. //
  22812. return code;
  22813. }
  22814. getInstanceIndex() {
  22815. if ( this.shaderStage === 'vertex' ) {
  22816. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  22817. }
  22818. return 'instanceIndex';
  22819. }
  22820. getInvocationLocalIndex() {
  22821. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  22822. }
  22823. getSubgroupSize() {
  22824. this.enableSubGroups();
  22825. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  22826. }
  22827. getInvocationSubgroupIndex() {
  22828. this.enableSubGroups();
  22829. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  22830. }
  22831. getSubgroupIndex() {
  22832. this.enableSubGroups();
  22833. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  22834. }
  22835. getDrawIndex() {
  22836. return null;
  22837. }
  22838. getFrontFacing() {
  22839. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  22840. }
  22841. getFragCoord() {
  22842. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  22843. }
  22844. getFragDepth() {
  22845. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  22846. }
  22847. getClipDistance() {
  22848. return 'varyings.hw_clip_distances';
  22849. }
  22850. isFlipY() {
  22851. return false;
  22852. }
  22853. enableDirective( name, shaderStage = this.shaderStage ) {
  22854. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  22855. stage.add( name );
  22856. }
  22857. getDirectives( shaderStage ) {
  22858. const snippets = [];
  22859. const directives = this.directives[ shaderStage ];
  22860. if ( directives !== undefined ) {
  22861. for ( const directive of directives ) {
  22862. snippets.push( `enable ${directive};` );
  22863. }
  22864. }
  22865. return snippets.join( '\n' );
  22866. }
  22867. enableSubGroups() {
  22868. this.enableDirective( 'subgroups' );
  22869. }
  22870. enableSubgroupsF16() {
  22871. this.enableDirective( 'subgroups-f16' );
  22872. }
  22873. enableClipDistances() {
  22874. this.enableDirective( 'clip_distances' );
  22875. }
  22876. enableShaderF16() {
  22877. this.enableDirective( 'f16' );
  22878. }
  22879. enableDualSourceBlending() {
  22880. this.enableDirective( 'dual_source_blending' );
  22881. }
  22882. enableHardwareClipping( planeCount ) {
  22883. this.enableClipDistances();
  22884. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  22885. }
  22886. getBuiltins( shaderStage ) {
  22887. const snippets = [];
  22888. const builtins = this.builtins[ shaderStage ];
  22889. if ( builtins !== undefined ) {
  22890. for ( const { name, property, type } of builtins.values() ) {
  22891. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  22892. }
  22893. }
  22894. return snippets.join( ',\n\t' );
  22895. }
  22896. getScopedArray( name, scope, bufferType, bufferCount ) {
  22897. if ( this.scopedArrays.has( name ) === false ) {
  22898. this.scopedArrays.set( name, {
  22899. name,
  22900. scope,
  22901. bufferType,
  22902. bufferCount
  22903. } );
  22904. }
  22905. return name;
  22906. }
  22907. getScopedArrays( shaderStage ) {
  22908. if ( shaderStage !== 'compute' ) {
  22909. return;
  22910. }
  22911. const snippets = [];
  22912. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  22913. const type = this.getType( bufferType );
  22914. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  22915. }
  22916. return snippets.join( '\n' );
  22917. }
  22918. getAttributes( shaderStage ) {
  22919. const snippets = [];
  22920. if ( shaderStage === 'compute' ) {
  22921. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  22922. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  22923. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  22924. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  22925. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  22926. this.enableDirective( 'subgroups', shaderStage );
  22927. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  22928. }
  22929. }
  22930. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  22931. const builtins = this.getBuiltins( 'attribute' );
  22932. if ( builtins ) snippets.push( builtins );
  22933. const attributes = this.getAttributesArray();
  22934. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  22935. const attribute = attributes[ index ];
  22936. const name = attribute.name;
  22937. const type = this.getType( attribute.type );
  22938. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  22939. }
  22940. }
  22941. return snippets.join( ',\n\t' );
  22942. }
  22943. getStructMembers( struct ) {
  22944. const snippets = [];
  22945. const members = struct.getMemberTypes();
  22946. for ( let i = 0; i < members.length; i ++ ) {
  22947. const member = members[ i ];
  22948. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  22949. }
  22950. const builtins = this.getBuiltins( 'output' );
  22951. if ( builtins ) snippets.push( '\t' + builtins );
  22952. return snippets.join( ',\n' );
  22953. }
  22954. getStructs( shaderStage ) {
  22955. const snippets = [];
  22956. const structs = this.structs[ shaderStage ];
  22957. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  22958. const struct = structs[ index ];
  22959. const name = struct.name;
  22960. let snippet = `\struct ${ name } {\n`;
  22961. snippet += this.getStructMembers( struct );
  22962. snippet += '\n}';
  22963. snippets.push( snippet );
  22964. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  22965. }
  22966. return snippets.join( '\n\n' );
  22967. }
  22968. getVar( type, name ) {
  22969. return `var ${ name } : ${ this.getType( type ) }`;
  22970. }
  22971. getVars( shaderStage ) {
  22972. const snippets = [];
  22973. const vars = this.vars[ shaderStage ];
  22974. if ( vars !== undefined ) {
  22975. for ( const variable of vars ) {
  22976. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  22977. }
  22978. }
  22979. return `\n${ snippets.join( '\n' ) }\n`;
  22980. }
  22981. getVaryings( shaderStage ) {
  22982. const snippets = [];
  22983. if ( shaderStage === 'vertex' ) {
  22984. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  22985. }
  22986. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  22987. const varyings = this.varyings;
  22988. const vars = this.vars[ shaderStage ];
  22989. for ( let index = 0; index < varyings.length; index ++ ) {
  22990. const varying = varyings[ index ];
  22991. if ( varying.needsInterpolation ) {
  22992. let attributesSnippet = `@location( ${index} )`;
  22993. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  22994. attributesSnippet += ' @interpolate( flat )';
  22995. }
  22996. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  22997. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  22998. vars.push( varying );
  22999. }
  23000. }
  23001. }
  23002. const builtins = this.getBuiltins( shaderStage );
  23003. if ( builtins ) snippets.push( builtins );
  23004. const code = snippets.join( ',\n\t' );
  23005. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  23006. }
  23007. getUniforms( shaderStage ) {
  23008. const uniforms = this.uniforms[ shaderStage ];
  23009. const bindingSnippets = [];
  23010. const bufferSnippets = [];
  23011. const structSnippets = [];
  23012. const uniformGroups = {};
  23013. for ( const uniform of uniforms ) {
  23014. const groupName = uniform.groupNode.name;
  23015. const uniformIndexes = this.bindingsIndexes[ groupName ];
  23016. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  23017. const texture = uniform.node.value;
  23018. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  23019. if ( this.isSampleCompare( texture ) ) {
  23020. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  23021. } else {
  23022. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  23023. }
  23024. }
  23025. let textureType;
  23026. let multisampled = '';
  23027. if ( texture.isMultisampleRenderTargetTexture === true ) {
  23028. multisampled = '_multisampled';
  23029. }
  23030. if ( texture.isCubeTexture === true ) {
  23031. textureType = 'texture_cube<f32>';
  23032. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  23033. textureType = 'texture_2d_array<f32>';
  23034. } else if ( texture.isDepthTexture === true ) {
  23035. textureType = `texture_depth${multisampled}_2d`;
  23036. } else if ( texture.isVideoTexture === true ) {
  23037. textureType = 'texture_external';
  23038. } else if ( texture.isData3DTexture === true ) {
  23039. textureType = 'texture_3d<f32>';
  23040. } else if ( uniform.node.isStorageTextureNode === true ) {
  23041. const format = getFormat( texture );
  23042. const access = this.getStorageAccess( uniform.node, shaderStage );
  23043. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  23044. } else {
  23045. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  23046. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  23047. }
  23048. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  23049. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  23050. const bufferNode = uniform.node;
  23051. const bufferType = this.getType( bufferNode.bufferType );
  23052. const bufferCount = bufferNode.bufferCount;
  23053. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  23054. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${bufferType}>` : `${bufferType}`;
  23055. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >\n`;
  23056. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  23057. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  23058. } else {
  23059. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  23060. const groupName = uniform.groupNode.name;
  23061. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  23062. index: uniformIndexes.binding ++,
  23063. id: uniformIndexes.group,
  23064. snippets: []
  23065. } );
  23066. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  23067. }
  23068. }
  23069. for ( const name in uniformGroups ) {
  23070. const group = uniformGroups[ name ];
  23071. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  23072. }
  23073. let code = bindingSnippets.join( '\n' );
  23074. code += bufferSnippets.join( '\n' );
  23075. code += structSnippets.join( '\n' );
  23076. return code;
  23077. }
  23078. buildCode() {
  23079. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  23080. this.sortBindingGroups();
  23081. for ( const shaderStage in shadersData ) {
  23082. const stageData = shadersData[ shaderStage ];
  23083. stageData.uniforms = this.getUniforms( shaderStage );
  23084. stageData.attributes = this.getAttributes( shaderStage );
  23085. stageData.varyings = this.getVaryings( shaderStage );
  23086. stageData.structs = this.getStructs( shaderStage );
  23087. stageData.vars = this.getVars( shaderStage );
  23088. stageData.codes = this.getCodes( shaderStage );
  23089. stageData.directives = this.getDirectives( shaderStage );
  23090. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  23091. //
  23092. let flow = '// code\n\n';
  23093. flow += this.flowCode[ shaderStage ];
  23094. const flowNodes = this.flowNodes[ shaderStage ];
  23095. const mainNode = flowNodes[ flowNodes.length - 1 ];
  23096. const outputNode = mainNode.outputNode;
  23097. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  23098. for ( const node of flowNodes ) {
  23099. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  23100. const slotName = node.name;
  23101. if ( slotName ) {
  23102. if ( flow.length > 0 ) flow += '\n';
  23103. flow += `\t// flow -> ${ slotName }\n\t`;
  23104. }
  23105. flow += `${ flowSlotData.code }\n\t`;
  23106. if ( node === mainNode && shaderStage !== 'compute' ) {
  23107. flow += '// result\n\n\t';
  23108. if ( shaderStage === 'vertex' ) {
  23109. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  23110. } else if ( shaderStage === 'fragment' ) {
  23111. if ( isOutputStruct ) {
  23112. stageData.returnType = outputNode.nodeType;
  23113. flow += `return ${ flowSlotData.result };`;
  23114. } else {
  23115. let structSnippet = '\t@location(0) color: vec4<f32>';
  23116. const builtins = this.getBuiltins( 'output' );
  23117. if ( builtins ) structSnippet += ',\n\t' + builtins;
  23118. stageData.returnType = 'OutputStruct';
  23119. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  23120. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  23121. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  23122. }
  23123. }
  23124. }
  23125. }
  23126. stageData.flow = flow;
  23127. }
  23128. if ( this.material !== null ) {
  23129. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  23130. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  23131. } else {
  23132. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  23133. }
  23134. }
  23135. getMethod( method, output = null ) {
  23136. let wgslMethod;
  23137. if ( output !== null ) {
  23138. wgslMethod = this._getWGSLMethod( method + '_' + output );
  23139. }
  23140. if ( wgslMethod === undefined ) {
  23141. wgslMethod = this._getWGSLMethod( method );
  23142. }
  23143. return wgslMethod || method;
  23144. }
  23145. getType( type ) {
  23146. return wgslTypeLib[ type ] || type;
  23147. }
  23148. isAvailable( name ) {
  23149. let result = supports[ name ];
  23150. if ( result === undefined ) {
  23151. if ( name === 'float32Filterable' ) {
  23152. result = this.renderer.hasFeature( 'float32-filterable' );
  23153. } else if ( name === 'clipDistance' ) {
  23154. result = this.renderer.hasFeature( 'clip-distances' );
  23155. }
  23156. supports[ name ] = result;
  23157. }
  23158. return result;
  23159. }
  23160. _getWGSLMethod( method ) {
  23161. if ( wgslPolyfill[ method ] !== undefined ) {
  23162. this._include( method );
  23163. }
  23164. return wgslMethods[ method ];
  23165. }
  23166. _include( name ) {
  23167. const codeNode = wgslPolyfill[ name ];
  23168. codeNode.build( this );
  23169. if ( this.currentFunctionNode !== null ) {
  23170. this.currentFunctionNode.includes.push( codeNode );
  23171. }
  23172. return codeNode;
  23173. }
  23174. _getWGSLVertexCode( shaderData ) {
  23175. return `${ this.getSignature() }
  23176. // directives
  23177. ${shaderData.directives}
  23178. // uniforms
  23179. ${shaderData.uniforms}
  23180. // varyings
  23181. ${shaderData.varyings}
  23182. var<private> varyings : VaryingsStruct;
  23183. // codes
  23184. ${shaderData.codes}
  23185. @vertex
  23186. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  23187. // vars
  23188. ${shaderData.vars}
  23189. // flow
  23190. ${shaderData.flow}
  23191. return varyings;
  23192. }
  23193. `;
  23194. }
  23195. _getWGSLFragmentCode( shaderData ) {
  23196. return `${ this.getSignature() }
  23197. // global
  23198. ${ diagnostics }
  23199. // uniforms
  23200. ${shaderData.uniforms}
  23201. // structs
  23202. ${shaderData.structs}
  23203. // codes
  23204. ${shaderData.codes}
  23205. @fragment
  23206. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  23207. // vars
  23208. ${shaderData.vars}
  23209. // flow
  23210. ${shaderData.flow}
  23211. }
  23212. `;
  23213. }
  23214. _getWGSLComputeCode( shaderData, workgroupSize ) {
  23215. return `${ this.getSignature() }
  23216. // directives
  23217. ${shaderData.directives}
  23218. // system
  23219. var<private> instanceIndex : u32;
  23220. // locals
  23221. ${shaderData.scopedArrays}
  23222. // uniforms
  23223. ${shaderData.uniforms}
  23224. // codes
  23225. ${shaderData.codes}
  23226. @compute @workgroup_size( ${workgroupSize} )
  23227. fn main( ${shaderData.attributes} ) {
  23228. // system
  23229. instanceIndex = id.x + id.y * numWorkgroups.x * u32(${workgroupSize}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  23230. // vars
  23231. ${shaderData.vars}
  23232. // flow
  23233. ${shaderData.flow}
  23234. }
  23235. `;
  23236. }
  23237. _getWGSLStruct( name, vars ) {
  23238. return `
  23239. struct ${name} {
  23240. ${vars}
  23241. };`;
  23242. }
  23243. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  23244. const structName = name + 'Struct';
  23245. const structSnippet = this._getWGSLStruct( structName, vars );
  23246. return `${structSnippet}
  23247. @binding( ${binding} ) @group( ${group} )
  23248. var<${access}> ${name} : ${structName};`;
  23249. }
  23250. }
  23251. class WebGPUUtils {
  23252. constructor( backend ) {
  23253. this.backend = backend;
  23254. }
  23255. getCurrentDepthStencilFormat( renderContext ) {
  23256. let format;
  23257. if ( renderContext.depthTexture !== null ) {
  23258. format = this.getTextureFormatGPU( renderContext.depthTexture );
  23259. } else if ( renderContext.depth && renderContext.stencil ) {
  23260. format = GPUTextureFormat.Depth24PlusStencil8;
  23261. } else if ( renderContext.depth ) {
  23262. format = GPUTextureFormat.Depth24Plus;
  23263. }
  23264. return format;
  23265. }
  23266. getTextureFormatGPU( texture ) {
  23267. return this.backend.get( texture ).format;
  23268. }
  23269. getCurrentColorFormat( renderContext ) {
  23270. let format;
  23271. if ( renderContext.textures !== null ) {
  23272. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  23273. } else {
  23274. format = this.getPreferredCanvasFormat(); // default context format
  23275. }
  23276. return format;
  23277. }
  23278. getCurrentColorSpace( renderContext ) {
  23279. if ( renderContext.textures !== null ) {
  23280. return renderContext.textures[ 0 ].colorSpace;
  23281. }
  23282. return this.backend.renderer.outputColorSpace;
  23283. }
  23284. getPrimitiveTopology( object, material ) {
  23285. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  23286. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  23287. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  23288. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  23289. }
  23290. getSampleCount( sampleCount ) {
  23291. let count = 1;
  23292. if ( sampleCount > 1 ) {
  23293. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  23294. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  23295. if ( count === 2 ) {
  23296. count = 4;
  23297. }
  23298. }
  23299. return count;
  23300. }
  23301. getSampleCountRenderContext( renderContext ) {
  23302. if ( renderContext.textures !== null ) {
  23303. return this.getSampleCount( renderContext.sampleCount );
  23304. }
  23305. return this.getSampleCount( this.backend.renderer.samples );
  23306. }
  23307. getPreferredCanvasFormat() {
  23308. // TODO: Remove this check when Quest 34.5 is out
  23309. // https://github.com/mrdoob/three.js/pull/29221/files#r1731833949
  23310. if ( navigator.userAgent.includes( 'Quest' ) ) {
  23311. return GPUTextureFormat.BGRA8Unorm;
  23312. } else {
  23313. return navigator.gpu.getPreferredCanvasFormat();
  23314. }
  23315. }
  23316. }
  23317. const typedArraysToVertexFormatPrefix = new Map( [
  23318. [ Int8Array, [ 'sint8', 'snorm8' ]],
  23319. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  23320. [ Int16Array, [ 'sint16', 'snorm16' ]],
  23321. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  23322. [ Int32Array, [ 'sint32', 'snorm32' ]],
  23323. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  23324. [ Float32Array, [ 'float32', ]],
  23325. ] );
  23326. const typedAttributeToVertexFormatPrefix = new Map( [
  23327. [ Float16BufferAttribute, [ 'float16', ]],
  23328. ] );
  23329. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  23330. [ Int32Array, 'sint32' ],
  23331. [ Int16Array, 'sint32' ], // patch for INT16
  23332. [ Uint32Array, 'uint32' ],
  23333. [ Uint16Array, 'uint32' ], // patch for UINT16
  23334. [ Float32Array, 'float32' ]
  23335. ] );
  23336. class WebGPUAttributeUtils {
  23337. constructor( backend ) {
  23338. this.backend = backend;
  23339. }
  23340. createAttribute( attribute, usage ) {
  23341. const bufferAttribute = this._getBufferAttribute( attribute );
  23342. const backend = this.backend;
  23343. const bufferData = backend.get( bufferAttribute );
  23344. let buffer = bufferData.buffer;
  23345. if ( buffer === undefined ) {
  23346. const device = backend.device;
  23347. let array = bufferAttribute.array;
  23348. // patch for INT16 and UINT16
  23349. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  23350. const tempArray = new Uint32Array( array.length );
  23351. for ( let i = 0; i < array.length; i ++ ) {
  23352. tempArray[ i ] = array[ i ];
  23353. }
  23354. array = tempArray;
  23355. }
  23356. bufferAttribute.array = array;
  23357. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  23358. array = new array.constructor( bufferAttribute.count * 4 );
  23359. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  23360. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  23361. }
  23362. // Update BufferAttribute
  23363. bufferAttribute.itemSize = 4;
  23364. bufferAttribute.array = array;
  23365. }
  23366. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  23367. buffer = device.createBuffer( {
  23368. label: bufferAttribute.name,
  23369. size: size,
  23370. usage: usage,
  23371. mappedAtCreation: true
  23372. } );
  23373. new array.constructor( buffer.getMappedRange() ).set( array );
  23374. buffer.unmap();
  23375. bufferData.buffer = buffer;
  23376. }
  23377. }
  23378. updateAttribute( attribute ) {
  23379. const bufferAttribute = this._getBufferAttribute( attribute );
  23380. const backend = this.backend;
  23381. const device = backend.device;
  23382. const buffer = backend.get( bufferAttribute ).buffer;
  23383. const array = bufferAttribute.array;
  23384. const isTypedArray = this._isTypedArray( array );
  23385. const updateRanges = bufferAttribute.updateRanges;
  23386. if ( updateRanges.length === 0 ) {
  23387. // Not using update ranges
  23388. device.queue.writeBuffer(
  23389. buffer,
  23390. 0,
  23391. array,
  23392. 0
  23393. );
  23394. } else {
  23395. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  23396. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  23397. const range = updateRanges[ i ];
  23398. const dataOffset = range.start * byteOffsetFactor;
  23399. const size = range.count * byteOffsetFactor;
  23400. device.queue.writeBuffer(
  23401. buffer,
  23402. 0,
  23403. array,
  23404. dataOffset,
  23405. size
  23406. );
  23407. }
  23408. bufferAttribute.clearUpdateRanges();
  23409. }
  23410. }
  23411. createShaderVertexBuffers( renderObject ) {
  23412. const attributes = renderObject.getAttributes();
  23413. const vertexBuffers = new Map();
  23414. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  23415. const geometryAttribute = attributes[ slot ];
  23416. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  23417. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  23418. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  23419. if ( vertexBufferLayout === undefined ) {
  23420. let arrayStride, stepMode;
  23421. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  23422. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  23423. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  23424. } else {
  23425. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  23426. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  23427. }
  23428. // patch for INT16 and UINT16
  23429. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  23430. arrayStride = 4;
  23431. }
  23432. vertexBufferLayout = {
  23433. arrayStride,
  23434. attributes: [],
  23435. stepMode
  23436. };
  23437. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  23438. }
  23439. const format = this._getVertexFormat( geometryAttribute );
  23440. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  23441. vertexBufferLayout.attributes.push( {
  23442. shaderLocation: slot,
  23443. offset,
  23444. format
  23445. } );
  23446. }
  23447. return Array.from( vertexBuffers.values() );
  23448. }
  23449. destroyAttribute( attribute ) {
  23450. const backend = this.backend;
  23451. const data = backend.get( this._getBufferAttribute( attribute ) );
  23452. data.buffer.destroy();
  23453. backend.delete( attribute );
  23454. }
  23455. async getArrayBufferAsync( attribute ) {
  23456. const backend = this.backend;
  23457. const device = backend.device;
  23458. const data = backend.get( this._getBufferAttribute( attribute ) );
  23459. const bufferGPU = data.buffer;
  23460. const size = bufferGPU.size;
  23461. const readBufferGPU = device.createBuffer( {
  23462. label: attribute.name,
  23463. size,
  23464. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  23465. } );
  23466. const cmdEncoder = device.createCommandEncoder( {} );
  23467. cmdEncoder.copyBufferToBuffer(
  23468. bufferGPU,
  23469. 0,
  23470. readBufferGPU,
  23471. 0,
  23472. size
  23473. );
  23474. readBufferGPU.unmap();
  23475. const gpuCommands = cmdEncoder.finish();
  23476. device.queue.submit( [ gpuCommands ] );
  23477. await readBufferGPU.mapAsync( GPUMapMode.READ );
  23478. const arrayBuffer = readBufferGPU.getMappedRange();
  23479. return arrayBuffer;
  23480. }
  23481. _getVertexFormat( geometryAttribute ) {
  23482. const { itemSize, normalized } = geometryAttribute;
  23483. const ArrayType = geometryAttribute.array.constructor;
  23484. const AttributeType = geometryAttribute.constructor;
  23485. let format;
  23486. if ( itemSize == 1 ) {
  23487. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  23488. } else {
  23489. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  23490. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  23491. if ( prefix ) {
  23492. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  23493. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  23494. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  23495. if ( paddedItemSize % 1 ) {
  23496. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  23497. }
  23498. format = `${prefix}x${paddedItemSize}`;
  23499. }
  23500. }
  23501. if ( ! format ) {
  23502. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  23503. }
  23504. return format;
  23505. }
  23506. _isTypedArray( array ) {
  23507. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  23508. }
  23509. _getBufferAttribute( attribute ) {
  23510. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  23511. return attribute;
  23512. }
  23513. }
  23514. class WebGPUBindingUtils {
  23515. constructor( backend ) {
  23516. this.backend = backend;
  23517. this.bindGroupLayoutCache = new WeakMap();
  23518. }
  23519. createBindingsLayout( bindGroup ) {
  23520. const backend = this.backend;
  23521. const device = backend.device;
  23522. const entries = [];
  23523. let index = 0;
  23524. for ( const binding of bindGroup.bindings ) {
  23525. const bindingGPU = {
  23526. binding: index ++,
  23527. visibility: binding.visibility
  23528. };
  23529. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  23530. const buffer = {}; // GPUBufferBindingLayout
  23531. if ( binding.isStorageBuffer ) {
  23532. if ( binding.visibility & 4 ) {
  23533. // compute
  23534. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  23535. buffer.type = GPUBufferBindingType.Storage;
  23536. } else {
  23537. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  23538. }
  23539. } else {
  23540. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  23541. }
  23542. }
  23543. bindingGPU.buffer = buffer;
  23544. } else if ( binding.isSampler ) {
  23545. const sampler = {}; // GPUSamplerBindingLayout
  23546. if ( binding.texture.isDepthTexture ) {
  23547. if ( binding.texture.compareFunction !== null ) {
  23548. sampler.type = 'comparison';
  23549. }
  23550. }
  23551. bindingGPU.sampler = sampler;
  23552. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  23553. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  23554. } else if ( binding.isSampledTexture && binding.store ) {
  23555. const storageTexture = {}; // GPUStorageTextureBindingLayout
  23556. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  23557. const access = binding.access;
  23558. if ( access === NodeAccess.READ_WRITE ) {
  23559. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  23560. } else if ( access === NodeAccess.WRITE_ONLY ) {
  23561. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  23562. } else {
  23563. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  23564. }
  23565. bindingGPU.storageTexture = storageTexture;
  23566. } else if ( binding.isSampledTexture ) {
  23567. const texture = {}; // GPUTextureBindingLayout
  23568. if ( binding.texture.isMultisampleRenderTargetTexture === true ) {
  23569. texture.multisampled = true;
  23570. }
  23571. if ( binding.texture.isDepthTexture ) {
  23572. texture.sampleType = GPUTextureSampleType.Depth;
  23573. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  23574. const type = binding.texture.type;
  23575. if ( type === IntType ) {
  23576. texture.sampleType = GPUTextureSampleType.SInt;
  23577. } else if ( type === UnsignedIntType ) {
  23578. texture.sampleType = GPUTextureSampleType.UInt;
  23579. } else if ( type === FloatType ) {
  23580. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  23581. texture.sampleType = GPUTextureSampleType.Float;
  23582. } else {
  23583. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  23584. }
  23585. }
  23586. }
  23587. if ( binding.isSampledCubeTexture ) {
  23588. texture.viewDimension = GPUTextureViewDimension.Cube;
  23589. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  23590. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  23591. } else if ( binding.isSampledTexture3D ) {
  23592. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  23593. }
  23594. bindingGPU.texture = texture;
  23595. } else {
  23596. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  23597. }
  23598. entries.push( bindingGPU );
  23599. }
  23600. return device.createBindGroupLayout( { entries } );
  23601. }
  23602. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  23603. const { backend, bindGroupLayoutCache } = this;
  23604. const bindingsData = backend.get( bindGroup );
  23605. // setup (static) binding layout and (dynamic) binding group
  23606. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  23607. if ( bindLayoutGPU === undefined ) {
  23608. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  23609. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  23610. }
  23611. let bindGroupGPU;
  23612. if ( cacheIndex > 0 ) {
  23613. if ( bindingsData.groups === undefined ) {
  23614. bindingsData.groups = [];
  23615. bindingsData.versions = [];
  23616. }
  23617. if ( bindingsData.versions[ cacheIndex ] === version ) {
  23618. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  23619. }
  23620. }
  23621. if ( bindGroupGPU === undefined ) {
  23622. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  23623. if ( cacheIndex > 0 ) {
  23624. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  23625. bindingsData.versions[ cacheIndex ] = version;
  23626. }
  23627. }
  23628. bindingsData.group = bindGroupGPU;
  23629. bindingsData.layout = bindLayoutGPU;
  23630. }
  23631. updateBinding( binding ) {
  23632. const backend = this.backend;
  23633. const device = backend.device;
  23634. const buffer = binding.buffer;
  23635. const bufferGPU = backend.get( binding ).buffer;
  23636. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  23637. }
  23638. createBindGroup( bindGroup, layoutGPU ) {
  23639. const backend = this.backend;
  23640. const device = backend.device;
  23641. let bindingPoint = 0;
  23642. const entriesGPU = [];
  23643. for ( const binding of bindGroup.bindings ) {
  23644. if ( binding.isUniformBuffer ) {
  23645. const bindingData = backend.get( binding );
  23646. if ( bindingData.buffer === undefined ) {
  23647. const byteLength = binding.byteLength;
  23648. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  23649. const bufferGPU = device.createBuffer( {
  23650. label: 'bindingBuffer_' + binding.name,
  23651. size: byteLength,
  23652. usage: usage
  23653. } );
  23654. bindingData.buffer = bufferGPU;
  23655. }
  23656. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  23657. } else if ( binding.isStorageBuffer ) {
  23658. const bindingData = backend.get( binding );
  23659. if ( bindingData.buffer === undefined ) {
  23660. const attribute = binding.attribute;
  23661. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  23662. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  23663. bindingData.buffer = backend.get( attribute ).buffer;
  23664. }
  23665. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  23666. } else if ( binding.isSampler ) {
  23667. const textureGPU = backend.get( binding.texture );
  23668. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  23669. } else if ( binding.isSampledTexture ) {
  23670. const textureData = backend.get( binding.texture );
  23671. let resourceGPU;
  23672. if ( textureData.externalTexture !== undefined ) {
  23673. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  23674. } else {
  23675. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  23676. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  23677. resourceGPU = textureData[ propertyName ];
  23678. if ( resourceGPU === undefined ) {
  23679. const aspectGPU = GPUTextureAspect.All;
  23680. let dimensionViewGPU;
  23681. if ( binding.isSampledCubeTexture ) {
  23682. dimensionViewGPU = GPUTextureViewDimension.Cube;
  23683. } else if ( binding.isSampledTexture3D ) {
  23684. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  23685. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  23686. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  23687. } else {
  23688. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  23689. }
  23690. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  23691. }
  23692. }
  23693. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  23694. }
  23695. bindingPoint ++;
  23696. }
  23697. return device.createBindGroup( {
  23698. label: 'bindGroup_' + bindGroup.name,
  23699. layout: layoutGPU,
  23700. entries: entriesGPU
  23701. } );
  23702. }
  23703. }
  23704. class WebGPUPipelineUtils {
  23705. constructor( backend ) {
  23706. this.backend = backend;
  23707. }
  23708. _getSampleCount( renderObjectContext ) {
  23709. return this.backend.utils.getSampleCountRenderContext( renderObjectContext );
  23710. }
  23711. createRenderPipeline( renderObject, promises ) {
  23712. const { object, material, geometry, pipeline } = renderObject;
  23713. const { vertexProgram, fragmentProgram } = pipeline;
  23714. const backend = this.backend;
  23715. const device = backend.device;
  23716. const utils = backend.utils;
  23717. const pipelineData = backend.get( pipeline );
  23718. // bind group layouts
  23719. const bindGroupLayouts = [];
  23720. for ( const bindGroup of renderObject.getBindings() ) {
  23721. const bindingsData = backend.get( bindGroup );
  23722. bindGroupLayouts.push( bindingsData.layout );
  23723. }
  23724. // vertex buffers
  23725. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  23726. // blending
  23727. let blending;
  23728. if ( material.transparent === true && material.blending !== NoBlending ) {
  23729. blending = this._getBlending( material );
  23730. }
  23731. // stencil
  23732. let stencilFront = {};
  23733. if ( material.stencilWrite === true ) {
  23734. stencilFront = {
  23735. compare: this._getStencilCompare( material ),
  23736. failOp: this._getStencilOperation( material.stencilFail ),
  23737. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  23738. passOp: this._getStencilOperation( material.stencilZPass )
  23739. };
  23740. }
  23741. const colorWriteMask = this._getColorWriteMask( material );
  23742. const targets = [];
  23743. if ( renderObject.context.textures !== null ) {
  23744. const textures = renderObject.context.textures;
  23745. for ( let i = 0; i < textures.length; i ++ ) {
  23746. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  23747. targets.push( {
  23748. format: colorFormat,
  23749. blend: blending,
  23750. writeMask: colorWriteMask
  23751. } );
  23752. }
  23753. } else {
  23754. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  23755. targets.push( {
  23756. format: colorFormat,
  23757. blend: blending,
  23758. writeMask: colorWriteMask
  23759. } );
  23760. }
  23761. const vertexModule = backend.get( vertexProgram ).module;
  23762. const fragmentModule = backend.get( fragmentProgram ).module;
  23763. const primitiveState = this._getPrimitiveState( object, geometry, material );
  23764. const depthCompare = this._getDepthCompare( material );
  23765. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  23766. const sampleCount = this._getSampleCount( renderObject.context );
  23767. const pipelineDescriptor = {
  23768. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  23769. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  23770. fragment: Object.assign( {}, fragmentModule, { targets } ),
  23771. primitive: primitiveState,
  23772. multisample: {
  23773. count: sampleCount,
  23774. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  23775. },
  23776. layout: device.createPipelineLayout( {
  23777. bindGroupLayouts
  23778. } )
  23779. };
  23780. const depthStencil = {};
  23781. const renderDepth = renderObject.context.depth;
  23782. const renderStencil = renderObject.context.stencil;
  23783. if ( renderDepth === true || renderStencil === true ) {
  23784. if ( renderDepth === true ) {
  23785. depthStencil.format = depthStencilFormat;
  23786. depthStencil.depthWriteEnabled = material.depthWrite;
  23787. depthStencil.depthCompare = depthCompare;
  23788. }
  23789. if ( renderStencil === true ) {
  23790. depthStencil.stencilFront = stencilFront;
  23791. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  23792. depthStencil.stencilReadMask = material.stencilFuncMask;
  23793. depthStencil.stencilWriteMask = material.stencilWriteMask;
  23794. }
  23795. pipelineDescriptor.depthStencil = depthStencil;
  23796. }
  23797. if ( promises === null ) {
  23798. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  23799. } else {
  23800. const p = new Promise( ( resolve /*, reject*/ ) => {
  23801. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  23802. pipelineData.pipeline = pipeline;
  23803. resolve();
  23804. } );
  23805. } );
  23806. promises.push( p );
  23807. }
  23808. }
  23809. createBundleEncoder( renderContext ) {
  23810. const backend = this.backend;
  23811. const { utils, device } = backend;
  23812. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  23813. const colorFormat = utils.getCurrentColorFormat( renderContext );
  23814. const sampleCount = this._getSampleCount( renderContext );
  23815. const descriptor = {
  23816. label: 'renderBundleEncoder',
  23817. colorFormats: [ colorFormat ],
  23818. depthStencilFormat,
  23819. sampleCount
  23820. };
  23821. return device.createRenderBundleEncoder( descriptor );
  23822. }
  23823. createComputePipeline( pipeline, bindings ) {
  23824. const backend = this.backend;
  23825. const device = backend.device;
  23826. const computeProgram = backend.get( pipeline.computeProgram ).module;
  23827. const pipelineGPU = backend.get( pipeline );
  23828. // bind group layouts
  23829. const bindGroupLayouts = [];
  23830. for ( const bindingsGroup of bindings ) {
  23831. const bindingsData = backend.get( bindingsGroup );
  23832. bindGroupLayouts.push( bindingsData.layout );
  23833. }
  23834. pipelineGPU.pipeline = device.createComputePipeline( {
  23835. compute: computeProgram,
  23836. layout: device.createPipelineLayout( {
  23837. bindGroupLayouts
  23838. } )
  23839. } );
  23840. }
  23841. _getBlending( material ) {
  23842. let color, alpha;
  23843. const blending = material.blending;
  23844. const blendSrc = material.blendSrc;
  23845. const blendDst = material.blendDst;
  23846. const blendEquation = material.blendEquation;
  23847. if ( blending === CustomBlending ) {
  23848. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  23849. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  23850. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  23851. color = {
  23852. srcFactor: this._getBlendFactor( blendSrc ),
  23853. dstFactor: this._getBlendFactor( blendDst ),
  23854. operation: this._getBlendOperation( blendEquation )
  23855. };
  23856. alpha = {
  23857. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  23858. dstFactor: this._getBlendFactor( blendDstAlpha ),
  23859. operation: this._getBlendOperation( blendEquationAlpha )
  23860. };
  23861. } else {
  23862. const premultipliedAlpha = material.premultipliedAlpha;
  23863. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  23864. color = {
  23865. srcFactor: srcRGB,
  23866. dstFactor: dstRGB,
  23867. operation: GPUBlendOperation.Add
  23868. };
  23869. alpha = {
  23870. srcFactor: srcAlpha,
  23871. dstFactor: dstAlpha,
  23872. operation: GPUBlendOperation.Add
  23873. };
  23874. };
  23875. if ( premultipliedAlpha ) {
  23876. switch ( blending ) {
  23877. case NormalBlending:
  23878. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  23879. break;
  23880. case AdditiveBlending:
  23881. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  23882. break;
  23883. case SubtractiveBlending:
  23884. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  23885. break;
  23886. case MultiplyBlending:
  23887. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  23888. break;
  23889. }
  23890. } else {
  23891. switch ( blending ) {
  23892. case NormalBlending:
  23893. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  23894. break;
  23895. case AdditiveBlending:
  23896. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  23897. break;
  23898. case SubtractiveBlending:
  23899. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  23900. break;
  23901. case MultiplyBlending:
  23902. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  23903. break;
  23904. }
  23905. }
  23906. }
  23907. if ( color !== undefined && alpha !== undefined ) {
  23908. return { color, alpha };
  23909. } else {
  23910. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  23911. }
  23912. }
  23913. _getBlendFactor( blend ) {
  23914. let blendFactor;
  23915. switch ( blend ) {
  23916. case ZeroFactor:
  23917. blendFactor = GPUBlendFactor.Zero;
  23918. break;
  23919. case OneFactor:
  23920. blendFactor = GPUBlendFactor.One;
  23921. break;
  23922. case SrcColorFactor:
  23923. blendFactor = GPUBlendFactor.Src;
  23924. break;
  23925. case OneMinusSrcColorFactor:
  23926. blendFactor = GPUBlendFactor.OneMinusSrc;
  23927. break;
  23928. case SrcAlphaFactor:
  23929. blendFactor = GPUBlendFactor.SrcAlpha;
  23930. break;
  23931. case OneMinusSrcAlphaFactor:
  23932. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  23933. break;
  23934. case DstColorFactor:
  23935. blendFactor = GPUBlendFactor.Dst;
  23936. break;
  23937. case OneMinusDstColorFactor:
  23938. blendFactor = GPUBlendFactor.OneMinusDstColor;
  23939. break;
  23940. case DstAlphaFactor:
  23941. blendFactor = GPUBlendFactor.DstAlpha;
  23942. break;
  23943. case OneMinusDstAlphaFactor:
  23944. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  23945. break;
  23946. case SrcAlphaSaturateFactor:
  23947. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  23948. break;
  23949. case BlendColorFactor:
  23950. blendFactor = GPUBlendFactor.Constant;
  23951. break;
  23952. case OneMinusBlendColorFactor:
  23953. blendFactor = GPUBlendFactor.OneMinusConstant;
  23954. break;
  23955. default:
  23956. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  23957. }
  23958. return blendFactor;
  23959. }
  23960. _getStencilCompare( material ) {
  23961. let stencilCompare;
  23962. const stencilFunc = material.stencilFunc;
  23963. switch ( stencilFunc ) {
  23964. case NeverStencilFunc:
  23965. stencilCompare = GPUCompareFunction.Never;
  23966. break;
  23967. case AlwaysStencilFunc:
  23968. stencilCompare = GPUCompareFunction.Always;
  23969. break;
  23970. case LessStencilFunc:
  23971. stencilCompare = GPUCompareFunction.Less;
  23972. break;
  23973. case LessEqualStencilFunc:
  23974. stencilCompare = GPUCompareFunction.LessEqual;
  23975. break;
  23976. case EqualStencilFunc:
  23977. stencilCompare = GPUCompareFunction.Equal;
  23978. break;
  23979. case GreaterEqualStencilFunc:
  23980. stencilCompare = GPUCompareFunction.GreaterEqual;
  23981. break;
  23982. case GreaterStencilFunc:
  23983. stencilCompare = GPUCompareFunction.Greater;
  23984. break;
  23985. case NotEqualStencilFunc:
  23986. stencilCompare = GPUCompareFunction.NotEqual;
  23987. break;
  23988. default:
  23989. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  23990. }
  23991. return stencilCompare;
  23992. }
  23993. _getStencilOperation( op ) {
  23994. let stencilOperation;
  23995. switch ( op ) {
  23996. case KeepStencilOp:
  23997. stencilOperation = GPUStencilOperation.Keep;
  23998. break;
  23999. case ZeroStencilOp:
  24000. stencilOperation = GPUStencilOperation.Zero;
  24001. break;
  24002. case ReplaceStencilOp:
  24003. stencilOperation = GPUStencilOperation.Replace;
  24004. break;
  24005. case InvertStencilOp:
  24006. stencilOperation = GPUStencilOperation.Invert;
  24007. break;
  24008. case IncrementStencilOp:
  24009. stencilOperation = GPUStencilOperation.IncrementClamp;
  24010. break;
  24011. case DecrementStencilOp:
  24012. stencilOperation = GPUStencilOperation.DecrementClamp;
  24013. break;
  24014. case IncrementWrapStencilOp:
  24015. stencilOperation = GPUStencilOperation.IncrementWrap;
  24016. break;
  24017. case DecrementWrapStencilOp:
  24018. stencilOperation = GPUStencilOperation.DecrementWrap;
  24019. break;
  24020. default:
  24021. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  24022. }
  24023. return stencilOperation;
  24024. }
  24025. _getBlendOperation( blendEquation ) {
  24026. let blendOperation;
  24027. switch ( blendEquation ) {
  24028. case AddEquation:
  24029. blendOperation = GPUBlendOperation.Add;
  24030. break;
  24031. case SubtractEquation:
  24032. blendOperation = GPUBlendOperation.Subtract;
  24033. break;
  24034. case ReverseSubtractEquation:
  24035. blendOperation = GPUBlendOperation.ReverseSubtract;
  24036. break;
  24037. case MinEquation:
  24038. blendOperation = GPUBlendOperation.Min;
  24039. break;
  24040. case MaxEquation:
  24041. blendOperation = GPUBlendOperation.Max;
  24042. break;
  24043. default:
  24044. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  24045. }
  24046. return blendOperation;
  24047. }
  24048. _getPrimitiveState( object, geometry, material ) {
  24049. const descriptor = {};
  24050. const utils = this.backend.utils;
  24051. descriptor.topology = utils.getPrimitiveTopology( object, material );
  24052. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  24053. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  24054. }
  24055. switch ( material.side ) {
  24056. case FrontSide:
  24057. descriptor.frontFace = GPUFrontFace.CCW;
  24058. descriptor.cullMode = GPUCullMode.Back;
  24059. break;
  24060. case BackSide:
  24061. descriptor.frontFace = GPUFrontFace.CCW;
  24062. descriptor.cullMode = GPUCullMode.Front;
  24063. break;
  24064. case DoubleSide:
  24065. descriptor.frontFace = GPUFrontFace.CCW;
  24066. descriptor.cullMode = GPUCullMode.None;
  24067. break;
  24068. default:
  24069. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  24070. break;
  24071. }
  24072. return descriptor;
  24073. }
  24074. _getColorWriteMask( material ) {
  24075. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  24076. }
  24077. _getDepthCompare( material ) {
  24078. let depthCompare;
  24079. if ( material.depthTest === false ) {
  24080. depthCompare = GPUCompareFunction.Always;
  24081. } else {
  24082. const depthFunc = material.depthFunc;
  24083. switch ( depthFunc ) {
  24084. case NeverDepth:
  24085. depthCompare = GPUCompareFunction.Never;
  24086. break;
  24087. case AlwaysDepth:
  24088. depthCompare = GPUCompareFunction.Always;
  24089. break;
  24090. case LessDepth:
  24091. depthCompare = GPUCompareFunction.Less;
  24092. break;
  24093. case LessEqualDepth:
  24094. depthCompare = GPUCompareFunction.LessEqual;
  24095. break;
  24096. case EqualDepth:
  24097. depthCompare = GPUCompareFunction.Equal;
  24098. break;
  24099. case GreaterEqualDepth:
  24100. depthCompare = GPUCompareFunction.GreaterEqual;
  24101. break;
  24102. case GreaterDepth:
  24103. depthCompare = GPUCompareFunction.Greater;
  24104. break;
  24105. case NotEqualDepth:
  24106. depthCompare = GPUCompareFunction.NotEqual;
  24107. break;
  24108. default:
  24109. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  24110. }
  24111. }
  24112. return depthCompare;
  24113. }
  24114. }
  24115. /*// debugger tools
  24116. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  24117. //*/
  24118. //
  24119. class WebGPUBackend extends Backend {
  24120. constructor( parameters = {} ) {
  24121. super( parameters );
  24122. this.isWebGPUBackend = true;
  24123. // some parameters require default values other than "undefined"
  24124. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  24125. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  24126. this.trackTimestamp = ( parameters.trackTimestamp === true );
  24127. this.device = null;
  24128. this.context = null;
  24129. this.colorBuffer = null;
  24130. this.defaultRenderPassdescriptor = null;
  24131. this.utils = new WebGPUUtils( this );
  24132. this.attributeUtils = new WebGPUAttributeUtils( this );
  24133. this.bindingUtils = new WebGPUBindingUtils( this );
  24134. this.pipelineUtils = new WebGPUPipelineUtils( this );
  24135. this.textureUtils = new WebGPUTextureUtils( this );
  24136. this.occludedResolveCache = new Map();
  24137. }
  24138. async init( renderer ) {
  24139. await super.init( renderer );
  24140. //
  24141. const parameters = this.parameters;
  24142. // create the device if it is not passed with parameters
  24143. let device;
  24144. if ( parameters.device === undefined ) {
  24145. const adapterOptions = {
  24146. powerPreference: parameters.powerPreference
  24147. };
  24148. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  24149. if ( adapter === null ) {
  24150. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  24151. }
  24152. // feature support
  24153. const features = Object.values( GPUFeatureName );
  24154. const supportedFeatures = [];
  24155. for ( const name of features ) {
  24156. if ( adapter.features.has( name ) ) {
  24157. supportedFeatures.push( name );
  24158. }
  24159. }
  24160. const deviceDescriptor = {
  24161. requiredFeatures: supportedFeatures,
  24162. requiredLimits: parameters.requiredLimits
  24163. };
  24164. device = await adapter.requestDevice( deviceDescriptor );
  24165. } else {
  24166. device = parameters.device;
  24167. }
  24168. device.lost.then( ( info ) => {
  24169. const deviceLossInfo = {
  24170. api: 'WebGPU',
  24171. message: info.message || 'Unknown reason',
  24172. reason: info.reason || null,
  24173. originalEvent: info
  24174. };
  24175. renderer.onDeviceLost( deviceLossInfo );
  24176. } );
  24177. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  24178. this.device = device;
  24179. this.context = context;
  24180. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  24181. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  24182. this.context.configure( {
  24183. device: this.device,
  24184. format: this.utils.getPreferredCanvasFormat(),
  24185. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  24186. alphaMode: alphaMode
  24187. } );
  24188. this.updateSize();
  24189. }
  24190. get coordinateSystem() {
  24191. return WebGPUCoordinateSystem;
  24192. }
  24193. async getArrayBufferAsync( attribute ) {
  24194. return await this.attributeUtils.getArrayBufferAsync( attribute );
  24195. }
  24196. getContext() {
  24197. return this.context;
  24198. }
  24199. _getDefaultRenderPassDescriptor() {
  24200. let descriptor = this.defaultRenderPassdescriptor;
  24201. if ( descriptor === null ) {
  24202. const renderer = this.renderer;
  24203. descriptor = {
  24204. colorAttachments: [ {
  24205. view: null
  24206. } ],
  24207. };
  24208. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  24209. descriptor.depthStencilAttachment = {
  24210. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  24211. };
  24212. }
  24213. const colorAttachment = descriptor.colorAttachments[ 0 ];
  24214. if ( this.renderer.samples > 0 ) {
  24215. colorAttachment.view = this.colorBuffer.createView();
  24216. } else {
  24217. colorAttachment.resolveTarget = undefined;
  24218. }
  24219. this.defaultRenderPassdescriptor = descriptor;
  24220. }
  24221. const colorAttachment = descriptor.colorAttachments[ 0 ];
  24222. if ( this.renderer.samples > 0 ) {
  24223. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  24224. } else {
  24225. colorAttachment.view = this.context.getCurrentTexture().createView();
  24226. }
  24227. return descriptor;
  24228. }
  24229. _getRenderPassDescriptor( renderContext ) {
  24230. const renderTarget = renderContext.renderTarget;
  24231. const renderTargetData = this.get( renderTarget );
  24232. let descriptors = renderTargetData.descriptors;
  24233. if ( descriptors === undefined ||
  24234. renderTargetData.width !== renderTarget.width ||
  24235. renderTargetData.height !== renderTarget.height ||
  24236. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  24237. renderTargetData.samples !== renderTarget.samples
  24238. ) {
  24239. descriptors = {};
  24240. renderTargetData.descriptors = descriptors;
  24241. // dispose
  24242. const onDispose = () => {
  24243. renderTarget.removeEventListener( 'dispose', onDispose );
  24244. this.delete( renderTarget );
  24245. };
  24246. renderTarget.addEventListener( 'dispose', onDispose );
  24247. }
  24248. const cacheKey = renderContext.getCacheKey();
  24249. let descriptor = descriptors[ cacheKey ];
  24250. if ( descriptor === undefined ) {
  24251. const textures = renderContext.textures;
  24252. const colorAttachments = [];
  24253. for ( let i = 0; i < textures.length; i ++ ) {
  24254. const textureData = this.get( textures[ i ] );
  24255. const textureView = textureData.texture.createView( {
  24256. baseMipLevel: renderContext.activeMipmapLevel,
  24257. mipLevelCount: 1,
  24258. baseArrayLayer: renderContext.activeCubeFace,
  24259. dimension: GPUTextureViewDimension.TwoD
  24260. } );
  24261. let view, resolveTarget;
  24262. if ( textureData.msaaTexture !== undefined ) {
  24263. view = textureData.msaaTexture.createView();
  24264. resolveTarget = textureView;
  24265. } else {
  24266. view = textureView;
  24267. resolveTarget = undefined;
  24268. }
  24269. colorAttachments.push( {
  24270. view,
  24271. resolveTarget,
  24272. loadOp: GPULoadOp.Load,
  24273. storeOp: GPUStoreOp.Store
  24274. } );
  24275. }
  24276. descriptor = {
  24277. colorAttachments,
  24278. };
  24279. if ( renderContext.depth ) {
  24280. const depthTextureData = this.get( renderContext.depthTexture );
  24281. const depthStencilAttachment = {
  24282. view: depthTextureData.texture.createView()
  24283. };
  24284. descriptor.depthStencilAttachment = depthStencilAttachment;
  24285. }
  24286. descriptors[ cacheKey ] = descriptor;
  24287. renderTargetData.width = renderTarget.width;
  24288. renderTargetData.height = renderTarget.height;
  24289. renderTargetData.samples = renderTarget.samples;
  24290. renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel;
  24291. }
  24292. return descriptor;
  24293. }
  24294. beginRender( renderContext ) {
  24295. const renderContextData = this.get( renderContext );
  24296. const device = this.device;
  24297. const occlusionQueryCount = renderContext.occlusionQueryCount;
  24298. let occlusionQuerySet;
  24299. if ( occlusionQueryCount > 0 ) {
  24300. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  24301. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  24302. // Get a reference to the array of objects with queries. The renderContextData property
  24303. // can be changed by another render pass before the buffer.mapAsyc() completes.
  24304. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  24305. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  24306. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  24307. //
  24308. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  24309. renderContextData.occlusionQuerySet = occlusionQuerySet;
  24310. renderContextData.occlusionQueryIndex = 0;
  24311. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  24312. renderContextData.lastOcclusionObject = null;
  24313. }
  24314. let descriptor;
  24315. if ( renderContext.textures === null ) {
  24316. descriptor = this._getDefaultRenderPassDescriptor();
  24317. } else {
  24318. descriptor = this._getRenderPassDescriptor( renderContext );
  24319. }
  24320. this.initTimestampQuery( renderContext, descriptor );
  24321. descriptor.occlusionQuerySet = occlusionQuerySet;
  24322. const depthStencilAttachment = descriptor.depthStencilAttachment;
  24323. if ( renderContext.textures !== null ) {
  24324. const colorAttachments = descriptor.colorAttachments;
  24325. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  24326. const colorAttachment = colorAttachments[ i ];
  24327. if ( renderContext.clearColor ) {
  24328. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  24329. colorAttachment.loadOp = GPULoadOp.Clear;
  24330. colorAttachment.storeOp = GPUStoreOp.Store;
  24331. } else {
  24332. colorAttachment.loadOp = GPULoadOp.Load;
  24333. colorAttachment.storeOp = GPUStoreOp.Store;
  24334. }
  24335. }
  24336. } else {
  24337. const colorAttachment = descriptor.colorAttachments[ 0 ];
  24338. if ( renderContext.clearColor ) {
  24339. colorAttachment.clearValue = renderContext.clearColorValue;
  24340. colorAttachment.loadOp = GPULoadOp.Clear;
  24341. colorAttachment.storeOp = GPUStoreOp.Store;
  24342. } else {
  24343. colorAttachment.loadOp = GPULoadOp.Load;
  24344. colorAttachment.storeOp = GPUStoreOp.Store;
  24345. }
  24346. }
  24347. //
  24348. if ( renderContext.depth ) {
  24349. if ( renderContext.clearDepth ) {
  24350. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  24351. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  24352. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  24353. } else {
  24354. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  24355. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  24356. }
  24357. }
  24358. if ( renderContext.stencil ) {
  24359. if ( renderContext.clearStencil ) {
  24360. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  24361. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  24362. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  24363. } else {
  24364. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  24365. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  24366. }
  24367. }
  24368. //
  24369. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  24370. const currentPass = encoder.beginRenderPass( descriptor );
  24371. //
  24372. renderContextData.descriptor = descriptor;
  24373. renderContextData.encoder = encoder;
  24374. renderContextData.currentPass = currentPass;
  24375. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  24376. renderContextData.renderBundles = [];
  24377. //
  24378. if ( renderContext.viewport ) {
  24379. this.updateViewport( renderContext );
  24380. }
  24381. if ( renderContext.scissor ) {
  24382. const { x, y, width, height } = renderContext.scissorValue;
  24383. currentPass.setScissorRect( x, y, width, height );
  24384. }
  24385. }
  24386. finishRender( renderContext ) {
  24387. const renderContextData = this.get( renderContext );
  24388. const occlusionQueryCount = renderContext.occlusionQueryCount;
  24389. if ( renderContextData.renderBundles.length > 0 ) {
  24390. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  24391. }
  24392. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  24393. renderContextData.currentPass.endOcclusionQuery();
  24394. }
  24395. renderContextData.currentPass.end();
  24396. if ( occlusionQueryCount > 0 ) {
  24397. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  24398. //
  24399. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  24400. if ( queryResolveBuffer === undefined ) {
  24401. queryResolveBuffer = this.device.createBuffer(
  24402. {
  24403. size: bufferSize,
  24404. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  24405. }
  24406. );
  24407. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  24408. }
  24409. //
  24410. const readBuffer = this.device.createBuffer(
  24411. {
  24412. size: bufferSize,
  24413. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  24414. }
  24415. );
  24416. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  24417. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  24418. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  24419. renderContextData.occlusionQueryBuffer = readBuffer;
  24420. //
  24421. this.resolveOccludedAsync( renderContext );
  24422. }
  24423. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  24424. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  24425. //
  24426. if ( renderContext.textures !== null ) {
  24427. const textures = renderContext.textures;
  24428. for ( let i = 0; i < textures.length; i ++ ) {
  24429. const texture = textures[ i ];
  24430. if ( texture.generateMipmaps === true ) {
  24431. this.textureUtils.generateMipmaps( texture );
  24432. }
  24433. }
  24434. }
  24435. }
  24436. isOccluded( renderContext, object ) {
  24437. const renderContextData = this.get( renderContext );
  24438. return renderContextData.occluded && renderContextData.occluded.has( object );
  24439. }
  24440. async resolveOccludedAsync( renderContext ) {
  24441. const renderContextData = this.get( renderContext );
  24442. // handle occlusion query results
  24443. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  24444. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  24445. const occluded = new WeakSet();
  24446. renderContextData.currentOcclusionQueryObjects = null;
  24447. renderContextData.currentOcclusionQueryBuffer = null;
  24448. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  24449. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  24450. const results = new BigUint64Array( buffer );
  24451. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  24452. if ( results[ i ] !== BigInt( 0 ) ) {
  24453. occluded.add( currentOcclusionQueryObjects[ i ] );
  24454. }
  24455. }
  24456. currentOcclusionQueryBuffer.destroy();
  24457. renderContextData.occluded = occluded;
  24458. }
  24459. }
  24460. updateViewport( renderContext ) {
  24461. const { currentPass } = this.get( renderContext );
  24462. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  24463. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  24464. }
  24465. clear( color, depth, stencil, renderTargetData = null ) {
  24466. const device = this.device;
  24467. const renderer = this.renderer;
  24468. let colorAttachments = [];
  24469. let depthStencilAttachment;
  24470. let clearValue;
  24471. let supportsDepth;
  24472. let supportsStencil;
  24473. if ( color ) {
  24474. const clearColor = this.getClearColor();
  24475. if ( this.renderer.alpha === true ) {
  24476. // premultiply alpha
  24477. const a = clearColor.a;
  24478. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  24479. } else {
  24480. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  24481. }
  24482. }
  24483. if ( renderTargetData === null ) {
  24484. supportsDepth = renderer.depth;
  24485. supportsStencil = renderer.stencil;
  24486. const descriptor = this._getDefaultRenderPassDescriptor();
  24487. if ( color ) {
  24488. colorAttachments = descriptor.colorAttachments;
  24489. const colorAttachment = colorAttachments[ 0 ];
  24490. colorAttachment.clearValue = clearValue;
  24491. colorAttachment.loadOp = GPULoadOp.Clear;
  24492. colorAttachment.storeOp = GPUStoreOp.Store;
  24493. }
  24494. if ( supportsDepth || supportsStencil ) {
  24495. depthStencilAttachment = descriptor.depthStencilAttachment;
  24496. }
  24497. } else {
  24498. supportsDepth = renderTargetData.depth;
  24499. supportsStencil = renderTargetData.stencil;
  24500. if ( color ) {
  24501. for ( const texture of renderTargetData.textures ) {
  24502. const textureData = this.get( texture );
  24503. const textureView = textureData.texture.createView();
  24504. let view, resolveTarget;
  24505. if ( textureData.msaaTexture !== undefined ) {
  24506. view = textureData.msaaTexture.createView();
  24507. resolveTarget = textureView;
  24508. } else {
  24509. view = textureView;
  24510. resolveTarget = undefined;
  24511. }
  24512. colorAttachments.push( {
  24513. view,
  24514. resolveTarget,
  24515. clearValue,
  24516. loadOp: GPULoadOp.Clear,
  24517. storeOp: GPUStoreOp.Store
  24518. } );
  24519. }
  24520. }
  24521. if ( supportsDepth || supportsStencil ) {
  24522. const depthTextureData = this.get( renderTargetData.depthTexture );
  24523. depthStencilAttachment = {
  24524. view: depthTextureData.texture.createView()
  24525. };
  24526. }
  24527. }
  24528. //
  24529. if ( supportsDepth ) {
  24530. if ( depth ) {
  24531. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  24532. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  24533. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  24534. } else {
  24535. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  24536. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  24537. }
  24538. }
  24539. //
  24540. if ( supportsStencil ) {
  24541. if ( stencil ) {
  24542. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  24543. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  24544. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  24545. } else {
  24546. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  24547. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  24548. }
  24549. }
  24550. //
  24551. const encoder = device.createCommandEncoder( {} );
  24552. const currentPass = encoder.beginRenderPass( {
  24553. colorAttachments,
  24554. depthStencilAttachment
  24555. } );
  24556. currentPass.end();
  24557. device.queue.submit( [ encoder.finish() ] );
  24558. }
  24559. // compute
  24560. beginCompute( computeGroup ) {
  24561. const groupGPU = this.get( computeGroup );
  24562. const descriptor = {};
  24563. this.initTimestampQuery( computeGroup, descriptor );
  24564. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  24565. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  24566. }
  24567. compute( computeGroup, computeNode, bindings, pipeline ) {
  24568. const { passEncoderGPU } = this.get( computeGroup );
  24569. // pipeline
  24570. const pipelineGPU = this.get( pipeline ).pipeline;
  24571. passEncoderGPU.setPipeline( pipelineGPU );
  24572. // bind groups
  24573. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  24574. const bindGroup = bindings[ i ];
  24575. const bindingsData = this.get( bindGroup );
  24576. passEncoderGPU.setBindGroup( i, bindingsData.group );
  24577. }
  24578. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  24579. const computeNodeData = this.get( computeNode );
  24580. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  24581. const { dispatchSize } = computeNodeData;
  24582. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  24583. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  24584. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  24585. } else {
  24586. dispatchSize.x = computeNode.dispatchCount;
  24587. }
  24588. passEncoderGPU.dispatchWorkgroups(
  24589. dispatchSize.x,
  24590. dispatchSize.y,
  24591. dispatchSize.z
  24592. );
  24593. }
  24594. finishCompute( computeGroup ) {
  24595. const groupData = this.get( computeGroup );
  24596. groupData.passEncoderGPU.end();
  24597. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  24598. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  24599. }
  24600. async waitForGPU() {
  24601. await this.device.queue.onSubmittedWorkDone();
  24602. }
  24603. // render object
  24604. draw( renderObject, info ) {
  24605. const { object, context, pipeline } = renderObject;
  24606. const bindings = renderObject.getBindings();
  24607. const renderContextData = this.get( context );
  24608. const pipelineGPU = this.get( pipeline ).pipeline;
  24609. const currentSets = renderContextData.currentSets;
  24610. const passEncoderGPU = renderContextData.currentPass;
  24611. const drawParams = renderObject.getDrawParameters();
  24612. if ( drawParams === null ) return;
  24613. // pipeline
  24614. if ( currentSets.pipeline !== pipelineGPU ) {
  24615. passEncoderGPU.setPipeline( pipelineGPU );
  24616. currentSets.pipeline = pipelineGPU;
  24617. }
  24618. // bind groups
  24619. const currentBindingGroups = currentSets.bindingGroups;
  24620. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  24621. const bindGroup = bindings[ i ];
  24622. const bindingsData = this.get( bindGroup );
  24623. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  24624. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  24625. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  24626. }
  24627. }
  24628. // attributes
  24629. const index = renderObject.getIndex();
  24630. const hasIndex = ( index !== null );
  24631. // index
  24632. if ( hasIndex === true ) {
  24633. if ( currentSets.index !== index ) {
  24634. const buffer = this.get( index ).buffer;
  24635. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  24636. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  24637. currentSets.index = index;
  24638. }
  24639. }
  24640. // vertex buffers
  24641. const vertexBuffers = renderObject.getVertexBuffers();
  24642. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  24643. const vertexBuffer = vertexBuffers[ i ];
  24644. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  24645. const buffer = this.get( vertexBuffer ).buffer;
  24646. passEncoderGPU.setVertexBuffer( i, buffer );
  24647. currentSets.attributes[ i ] = vertexBuffer;
  24648. }
  24649. }
  24650. // occlusion queries - handle multiple consecutive draw calls for an object
  24651. if ( renderContextData.occlusionQuerySet !== undefined ) {
  24652. const lastObject = renderContextData.lastOcclusionObject;
  24653. if ( lastObject !== object ) {
  24654. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  24655. passEncoderGPU.endOcclusionQuery();
  24656. renderContextData.occlusionQueryIndex ++;
  24657. }
  24658. if ( object.occlusionTest === true ) {
  24659. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  24660. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  24661. }
  24662. renderContextData.lastOcclusionObject = object;
  24663. }
  24664. }
  24665. // draw
  24666. if ( object.isBatchedMesh === true ) {
  24667. const starts = object._multiDrawStarts;
  24668. const counts = object._multiDrawCounts;
  24669. const drawCount = object._multiDrawCount;
  24670. const drawInstances = object._multiDrawInstances;
  24671. const bytesPerElement = hasIndex ? index.array.BYTES_PER_ELEMENT : 1;
  24672. for ( let i = 0; i < drawCount; i ++ ) {
  24673. const count = drawInstances ? drawInstances[ i ] : 1;
  24674. const firstInstance = count > 1 ? 0 : i;
  24675. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / bytesPerElement, 0, firstInstance );
  24676. }
  24677. } else if ( hasIndex === true ) {
  24678. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  24679. const indirect = renderObject.getIndirect();
  24680. if ( indirect !== null ) {
  24681. const buffer = this.get( indirect ).buffer;
  24682. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  24683. } else {
  24684. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  24685. }
  24686. info.update( object, indexCount, instanceCount );
  24687. } else {
  24688. const { vertexCount, instanceCount, firstVertex } = drawParams;
  24689. const indirect = renderObject.getIndirect();
  24690. if ( indirect !== null ) {
  24691. const buffer = this.get( indirect ).buffer;
  24692. passEncoderGPU.drawIndirect( buffer, 0 );
  24693. } else {
  24694. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  24695. }
  24696. info.update( object, vertexCount, instanceCount );
  24697. }
  24698. }
  24699. // cache key
  24700. needsRenderUpdate( renderObject ) {
  24701. const data = this.get( renderObject );
  24702. const { object, material } = renderObject;
  24703. const utils = this.utils;
  24704. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  24705. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  24706. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  24707. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  24708. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  24709. let needsUpdate = false;
  24710. if ( data.material !== material || data.materialVersion !== material.version ||
  24711. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  24712. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  24713. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  24714. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  24715. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  24716. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  24717. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  24718. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  24719. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  24720. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  24721. data.primitiveTopology !== primitiveTopology ||
  24722. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  24723. ) {
  24724. data.material = material; data.materialVersion = material.version;
  24725. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  24726. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  24727. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  24728. data.colorWrite = material.colorWrite;
  24729. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  24730. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  24731. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  24732. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  24733. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  24734. data.sampleCount = sampleCount;
  24735. data.colorSpace = colorSpace;
  24736. data.colorFormat = colorFormat;
  24737. data.depthStencilFormat = depthStencilFormat;
  24738. data.primitiveTopology = primitiveTopology;
  24739. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  24740. needsUpdate = true;
  24741. }
  24742. return needsUpdate;
  24743. }
  24744. getRenderCacheKey( renderObject ) {
  24745. const { object, material } = renderObject;
  24746. const utils = this.utils;
  24747. const renderContext = renderObject.context;
  24748. return [
  24749. material.transparent, material.blending, material.premultipliedAlpha,
  24750. material.blendSrc, material.blendDst, material.blendEquation,
  24751. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  24752. material.colorWrite,
  24753. material.depthWrite, material.depthTest, material.depthFunc,
  24754. material.stencilWrite, material.stencilFunc,
  24755. material.stencilFail, material.stencilZFail, material.stencilZPass,
  24756. material.stencilFuncMask, material.stencilWriteMask,
  24757. material.side,
  24758. utils.getSampleCountRenderContext( renderContext ),
  24759. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  24760. utils.getPrimitiveTopology( object, material ),
  24761. renderObject.getGeometryCacheKey(),
  24762. renderObject.clippingContextCacheKey
  24763. ].join();
  24764. }
  24765. // textures
  24766. createSampler( texture ) {
  24767. this.textureUtils.createSampler( texture );
  24768. }
  24769. destroySampler( texture ) {
  24770. this.textureUtils.destroySampler( texture );
  24771. }
  24772. createDefaultTexture( texture ) {
  24773. this.textureUtils.createDefaultTexture( texture );
  24774. }
  24775. createTexture( texture, options ) {
  24776. this.textureUtils.createTexture( texture, options );
  24777. }
  24778. updateTexture( texture, options ) {
  24779. this.textureUtils.updateTexture( texture, options );
  24780. }
  24781. generateMipmaps( texture ) {
  24782. this.textureUtils.generateMipmaps( texture );
  24783. }
  24784. destroyTexture( texture ) {
  24785. this.textureUtils.destroyTexture( texture );
  24786. }
  24787. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  24788. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  24789. }
  24790. initTimestampQuery( renderContext, descriptor ) {
  24791. if ( ! this.trackTimestamp ) return;
  24792. const renderContextData = this.get( renderContext );
  24793. if ( ! renderContextData.timeStampQuerySet ) {
  24794. const type = renderContext.isComputeNode ? 'compute' : 'render';
  24795. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2, label: `timestamp_${type}_${renderContext.id}` } );
  24796. const timestampWrites = {
  24797. querySet: timeStampQuerySet,
  24798. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  24799. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  24800. };
  24801. Object.assign( descriptor, { timestampWrites } );
  24802. renderContextData.timeStampQuerySet = timeStampQuerySet;
  24803. }
  24804. }
  24805. // timestamp utils
  24806. prepareTimestampBuffer( renderContext, encoder ) {
  24807. if ( ! this.trackTimestamp ) return;
  24808. const renderContextData = this.get( renderContext );
  24809. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  24810. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  24811. renderContextData.currentTimestampQueryBuffers = {
  24812. resolveBuffer: this.device.createBuffer( {
  24813. label: 'timestamp resolve buffer',
  24814. size: size,
  24815. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  24816. } ),
  24817. resultBuffer: this.device.createBuffer( {
  24818. label: 'timestamp result buffer',
  24819. size: size,
  24820. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  24821. } )
  24822. };
  24823. }
  24824. const { resolveBuffer, resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  24825. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  24826. if ( resultBuffer.mapState === 'unmapped' ) {
  24827. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  24828. }
  24829. }
  24830. async resolveTimestampAsync( renderContext, type = 'render' ) {
  24831. if ( ! this.trackTimestamp ) return;
  24832. const renderContextData = this.get( renderContext );
  24833. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  24834. const { resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  24835. await this.device.queue.onSubmittedWorkDone();
  24836. if ( resultBuffer.mapState === 'unmapped' ) {
  24837. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  24838. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  24839. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  24840. this.renderer.info.updateTimestamp( type, duration );
  24841. resultBuffer.unmap();
  24842. } );
  24843. }
  24844. }
  24845. // node builder
  24846. createNodeBuilder( object, renderer ) {
  24847. return new WGSLNodeBuilder( object, renderer );
  24848. }
  24849. // program
  24850. createProgram( program ) {
  24851. const programGPU = this.get( program );
  24852. programGPU.module = {
  24853. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  24854. entryPoint: 'main'
  24855. };
  24856. }
  24857. destroyProgram( program ) {
  24858. this.delete( program );
  24859. }
  24860. // pipelines
  24861. createRenderPipeline( renderObject, promises ) {
  24862. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  24863. }
  24864. createComputePipeline( computePipeline, bindings ) {
  24865. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  24866. }
  24867. beginBundle( renderContext ) {
  24868. const renderContextData = this.get( renderContext );
  24869. renderContextData._currentPass = renderContextData.currentPass;
  24870. renderContextData._currentSets = renderContextData.currentSets;
  24871. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  24872. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  24873. }
  24874. finishBundle( renderContext, bundle ) {
  24875. const renderContextData = this.get( renderContext );
  24876. const bundleEncoder = renderContextData.currentPass;
  24877. const bundleGPU = bundleEncoder.finish();
  24878. this.get( bundle ).bundleGPU = bundleGPU;
  24879. // restore render pass state
  24880. renderContextData.currentSets = renderContextData._currentSets;
  24881. renderContextData.currentPass = renderContextData._currentPass;
  24882. }
  24883. addBundle( renderContext, bundle ) {
  24884. const renderContextData = this.get( renderContext );
  24885. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  24886. }
  24887. // bindings
  24888. createBindings( bindGroup, bindings, cacheIndex, version ) {
  24889. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  24890. }
  24891. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  24892. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  24893. }
  24894. updateBinding( binding ) {
  24895. this.bindingUtils.updateBinding( binding );
  24896. }
  24897. // attributes
  24898. createIndexAttribute( attribute ) {
  24899. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  24900. }
  24901. createAttribute( attribute ) {
  24902. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  24903. }
  24904. createStorageAttribute( attribute ) {
  24905. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  24906. }
  24907. createIndirectStorageAttribute( attribute ) {
  24908. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  24909. }
  24910. updateAttribute( attribute ) {
  24911. this.attributeUtils.updateAttribute( attribute );
  24912. }
  24913. destroyAttribute( attribute ) {
  24914. this.attributeUtils.destroyAttribute( attribute );
  24915. }
  24916. // canvas
  24917. updateSize() {
  24918. this.colorBuffer = this.textureUtils.getColorBuffer();
  24919. this.defaultRenderPassdescriptor = null;
  24920. }
  24921. // utils public
  24922. getMaxAnisotropy() {
  24923. return 16;
  24924. }
  24925. hasFeature( name ) {
  24926. return this.device.features.has( name );
  24927. }
  24928. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  24929. let dstX = 0;
  24930. let dstY = 0;
  24931. let dstLayer = 0;
  24932. let srcX = 0;
  24933. let srcY = 0;
  24934. let srcLayer = 0;
  24935. let srcWidth = srcTexture.image.width;
  24936. let srcHeight = srcTexture.image.height;
  24937. if ( srcRegion !== null ) {
  24938. srcX = srcRegion.x;
  24939. srcY = srcRegion.y;
  24940. srcLayer = srcRegion.z || 0;
  24941. srcWidth = srcRegion.width;
  24942. srcHeight = srcRegion.height;
  24943. }
  24944. if ( dstPosition !== null ) {
  24945. dstX = dstPosition.x;
  24946. dstY = dstPosition.y;
  24947. dstLayer = dstPosition.z || 0;
  24948. }
  24949. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  24950. const sourceGPU = this.get( srcTexture ).texture;
  24951. const destinationGPU = this.get( dstTexture ).texture;
  24952. encoder.copyTextureToTexture(
  24953. {
  24954. texture: sourceGPU,
  24955. mipLevel: level,
  24956. origin: { x: srcX, y: srcY, z: srcLayer }
  24957. },
  24958. {
  24959. texture: destinationGPU,
  24960. mipLevel: level,
  24961. origin: { x: dstX, y: dstY, z: dstLayer }
  24962. },
  24963. [
  24964. srcWidth,
  24965. srcHeight,
  24966. 1
  24967. ]
  24968. );
  24969. this.device.queue.submit( [ encoder.finish() ] );
  24970. }
  24971. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  24972. const renderContextData = this.get( renderContext );
  24973. let sourceGPU = null;
  24974. if ( renderContext.renderTarget ) {
  24975. if ( texture.isDepthTexture ) {
  24976. sourceGPU = this.get( renderContext.depthTexture ).texture;
  24977. } else {
  24978. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  24979. }
  24980. } else {
  24981. if ( texture.isDepthTexture ) {
  24982. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  24983. } else {
  24984. sourceGPU = this.context.getCurrentTexture();
  24985. }
  24986. }
  24987. const destinationGPU = this.get( texture ).texture;
  24988. if ( sourceGPU.format !== destinationGPU.format ) {
  24989. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  24990. return;
  24991. }
  24992. let encoder;
  24993. if ( renderContextData.currentPass ) {
  24994. renderContextData.currentPass.end();
  24995. encoder = renderContextData.encoder;
  24996. } else {
  24997. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  24998. }
  24999. encoder.copyTextureToTexture(
  25000. {
  25001. texture: sourceGPU,
  25002. origin: [ rectangle.x, rectangle.y, 0 ],
  25003. },
  25004. {
  25005. texture: destinationGPU
  25006. },
  25007. [
  25008. rectangle.z,
  25009. rectangle.w
  25010. ]
  25011. );
  25012. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  25013. if ( renderContextData.currentPass ) {
  25014. const { descriptor } = renderContextData;
  25015. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  25016. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  25017. }
  25018. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  25019. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  25020. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  25021. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  25022. if ( renderContext.viewport ) {
  25023. this.updateViewport( renderContext );
  25024. }
  25025. if ( renderContext.scissor ) {
  25026. const { x, y, width, height } = renderContext.scissorValue;
  25027. renderContextData.currentPass.setScissorRect( x, y, width, height );
  25028. }
  25029. } else {
  25030. this.device.queue.submit( [ encoder.finish() ] );
  25031. }
  25032. }
  25033. }
  25034. class IESSpotLight extends SpotLight {
  25035. constructor( color, intensity, distance, angle, penumbra, decay ) {
  25036. super( color, intensity, distance, angle, penumbra, decay );
  25037. this.iesMap = null;
  25038. }
  25039. copy( source, recursive ) {
  25040. super.copy( source, recursive );
  25041. this.iesMap = source.iesMap;
  25042. return this;
  25043. }
  25044. }
  25045. class StandardNodeLibrary extends NodeLibrary {
  25046. constructor() {
  25047. super();
  25048. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  25049. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  25050. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  25051. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  25052. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  25053. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  25054. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  25055. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  25056. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  25057. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  25058. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  25059. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  25060. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  25061. this.addLight( PointLightNode, PointLight );
  25062. this.addLight( DirectionalLightNode, DirectionalLight );
  25063. this.addLight( RectAreaLightNode, RectAreaLight );
  25064. this.addLight( SpotLightNode, SpotLight );
  25065. this.addLight( AmbientLightNode, AmbientLight );
  25066. this.addLight( HemisphereLightNode, HemisphereLight );
  25067. this.addLight( LightProbeNode, LightProbe );
  25068. this.addLight( IESSpotLightNode, IESSpotLight );
  25069. this.addToneMapping( linearToneMapping, LinearToneMapping );
  25070. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  25071. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  25072. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  25073. this.addToneMapping( agxToneMapping, AgXToneMapping );
  25074. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  25075. }
  25076. }
  25077. /*
  25078. const debugHandler = {
  25079. get: function ( target, name ) {
  25080. // Add |update
  25081. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  25082. return target[ name ];
  25083. }
  25084. };
  25085. */
  25086. class WebGPURenderer extends Renderer {
  25087. constructor( parameters = {} ) {
  25088. let BackendClass;
  25089. if ( parameters.forceWebGL ) {
  25090. BackendClass = WebGLBackend;
  25091. } else {
  25092. BackendClass = WebGPUBackend;
  25093. parameters.getFallback = () => {
  25094. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  25095. return new WebGLBackend( parameters );
  25096. };
  25097. }
  25098. const backend = new BackendClass( parameters );
  25099. //super( new Proxy( backend, debugHandler ) );
  25100. super( backend, parameters );
  25101. this.library = new StandardNodeLibrary();
  25102. this.isWebGPURenderer = true;
  25103. }
  25104. }
  25105. class BundleGroup extends Group {
  25106. constructor() {
  25107. super();
  25108. this.isBundleGroup = true;
  25109. this.type = 'BundleGroup';
  25110. this.static = true;
  25111. this.version = 0;
  25112. }
  25113. set needsUpdate( value ) {
  25114. if ( value === true ) this.version ++;
  25115. }
  25116. }
  25117. const _material = /*@__PURE__*/ new NodeMaterial();
  25118. const _quadMesh = /*@__PURE__*/ new QuadMesh( _material );
  25119. class PostProcessing {
  25120. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  25121. this.renderer = renderer;
  25122. this.outputNode = outputNode;
  25123. this.outputColorTransform = true;
  25124. this.needsUpdate = true;
  25125. _material.name = 'PostProcessing';
  25126. }
  25127. render() {
  25128. this.update();
  25129. const renderer = this.renderer;
  25130. const toneMapping = renderer.toneMapping;
  25131. const outputColorSpace = renderer.outputColorSpace;
  25132. renderer.toneMapping = NoToneMapping;
  25133. renderer.outputColorSpace = LinearSRGBColorSpace;
  25134. //
  25135. _quadMesh.render( renderer );
  25136. //
  25137. renderer.toneMapping = toneMapping;
  25138. renderer.outputColorSpace = outputColorSpace;
  25139. }
  25140. update() {
  25141. if ( this.needsUpdate === true ) {
  25142. const renderer = this.renderer;
  25143. const toneMapping = renderer.toneMapping;
  25144. const outputColorSpace = renderer.outputColorSpace;
  25145. _quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  25146. _quadMesh.material.needsUpdate = true;
  25147. this.needsUpdate = false;
  25148. }
  25149. }
  25150. async renderAsync() {
  25151. this.update();
  25152. const renderer = this.renderer;
  25153. const toneMapping = renderer.toneMapping;
  25154. const outputColorSpace = renderer.outputColorSpace;
  25155. renderer.toneMapping = NoToneMapping;
  25156. renderer.outputColorSpace = LinearSRGBColorSpace;
  25157. //
  25158. await _quadMesh.renderAsync( renderer );
  25159. //
  25160. renderer.toneMapping = toneMapping;
  25161. renderer.outputColorSpace = outputColorSpace;
  25162. }
  25163. }
  25164. // renderer state
  25165. function saveRendererState( renderer, state = {} ) {
  25166. state.toneMapping = renderer.toneMapping;
  25167. state.toneMappingExposure = renderer.toneMappingExposure;
  25168. state.outputColorSpace = renderer.outputColorSpace;
  25169. state.renderTarget = renderer.getRenderTarget();
  25170. state.activeCubeFace = renderer.getActiveCubeFace();
  25171. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  25172. state.renderObjectFunction = renderer.getRenderObjectFunction();
  25173. state.pixelRatio = renderer.getPixelRatio();
  25174. state.mrt = renderer.getMRT();
  25175. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  25176. state.clearAlpha = renderer.getClearAlpha();
  25177. state.autoClear = renderer.autoClear;
  25178. state.scissorTest = renderer.getScissorTest();
  25179. return state;
  25180. }
  25181. function resetRendererState( renderer, state ) {
  25182. state = saveRendererState( renderer, state );
  25183. renderer.setMRT( null );
  25184. renderer.setRenderObjectFunction( null );
  25185. renderer.setClearColor( 0x000000, 1 );
  25186. renderer.autoClear = true;
  25187. return state;
  25188. }
  25189. function restoreRendererState( renderer, state ) {
  25190. renderer.toneMapping = state.toneMapping;
  25191. renderer.toneMappingExposure = state.toneMappingExposure;
  25192. renderer.outputColorSpace = state.outputColorSpace;
  25193. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  25194. renderer.setRenderObjectFunction( state.renderObjectFunction );
  25195. renderer.setPixelRatio( state.pixelRatio );
  25196. renderer.setMRT( state.mrt );
  25197. renderer.setClearColor( state.clearColor, state.clearAlpha );
  25198. renderer.autoClear = state.autoClear;
  25199. renderer.setScissorTest( state.scissorTest );
  25200. }
  25201. // renderer and scene state
  25202. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  25203. state = saveRendererState( renderer, state );
  25204. state.background = scene.background;
  25205. state.backgroundNode = scene.backgroundNode;
  25206. state.overrideMaterial = scene.overrideMaterial;
  25207. return state;
  25208. }
  25209. function resetRendererAndSceneState( renderer, scene, state ) {
  25210. state = saveRendererAndSceneState( renderer, scene, state );
  25211. scene.background = null;
  25212. scene.backgroundNode = null;
  25213. scene.overrideMaterial = null;
  25214. return state;
  25215. }
  25216. function restoreRendererAndSceneState( renderer, scene, state ) {
  25217. restoreRendererState( renderer, state );
  25218. scene.background = state.background;
  25219. scene.backgroundNode = state.backgroundNode;
  25220. scene.overrideMaterial = state.overrideMaterial;
  25221. }
  25222. var PostProcessingUtils = /*#__PURE__*/Object.freeze({
  25223. __proto__: null,
  25224. resetRendererAndSceneState: resetRendererAndSceneState,
  25225. resetRendererState: resetRendererState,
  25226. restoreRendererAndSceneState: restoreRendererAndSceneState,
  25227. restoreRendererState: restoreRendererState,
  25228. saveRendererAndSceneState: saveRendererAndSceneState,
  25229. saveRendererState: saveRendererState
  25230. });
  25231. class StorageTexture extends Texture {
  25232. constructor( width = 1, height = 1 ) {
  25233. super();
  25234. this.image = { width, height };
  25235. this.magFilter = LinearFilter;
  25236. this.minFilter = LinearFilter;
  25237. this.isStorageTexture = true;
  25238. }
  25239. }
  25240. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  25241. constructor( array, itemSize ) {
  25242. super( array, itemSize, Uint32Array );
  25243. this.isIndirectStorageBufferAttribute = true;
  25244. }
  25245. }
  25246. class NodeLoader extends Loader {
  25247. constructor( manager ) {
  25248. super( manager );
  25249. this.textures = {};
  25250. this.nodes = {};
  25251. }
  25252. load( url, onLoad, onProgress, onError ) {
  25253. const loader = new FileLoader( this.manager );
  25254. loader.setPath( this.path );
  25255. loader.setRequestHeader( this.requestHeader );
  25256. loader.setWithCredentials( this.withCredentials );
  25257. loader.load( url, ( text ) => {
  25258. try {
  25259. onLoad( this.parse( JSON.parse( text ) ) );
  25260. } catch ( e ) {
  25261. if ( onError ) {
  25262. onError( e );
  25263. } else {
  25264. console.error( e );
  25265. }
  25266. this.manager.itemError( url );
  25267. }
  25268. }, onProgress, onError );
  25269. }
  25270. parseNodes( json ) {
  25271. const nodes = {};
  25272. if ( json !== undefined ) {
  25273. for ( const nodeJSON of json ) {
  25274. const { uuid, type } = nodeJSON;
  25275. nodes[ uuid ] = this.createNodeFromType( type );
  25276. nodes[ uuid ].uuid = uuid;
  25277. }
  25278. const meta = { nodes, textures: this.textures };
  25279. for ( const nodeJSON of json ) {
  25280. nodeJSON.meta = meta;
  25281. const node = nodes[ nodeJSON.uuid ];
  25282. node.deserialize( nodeJSON );
  25283. delete nodeJSON.meta;
  25284. }
  25285. }
  25286. return nodes;
  25287. }
  25288. parse( json ) {
  25289. const node = this.createNodeFromType( json.type );
  25290. node.uuid = json.uuid;
  25291. const nodes = this.parseNodes( json.nodes );
  25292. const meta = { nodes, textures: this.textures };
  25293. json.meta = meta;
  25294. node.deserialize( json );
  25295. delete json.meta;
  25296. return node;
  25297. }
  25298. setTextures( value ) {
  25299. this.textures = value;
  25300. return this;
  25301. }
  25302. setNodes( value ) {
  25303. this.nodes = value;
  25304. return this;
  25305. }
  25306. createNodeFromType( type ) {
  25307. if ( this.nodes[ type ] === undefined ) {
  25308. console.error( 'THREE.NodeLoader: Node type not found:', type );
  25309. return float();
  25310. }
  25311. return nodeObject( new this.nodes[ type ]() );
  25312. }
  25313. }
  25314. class NodeMaterialLoader extends MaterialLoader {
  25315. constructor( manager ) {
  25316. super( manager );
  25317. this.nodes = {};
  25318. this.nodeMaterials = {};
  25319. }
  25320. parse( json ) {
  25321. const material = super.parse( json );
  25322. const nodes = this.nodes;
  25323. const inputNodes = json.inputNodes;
  25324. for ( const property in inputNodes ) {
  25325. const uuid = inputNodes[ property ];
  25326. material[ property ] = nodes[ uuid ];
  25327. }
  25328. return material;
  25329. }
  25330. setNodes( value ) {
  25331. this.nodes = value;
  25332. return this;
  25333. }
  25334. setNodeMaterials( value ) {
  25335. this.nodeMaterials = value;
  25336. return this;
  25337. }
  25338. createMaterialFromType( type ) {
  25339. const materialClass = this.nodeMaterials[ type ];
  25340. if ( materialClass !== undefined ) {
  25341. return new materialClass();
  25342. }
  25343. return super.createMaterialFromType( type );
  25344. }
  25345. }
  25346. class NodeObjectLoader extends ObjectLoader {
  25347. constructor( manager ) {
  25348. super( manager );
  25349. this.nodes = {};
  25350. this.nodeMaterials = {};
  25351. this._nodesJSON = null;
  25352. }
  25353. setNodes( value ) {
  25354. this.nodes = value;
  25355. return this;
  25356. }
  25357. setNodeMaterials( value ) {
  25358. this.nodeMaterials = value;
  25359. return this;
  25360. }
  25361. parse( json, onLoad ) {
  25362. this._nodesJSON = json.nodes;
  25363. const data = super.parse( json, onLoad );
  25364. this._nodesJSON = null; // dispose
  25365. return data;
  25366. }
  25367. parseNodes( json, textures ) {
  25368. if ( json !== undefined ) {
  25369. const loader = new NodeLoader();
  25370. loader.setNodes( this.nodes );
  25371. loader.setTextures( textures );
  25372. return loader.parseNodes( json );
  25373. }
  25374. return {};
  25375. }
  25376. parseMaterials( json, textures ) {
  25377. const materials = {};
  25378. if ( json !== undefined ) {
  25379. const nodes = this.parseNodes( this._nodesJSON, textures );
  25380. const loader = new NodeMaterialLoader();
  25381. loader.setTextures( textures );
  25382. loader.setNodes( nodes );
  25383. loader.setNodeMaterials( this.nodeMaterials );
  25384. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25385. const data = json[ i ];
  25386. materials[ data.uuid ] = loader.parse( data );
  25387. }
  25388. }
  25389. return materials;
  25390. }
  25391. }
  25392. class ClippingGroup extends Group {
  25393. constructor() {
  25394. super();
  25395. this.isClippingGroup = true;
  25396. this.clippingPlanes = [];
  25397. this.enabled = true;
  25398. this.clipIntersection = false;
  25399. this.clipShadows = false;
  25400. }
  25401. }
  25402. 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号