three.webgpu.nodes.js 933 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214
  1. /**
  2. * @license
  3. * Copyright 2010-2024 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. import { Color, Vector2, Vector3, Vector4, Matrix3, Matrix4, EventDispatcher, MathUtils, ColorManagement, SRGBTransfer, NoToneMapping, StaticDrawUsage, InterleavedBuffer, DynamicDrawUsage, InterleavedBufferAttribute, NoColorSpace, UnsignedIntType, IntType, WebGLCoordinateSystem, BackSide, CubeReflectionMapping, CubeRefractionMapping, WebGPUCoordinateSystem, TangentSpaceNormalMap, ObjectSpaceNormalMap, InstancedInterleavedBuffer, InstancedBufferAttribute, DataArrayTexture, FloatType, FramebufferTexture, LinearMipmapLinearFilter, DepthTexture, Material, NormalBlending, PointsMaterial, LineBasicMaterial, LineDashedMaterial, MeshNormalMaterial, WebGLCubeRenderTarget, BoxGeometry, NoBlending, Mesh, Scene, LinearFilter, CubeCamera, CubeTexture, EquirectangularReflectionMapping, EquirectangularRefractionMapping, AddOperation, MixOperation, MultiplyOperation, MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial, Texture, MeshStandardMaterial, MeshPhysicalMaterial, MeshToonMaterial, MeshMatcapMaterial, SpriteMaterial, ShadowMaterial, Uint32BufferAttribute, Uint16BufferAttribute, DoubleSide, DepthStencilFormat, DepthFormat, UnsignedInt248Type, UnsignedByteType, RenderTarget, Plane, Object3D, HalfFloatType, LinearMipMapLinearFilter, OrthographicCamera, BufferGeometry, Float32BufferAttribute, UVMapping, Euler, LinearSRGBColorSpace, LessCompare, VSMShadowMap, RGFormat, SphereGeometry, BufferAttribute, CubeUVReflectionMapping, PerspectiveCamera, RGBAFormat, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, REVISION, SRGBColorSpace, PCFShadowMap as PCFShadowMap$1, 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, BasicShadowMap, 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 } = 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: renderObject.object.matrixWorld.clone()
  88. };
  89. if ( renderObject.object.center ) {
  90. data.center = renderObject.object.center.clone();
  91. }
  92. if ( renderObject.object.morphTargetInfluences ) {
  93. data.morphTargetInfluences = renderObject.object.morphTargetInfluences.slice();
  94. }
  95. if ( renderObject.bundle !== null ) {
  96. data.version = renderObject.bundle.version;
  97. }
  98. if ( data.material.transmission > 0 ) {
  99. const { width, height } = renderObject.context;
  100. data.bufferWidth = width;
  101. data.bufferHeight = height;
  102. }
  103. this.renderObjects.set( renderObject, data );
  104. }
  105. return data;
  106. }
  107. getAttributesData( attributes ) {
  108. const attributesData = {};
  109. for ( const name in attributes ) {
  110. const attribute = attributes[ name ];
  111. attributesData[ name ] = {
  112. version: attribute.version
  113. };
  114. }
  115. return attributesData;
  116. }
  117. containsNode( builder ) {
  118. const material = builder.material;
  119. for ( const property in material ) {
  120. if ( material[ property ] && material[ property ].isNode )
  121. return true;
  122. }
  123. if ( builder.renderer.nodes.modelViewMatrix !== null || builder.renderer.nodes.modelNormalViewMatrix !== null )
  124. return true;
  125. return false;
  126. }
  127. getMaterialData( material ) {
  128. const data = {};
  129. for ( const property of this.refreshUniforms ) {
  130. const value = material[ property ];
  131. if ( value === null || value === undefined ) continue;
  132. if ( typeof value === 'object' && value.clone !== undefined ) {
  133. if ( value.isTexture === true ) {
  134. data[ property ] = { id: value.id, version: value.version };
  135. } else {
  136. data[ property ] = value.clone();
  137. }
  138. } else {
  139. data[ property ] = value;
  140. }
  141. }
  142. return data;
  143. }
  144. equals( renderObject ) {
  145. const { object, material, geometry } = renderObject;
  146. const renderObjectData = this.getRenderObjectData( renderObject );
  147. // world matrix
  148. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  149. renderObjectData.worldMatrix.copy( object.matrixWorld );
  150. return false;
  151. }
  152. // material
  153. const materialData = renderObjectData.material;
  154. for ( const property in materialData ) {
  155. const value = materialData[ property ];
  156. const mtlValue = material[ property ];
  157. if ( value.equals !== undefined ) {
  158. if ( value.equals( mtlValue ) === false ) {
  159. value.copy( mtlValue );
  160. return false;
  161. }
  162. } else if ( mtlValue.isTexture === true ) {
  163. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  164. value.id = mtlValue.id;
  165. value.version = mtlValue.version;
  166. return false;
  167. }
  168. } else if ( value !== mtlValue ) {
  169. materialData[ property ] = mtlValue;
  170. return false;
  171. }
  172. }
  173. if ( materialData.transmission > 0 ) {
  174. const { width, height } = renderObject.context;
  175. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  176. renderObjectData.bufferWidth = width;
  177. renderObjectData.bufferHeight = height;
  178. return false;
  179. }
  180. }
  181. // geometry
  182. const storedGeometryData = renderObjectData.geometry;
  183. const attributes = geometry.attributes;
  184. const storedAttributes = storedGeometryData.attributes;
  185. const storedAttributeNames = Object.keys( storedAttributes );
  186. const currentAttributeNames = Object.keys( attributes );
  187. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  188. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  189. return false;
  190. }
  191. // Compare each attribute
  192. for ( const name of storedAttributeNames ) {
  193. const storedAttributeData = storedAttributes[ name ];
  194. const attribute = attributes[ name ];
  195. if ( attribute === undefined ) {
  196. // Attribute was removed
  197. delete storedAttributes[ name ];
  198. return false;
  199. }
  200. if ( storedAttributeData.version !== attribute.version ) {
  201. storedAttributeData.version = attribute.version;
  202. return false;
  203. }
  204. }
  205. // Check index
  206. const index = geometry.index;
  207. const storedIndexVersion = storedGeometryData.indexVersion;
  208. const currentIndexVersion = index ? index.version : null;
  209. if ( storedIndexVersion !== currentIndexVersion ) {
  210. storedGeometryData.indexVersion = currentIndexVersion;
  211. return false;
  212. }
  213. // Check drawRange
  214. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  215. storedGeometryData.drawRange.start = geometry.drawRange.start;
  216. storedGeometryData.drawRange.count = geometry.drawRange.count;
  217. return false;
  218. }
  219. // morph targets
  220. if ( renderObjectData.morphTargetInfluences ) {
  221. let morphChanged = false;
  222. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  223. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  224. morphChanged = true;
  225. }
  226. }
  227. if ( morphChanged ) return true;
  228. }
  229. // center
  230. if ( renderObjectData.center ) {
  231. if ( renderObjectData.center.equals( object.center ) === false ) {
  232. renderObjectData.center.copy( object.center );
  233. return true;
  234. }
  235. }
  236. // bundle
  237. if ( renderObject.bundle !== null ) {
  238. renderObjectData.version = renderObject.bundle.version;
  239. }
  240. return true;
  241. }
  242. needsRefresh( renderObject, nodeFrame ) {
  243. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) )
  244. return true;
  245. const { renderId } = nodeFrame;
  246. if ( this.renderId !== renderId ) {
  247. this.renderId = renderId;
  248. return true;
  249. }
  250. const isStatic = renderObject.object.static === true;
  251. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  252. if ( isStatic || isBundle )
  253. return false;
  254. const notEqual = this.equals( renderObject ) !== true;
  255. return notEqual;
  256. }
  257. }
  258. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  259. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  260. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  261. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  262. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  263. function cyrb53( value, seed = 0 ) {
  264. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  265. if ( value instanceof Array ) {
  266. for ( let i = 0, val; i < value.length; i ++ ) {
  267. val = value[ i ];
  268. h1 = Math.imul( h1 ^ val, 2654435761 );
  269. h2 = Math.imul( h2 ^ val, 1597334677 );
  270. }
  271. } else {
  272. for ( let i = 0, ch; i < value.length; i ++ ) {
  273. ch = value.charCodeAt( i );
  274. h1 = Math.imul( h1 ^ ch, 2654435761 );
  275. h2 = Math.imul( h2 ^ ch, 1597334677 );
  276. }
  277. }
  278. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  279. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  280. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  281. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  282. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  283. }
  284. const hashString = ( str ) => cyrb53( str );
  285. const hashArray = ( array ) => cyrb53( array );
  286. const hash$1 = ( ...params ) => cyrb53( params );
  287. function getCacheKey$1( object, force = false ) {
  288. const values = [];
  289. if ( object.isNode === true ) {
  290. values.push( object.id );
  291. object = object.getSelf();
  292. }
  293. for ( const { property, childNode } of getNodeChildren( object ) ) {
  294. values.push( values, cyrb53( property.slice( 0, - 4 ) ), childNode.getCacheKey( force ) );
  295. }
  296. return cyrb53( values );
  297. }
  298. function* getNodeChildren( node, toJSON = false ) {
  299. for ( const property in node ) {
  300. // Ignore private properties.
  301. if ( property.startsWith( '_' ) === true ) continue;
  302. const object = node[ property ];
  303. if ( Array.isArray( object ) === true ) {
  304. for ( let i = 0; i < object.length; i ++ ) {
  305. const child = object[ i ];
  306. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  307. yield { property, index: i, childNode: child };
  308. }
  309. }
  310. } else if ( object && object.isNode === true ) {
  311. yield { property, childNode: object };
  312. } else if ( typeof object === 'object' ) {
  313. for ( const subProperty in object ) {
  314. const child = object[ subProperty ];
  315. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  316. yield { property, index: subProperty, childNode: child };
  317. }
  318. }
  319. }
  320. }
  321. }
  322. function getValueType( value ) {
  323. if ( value === undefined || value === null ) return null;
  324. const typeOf = typeof value;
  325. if ( value.isNode === true ) {
  326. return 'node';
  327. } else if ( typeOf === 'number' ) {
  328. return 'float';
  329. } else if ( typeOf === 'boolean' ) {
  330. return 'bool';
  331. } else if ( typeOf === 'string' ) {
  332. return 'string';
  333. } else if ( typeOf === 'function' ) {
  334. return 'shader';
  335. } else if ( value.isVector2 === true ) {
  336. return 'vec2';
  337. } else if ( value.isVector3 === true ) {
  338. return 'vec3';
  339. } else if ( value.isVector4 === true ) {
  340. return 'vec4';
  341. } else if ( value.isMatrix3 === true ) {
  342. return 'mat3';
  343. } else if ( value.isMatrix4 === true ) {
  344. return 'mat4';
  345. } else if ( value.isColor === true ) {
  346. return 'color';
  347. } else if ( value instanceof ArrayBuffer ) {
  348. return 'ArrayBuffer';
  349. }
  350. return null;
  351. }
  352. function getValueFromType( type, ...params ) {
  353. const last4 = type ? type.slice( - 4 ) : undefined;
  354. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  355. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  356. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  357. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  358. }
  359. if ( type === 'color' ) {
  360. return new Color( ...params );
  361. } else if ( last4 === 'vec2' ) {
  362. return new Vector2( ...params );
  363. } else if ( last4 === 'vec3' ) {
  364. return new Vector3( ...params );
  365. } else if ( last4 === 'vec4' ) {
  366. return new Vector4( ...params );
  367. } else if ( last4 === 'mat3' ) {
  368. return new Matrix3( ...params );
  369. } else if ( last4 === 'mat4' ) {
  370. return new Matrix4( ...params );
  371. } else if ( type === 'bool' ) {
  372. return params[ 0 ] || false;
  373. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  374. return params[ 0 ] || 0;
  375. } else if ( type === 'string' ) {
  376. return params[ 0 ] || '';
  377. } else if ( type === 'ArrayBuffer' ) {
  378. return base64ToArrayBuffer( params[ 0 ] );
  379. }
  380. return null;
  381. }
  382. function arrayBufferToBase64( arrayBuffer ) {
  383. let chars = '';
  384. const array = new Uint8Array( arrayBuffer );
  385. for ( let i = 0; i < array.length; i ++ ) {
  386. chars += String.fromCharCode( array[ i ] );
  387. }
  388. return btoa( chars );
  389. }
  390. function base64ToArrayBuffer( base64 ) {
  391. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  392. }
  393. var NodeUtils = /*#__PURE__*/Object.freeze({
  394. __proto__: null,
  395. arrayBufferToBase64: arrayBufferToBase64,
  396. base64ToArrayBuffer: base64ToArrayBuffer,
  397. getCacheKey: getCacheKey$1,
  398. getNodeChildren: getNodeChildren,
  399. getValueFromType: getValueFromType,
  400. getValueType: getValueType,
  401. hash: hash$1,
  402. hashArray: hashArray,
  403. hashString: hashString
  404. });
  405. const NodeShaderStage = {
  406. VERTEX: 'vertex',
  407. FRAGMENT: 'fragment'
  408. };
  409. const NodeUpdateType = {
  410. NONE: 'none',
  411. FRAME: 'frame',
  412. RENDER: 'render',
  413. OBJECT: 'object'
  414. };
  415. const NodeType = {
  416. BOOLEAN: 'bool',
  417. INTEGER: 'int',
  418. FLOAT: 'float',
  419. VECTOR2: 'vec2',
  420. VECTOR3: 'vec3',
  421. VECTOR4: 'vec4',
  422. MATRIX2: 'mat2',
  423. MATRIX3: 'mat3',
  424. MATRIX4: 'mat4'
  425. };
  426. const defaultShaderStages = [ 'fragment', 'vertex' ];
  427. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  428. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  429. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  430. let _nodeId = 0;
  431. class Node extends EventDispatcher {
  432. static get type() {
  433. return 'Node';
  434. }
  435. constructor( nodeType = null ) {
  436. super();
  437. this.nodeType = nodeType;
  438. this.updateType = NodeUpdateType.NONE;
  439. this.updateBeforeType = NodeUpdateType.NONE;
  440. this.updateAfterType = NodeUpdateType.NONE;
  441. this.uuid = MathUtils.generateUUID();
  442. this.version = 0;
  443. this._cacheKey = null;
  444. this._cacheKeyVersion = 0;
  445. this.global = false;
  446. this.isNode = true;
  447. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  448. }
  449. set needsUpdate( value ) {
  450. if ( value === true ) {
  451. this.version ++;
  452. }
  453. }
  454. get type() {
  455. return this.constructor.type;
  456. }
  457. onUpdate( callback, updateType ) {
  458. this.updateType = updateType;
  459. this.update = callback.bind( this.getSelf() );
  460. return this;
  461. }
  462. onFrameUpdate( callback ) {
  463. return this.onUpdate( callback, NodeUpdateType.FRAME );
  464. }
  465. onRenderUpdate( callback ) {
  466. return this.onUpdate( callback, NodeUpdateType.RENDER );
  467. }
  468. onObjectUpdate( callback ) {
  469. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  470. }
  471. onReference( callback ) {
  472. this.updateReference = callback.bind( this.getSelf() );
  473. return this;
  474. }
  475. getSelf() {
  476. // Returns non-node object.
  477. return this.self || this;
  478. }
  479. updateReference( /*state*/ ) {
  480. return this;
  481. }
  482. isGlobal( /*builder*/ ) {
  483. return this.global;
  484. }
  485. * getChildren() {
  486. for ( const { childNode } of getNodeChildren( this ) ) {
  487. yield childNode;
  488. }
  489. }
  490. dispose() {
  491. this.dispatchEvent( { type: 'dispose' } );
  492. }
  493. traverse( callback ) {
  494. callback( this );
  495. for ( const childNode of this.getChildren() ) {
  496. childNode.traverse( callback );
  497. }
  498. }
  499. getCacheKey( force = false ) {
  500. force = force || this.version !== this._cacheKeyVersion;
  501. if ( force === true || this._cacheKey === null ) {
  502. this._cacheKey = getCacheKey$1( this, force );
  503. this._cacheKeyVersion = this.version;
  504. }
  505. return this._cacheKey;
  506. }
  507. getScope() {
  508. return this;
  509. }
  510. getHash( /*builder*/ ) {
  511. return this.uuid;
  512. }
  513. getUpdateType() {
  514. return this.updateType;
  515. }
  516. getUpdateBeforeType() {
  517. return this.updateBeforeType;
  518. }
  519. getUpdateAfterType() {
  520. return this.updateAfterType;
  521. }
  522. getElementType( builder ) {
  523. const type = this.getNodeType( builder );
  524. const elementType = builder.getElementType( type );
  525. return elementType;
  526. }
  527. getNodeType( builder ) {
  528. const nodeProperties = builder.getNodeProperties( this );
  529. if ( nodeProperties.outputNode ) {
  530. return nodeProperties.outputNode.getNodeType( builder );
  531. }
  532. return this.nodeType;
  533. }
  534. getShared( builder ) {
  535. const hash = this.getHash( builder );
  536. const nodeFromHash = builder.getNodeFromHash( hash );
  537. return nodeFromHash || this;
  538. }
  539. setup( builder ) {
  540. const nodeProperties = builder.getNodeProperties( this );
  541. let index = 0;
  542. for ( const childNode of this.getChildren() ) {
  543. nodeProperties[ 'node' + index ++ ] = childNode;
  544. }
  545. // return a outputNode if exists
  546. return null;
  547. }
  548. analyze( builder ) {
  549. const usageCount = builder.increaseUsage( this );
  550. if ( usageCount === 1 ) {
  551. // node flow children
  552. const nodeProperties = builder.getNodeProperties( this );
  553. for ( const childNode of Object.values( nodeProperties ) ) {
  554. if ( childNode && childNode.isNode === true ) {
  555. childNode.build( builder );
  556. }
  557. }
  558. }
  559. }
  560. generate( builder, output ) {
  561. const { outputNode } = builder.getNodeProperties( this );
  562. if ( outputNode && outputNode.isNode === true ) {
  563. return outputNode.build( builder, output );
  564. }
  565. }
  566. updateBefore( /*frame*/ ) {
  567. console.warn( 'Abstract function.' );
  568. }
  569. updateAfter( /*frame*/ ) {
  570. console.warn( 'Abstract function.' );
  571. }
  572. update( /*frame*/ ) {
  573. console.warn( 'Abstract function.' );
  574. }
  575. build( builder, output = null ) {
  576. const refNode = this.getShared( builder );
  577. if ( this !== refNode ) {
  578. return refNode.build( builder, output );
  579. }
  580. builder.addNode( this );
  581. builder.addChain( this );
  582. /* Build stages expected results:
  583. - "setup" -> Node
  584. - "analyze" -> null
  585. - "generate" -> String
  586. */
  587. let result = null;
  588. const buildStage = builder.getBuildStage();
  589. if ( buildStage === 'setup' ) {
  590. this.updateReference( builder );
  591. const properties = builder.getNodeProperties( this );
  592. if ( properties.initialized !== true ) {
  593. const stackNodesBeforeSetup = builder.stack.nodes.length;
  594. properties.initialized = true;
  595. properties.outputNode = this.setup( builder );
  596. if ( properties.outputNode !== null && builder.stack.nodes.length !== stackNodesBeforeSetup ) ;
  597. for ( const childNode of Object.values( properties ) ) {
  598. if ( childNode && childNode.isNode === true ) {
  599. childNode.build( builder );
  600. }
  601. }
  602. }
  603. } else if ( buildStage === 'analyze' ) {
  604. this.analyze( builder );
  605. } else if ( buildStage === 'generate' ) {
  606. const isGenerateOnce = this.generate.length === 1;
  607. if ( isGenerateOnce ) {
  608. const type = this.getNodeType( builder );
  609. const nodeData = builder.getDataFromNode( this );
  610. result = nodeData.snippet;
  611. if ( result === undefined ) {
  612. result = this.generate( builder ) || '';
  613. nodeData.snippet = result;
  614. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  615. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  616. }
  617. result = builder.format( result, type, output );
  618. } else {
  619. result = this.generate( builder, output ) || '';
  620. }
  621. }
  622. builder.removeChain( this );
  623. builder.addSequentialNode( this );
  624. return result;
  625. }
  626. getSerializeChildren() {
  627. return getNodeChildren( this );
  628. }
  629. serialize( json ) {
  630. const nodeChildren = this.getSerializeChildren();
  631. const inputNodes = {};
  632. for ( const { property, index, childNode } of nodeChildren ) {
  633. if ( index !== undefined ) {
  634. if ( inputNodes[ property ] === undefined ) {
  635. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  636. }
  637. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  638. } else {
  639. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  640. }
  641. }
  642. if ( Object.keys( inputNodes ).length > 0 ) {
  643. json.inputNodes = inputNodes;
  644. }
  645. }
  646. deserialize( json ) {
  647. if ( json.inputNodes !== undefined ) {
  648. const nodes = json.meta.nodes;
  649. for ( const property in json.inputNodes ) {
  650. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  651. const inputArray = [];
  652. for ( const uuid of json.inputNodes[ property ] ) {
  653. inputArray.push( nodes[ uuid ] );
  654. }
  655. this[ property ] = inputArray;
  656. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  657. const inputObject = {};
  658. for ( const subProperty in json.inputNodes[ property ] ) {
  659. const uuid = json.inputNodes[ property ][ subProperty ];
  660. inputObject[ subProperty ] = nodes[ uuid ];
  661. }
  662. this[ property ] = inputObject;
  663. } else {
  664. const uuid = json.inputNodes[ property ];
  665. this[ property ] = nodes[ uuid ];
  666. }
  667. }
  668. }
  669. }
  670. toJSON( meta ) {
  671. const { uuid, type } = this;
  672. const isRoot = ( meta === undefined || typeof meta === 'string' );
  673. if ( isRoot ) {
  674. meta = {
  675. textures: {},
  676. images: {},
  677. nodes: {}
  678. };
  679. }
  680. // serialize
  681. let data = meta.nodes[ uuid ];
  682. if ( data === undefined ) {
  683. data = {
  684. uuid,
  685. type,
  686. meta,
  687. metadata: {
  688. version: 4.6,
  689. type: 'Node',
  690. generator: 'Node.toJSON'
  691. }
  692. };
  693. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  694. this.serialize( data );
  695. delete data.meta;
  696. }
  697. // TODO: Copied from Object3D.toJSON
  698. function extractFromCache( cache ) {
  699. const values = [];
  700. for ( const key in cache ) {
  701. const data = cache[ key ];
  702. delete data.metadata;
  703. values.push( data );
  704. }
  705. return values;
  706. }
  707. if ( isRoot ) {
  708. const textures = extractFromCache( meta.textures );
  709. const images = extractFromCache( meta.images );
  710. const nodes = extractFromCache( meta.nodes );
  711. if ( textures.length > 0 ) data.textures = textures;
  712. if ( images.length > 0 ) data.images = images;
  713. if ( nodes.length > 0 ) data.nodes = nodes;
  714. }
  715. return data;
  716. }
  717. }
  718. class ArrayElementNode extends Node {
  719. static get type() {
  720. return 'ArrayElementNode';
  721. } // @TODO: If extending from TempNode it breaks webgpu_compute
  722. constructor( node, indexNode ) {
  723. super();
  724. this.node = node;
  725. this.indexNode = indexNode;
  726. this.isArrayElementNode = true;
  727. }
  728. getNodeType( builder ) {
  729. return this.node.getElementType( builder );
  730. }
  731. generate( builder ) {
  732. const nodeSnippet = this.node.build( builder );
  733. const indexSnippet = this.indexNode.build( builder, 'uint' );
  734. return `${nodeSnippet}[ ${indexSnippet} ]`;
  735. }
  736. }
  737. class ConvertNode extends Node {
  738. static get type() {
  739. return 'ConvertNode';
  740. }
  741. constructor( node, convertTo ) {
  742. super();
  743. this.node = node;
  744. this.convertTo = convertTo;
  745. }
  746. getNodeType( builder ) {
  747. const requestType = this.node.getNodeType( builder );
  748. let convertTo = null;
  749. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  750. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  751. convertTo = overloadingType;
  752. }
  753. }
  754. return convertTo;
  755. }
  756. serialize( data ) {
  757. super.serialize( data );
  758. data.convertTo = this.convertTo;
  759. }
  760. deserialize( data ) {
  761. super.deserialize( data );
  762. this.convertTo = data.convertTo;
  763. }
  764. generate( builder, output ) {
  765. const node = this.node;
  766. const type = this.getNodeType( builder );
  767. const snippet = node.build( builder, type );
  768. return builder.format( snippet, type, output );
  769. }
  770. }
  771. class TempNode extends Node {
  772. static get type() {
  773. return 'TempNode';
  774. }
  775. constructor( type ) {
  776. super( type );
  777. this.isTempNode = true;
  778. }
  779. hasDependencies( builder ) {
  780. return builder.getDataFromNode( this ).usageCount > 1;
  781. }
  782. build( builder, output ) {
  783. const buildStage = builder.getBuildStage();
  784. if ( buildStage === 'generate' ) {
  785. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  786. const nodeData = builder.getDataFromNode( this );
  787. if ( nodeData.propertyName !== undefined ) {
  788. return builder.format( nodeData.propertyName, type, output );
  789. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  790. const snippet = super.build( builder, type );
  791. const nodeVar = builder.getVarFromNode( this, null, type );
  792. const propertyName = builder.getPropertyName( nodeVar );
  793. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  794. nodeData.snippet = snippet;
  795. nodeData.propertyName = propertyName;
  796. return builder.format( nodeData.propertyName, type, output );
  797. }
  798. }
  799. return super.build( builder, output );
  800. }
  801. }
  802. class JoinNode extends TempNode {
  803. static get type() {
  804. return 'JoinNode';
  805. }
  806. constructor( nodes = [], nodeType = null ) {
  807. super( nodeType );
  808. this.nodes = nodes;
  809. }
  810. getNodeType( builder ) {
  811. if ( this.nodeType !== null ) {
  812. return builder.getVectorType( this.nodeType );
  813. }
  814. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  815. }
  816. generate( builder, output ) {
  817. const type = this.getNodeType( builder );
  818. const nodes = this.nodes;
  819. const primitiveType = builder.getComponentType( type );
  820. const snippetValues = [];
  821. for ( const input of nodes ) {
  822. let inputSnippet = input.build( builder );
  823. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  824. if ( inputPrimitiveType !== primitiveType ) {
  825. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  826. }
  827. snippetValues.push( inputSnippet );
  828. }
  829. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  830. return builder.format( snippet, type, output );
  831. }
  832. }
  833. const stringVectorComponents = vectorComponents.join( '' );
  834. class SplitNode extends Node {
  835. static get type() {
  836. return 'SplitNode';
  837. }
  838. constructor( node, components = 'x' ) {
  839. super();
  840. this.node = node;
  841. this.components = components;
  842. this.isSplitNode = true;
  843. }
  844. getVectorLength() {
  845. let vectorLength = this.components.length;
  846. for ( const c of this.components ) {
  847. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  848. }
  849. return vectorLength;
  850. }
  851. getComponentType( builder ) {
  852. return builder.getComponentType( this.node.getNodeType( builder ) );
  853. }
  854. getNodeType( builder ) {
  855. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  856. }
  857. generate( builder, output ) {
  858. const node = this.node;
  859. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  860. let snippet = null;
  861. if ( nodeTypeLength > 1 ) {
  862. let type = null;
  863. const componentsLength = this.getVectorLength();
  864. if ( componentsLength >= nodeTypeLength ) {
  865. // needed expand the input node
  866. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  867. }
  868. const nodeSnippet = node.build( builder, type );
  869. if ( this.components.length === nodeTypeLength && this.components === stringVectorComponents.slice( 0, this.components.length ) ) {
  870. // unnecessary swizzle
  871. snippet = builder.format( nodeSnippet, type, output );
  872. } else {
  873. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  874. }
  875. } else {
  876. // ignore .components if .node returns float/integer
  877. snippet = node.build( builder, output );
  878. }
  879. return snippet;
  880. }
  881. serialize( data ) {
  882. super.serialize( data );
  883. data.components = this.components;
  884. }
  885. deserialize( data ) {
  886. super.deserialize( data );
  887. this.components = data.components;
  888. }
  889. }
  890. class SetNode extends TempNode {
  891. static get type() {
  892. return 'SetNode';
  893. }
  894. constructor( sourceNode, components, targetNode ) {
  895. super();
  896. this.sourceNode = sourceNode;
  897. this.components = components;
  898. this.targetNode = targetNode;
  899. }
  900. getNodeType( builder ) {
  901. return this.sourceNode.getNodeType( builder );
  902. }
  903. generate( builder ) {
  904. const { sourceNode, components, targetNode } = this;
  905. const sourceType = this.getNodeType( builder );
  906. const targetType = builder.getTypeFromLength( components.length, targetNode.getNodeType( builder ) );
  907. const targetSnippet = targetNode.build( builder, targetType );
  908. const sourceSnippet = sourceNode.build( builder, sourceType );
  909. const length = builder.getTypeLength( sourceType );
  910. const snippetValues = [];
  911. for ( let i = 0; i < length; i ++ ) {
  912. const component = vectorComponents[ i ];
  913. if ( component === components[ 0 ] ) {
  914. snippetValues.push( targetSnippet );
  915. i += components.length - 1;
  916. } else {
  917. snippetValues.push( sourceSnippet + '.' + component );
  918. }
  919. }
  920. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  921. }
  922. }
  923. class FlipNode extends TempNode {
  924. static get type() {
  925. return 'FlipNode';
  926. }
  927. constructor( sourceNode, components ) {
  928. super();
  929. this.sourceNode = sourceNode;
  930. this.components = components;
  931. }
  932. getNodeType( builder ) {
  933. return this.sourceNode.getNodeType( builder );
  934. }
  935. generate( builder ) {
  936. const { components, sourceNode } = this;
  937. const sourceType = this.getNodeType( builder );
  938. const sourceSnippet = sourceNode.build( builder );
  939. const sourceCache = builder.getVarFromNode( this );
  940. const sourceProperty = builder.getPropertyName( sourceCache );
  941. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  942. const length = builder.getTypeLength( sourceType );
  943. const snippetValues = [];
  944. let componentIndex = 0;
  945. for ( let i = 0; i < length; i ++ ) {
  946. const component = vectorComponents[ i ];
  947. if ( component === components[ componentIndex ] ) {
  948. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  949. componentIndex ++;
  950. } else {
  951. snippetValues.push( sourceProperty + '.' + component );
  952. }
  953. }
  954. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  955. }
  956. }
  957. class InputNode extends Node {
  958. static get type() {
  959. return 'InputNode';
  960. }
  961. constructor( value, nodeType = null ) {
  962. super( nodeType );
  963. this.isInputNode = true;
  964. this.value = value;
  965. this.precision = null;
  966. }
  967. getNodeType( /*builder*/ ) {
  968. if ( this.nodeType === null ) {
  969. return getValueType( this.value );
  970. }
  971. return this.nodeType;
  972. }
  973. getInputType( builder ) {
  974. return this.getNodeType( builder );
  975. }
  976. setPrecision( precision ) {
  977. this.precision = precision;
  978. return this;
  979. }
  980. serialize( data ) {
  981. super.serialize( data );
  982. data.value = this.value;
  983. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  984. data.valueType = getValueType( this.value );
  985. data.nodeType = this.nodeType;
  986. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  987. data.precision = this.precision;
  988. }
  989. deserialize( data ) {
  990. super.deserialize( data );
  991. this.nodeType = data.nodeType;
  992. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  993. this.precision = data.precision || null;
  994. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  995. }
  996. generate( /*builder, output*/ ) {
  997. console.warn( 'Abstract function.' );
  998. }
  999. }
  1000. class ConstNode extends InputNode {
  1001. static get type() {
  1002. return 'ConstNode';
  1003. }
  1004. constructor( value, nodeType = null ) {
  1005. super( value, nodeType );
  1006. this.isConstNode = true;
  1007. }
  1008. generateConst( builder ) {
  1009. return builder.generateConst( this.getNodeType( builder ), this.value );
  1010. }
  1011. generate( builder, output ) {
  1012. const type = this.getNodeType( builder );
  1013. return builder.format( this.generateConst( builder ), type, output );
  1014. }
  1015. }
  1016. //
  1017. let currentStack = null;
  1018. const NodeElements = new Map();
  1019. function addMethodChaining( name, nodeElement ) {
  1020. if ( NodeElements.has( name ) ) {
  1021. console.warn( `Redefinition of method chaining ${ name }` );
  1022. return;
  1023. }
  1024. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  1025. NodeElements.set( name, nodeElement );
  1026. }
  1027. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  1028. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  1029. const shaderNodeHandler = {
  1030. setup( NodeClosure, params ) {
  1031. const inputs = params.shift();
  1032. return NodeClosure( nodeObjects( inputs ), ...params );
  1033. },
  1034. get( node, prop, nodeObj ) {
  1035. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1036. if ( node.isStackNode !== true && prop === 'assign' ) {
  1037. return ( ...params ) => {
  1038. currentStack.assign( nodeObj, ...params );
  1039. return nodeObj;
  1040. };
  1041. } else if ( NodeElements.has( prop ) ) {
  1042. const nodeElement = NodeElements.get( prop );
  1043. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  1044. } else if ( prop === 'self' ) {
  1045. return node;
  1046. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  1047. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  1048. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  1049. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  1050. // accessing properties ( swizzle )
  1051. prop = parseSwizzle( prop );
  1052. return nodeObject( new SplitNode( nodeObj, prop ) );
  1053. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1054. // set properties ( swizzle ) and sort to xyzw sequence
  1055. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  1056. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  1057. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1058. // set properties ( swizzle ) and sort to xyzw sequence
  1059. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  1060. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  1061. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  1062. // accessing property
  1063. if ( prop === 'width' ) prop = 'x';
  1064. else if ( prop === 'height' ) prop = 'y';
  1065. else if ( prop === 'depth' ) prop = 'z';
  1066. return nodeObject( new SplitNode( node, prop ) );
  1067. } else if ( /^\d+$/.test( prop ) === true ) {
  1068. // accessing array
  1069. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  1070. }
  1071. }
  1072. return Reflect.get( node, prop, nodeObj );
  1073. },
  1074. set( node, prop, value, nodeObj ) {
  1075. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1076. // setting properties
  1077. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  1078. nodeObj[ prop ].assign( value );
  1079. return true;
  1080. }
  1081. }
  1082. return Reflect.set( node, prop, value, nodeObj );
  1083. }
  1084. };
  1085. const nodeObjectsCacheMap = new WeakMap();
  1086. const nodeBuilderFunctionsCacheMap = new WeakMap();
  1087. const ShaderNodeObject = function ( obj, altType = null ) {
  1088. const type = getValueType( obj );
  1089. if ( type === 'node' ) {
  1090. let nodeObject = nodeObjectsCacheMap.get( obj );
  1091. if ( nodeObject === undefined ) {
  1092. nodeObject = new Proxy( obj, shaderNodeHandler );
  1093. nodeObjectsCacheMap.set( obj, nodeObject );
  1094. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  1095. }
  1096. return nodeObject;
  1097. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  1098. return nodeObject( getConstNode( obj, altType ) );
  1099. } else if ( type === 'shader' ) {
  1100. return Fn( obj );
  1101. }
  1102. return obj;
  1103. };
  1104. const ShaderNodeObjects = function ( objects, altType = null ) {
  1105. for ( const name in objects ) {
  1106. objects[ name ] = nodeObject( objects[ name ], altType );
  1107. }
  1108. return objects;
  1109. };
  1110. const ShaderNodeArray = function ( array, altType = null ) {
  1111. const len = array.length;
  1112. for ( let i = 0; i < len; i ++ ) {
  1113. array[ i ] = nodeObject( array[ i ], altType );
  1114. }
  1115. return array;
  1116. };
  1117. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  1118. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  1119. if ( scope === null ) {
  1120. return ( ...params ) => {
  1121. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  1122. };
  1123. } else if ( factor !== null ) {
  1124. factor = nodeObject( factor );
  1125. return ( ...params ) => {
  1126. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  1127. };
  1128. } else {
  1129. return ( ...params ) => {
  1130. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  1131. };
  1132. }
  1133. };
  1134. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  1135. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  1136. };
  1137. class ShaderCallNodeInternal extends Node {
  1138. constructor( shaderNode, inputNodes ) {
  1139. super();
  1140. this.shaderNode = shaderNode;
  1141. this.inputNodes = inputNodes;
  1142. }
  1143. getNodeType( builder ) {
  1144. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  1145. }
  1146. call( builder ) {
  1147. const { shaderNode, inputNodes } = this;
  1148. const properties = builder.getNodeProperties( shaderNode );
  1149. if ( properties.onceOutput ) return properties.onceOutput;
  1150. //
  1151. let result = null;
  1152. if ( shaderNode.layout ) {
  1153. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  1154. if ( functionNodesCacheMap === undefined ) {
  1155. functionNodesCacheMap = new WeakMap();
  1156. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  1157. }
  1158. let functionNode = functionNodesCacheMap.get( shaderNode );
  1159. if ( functionNode === undefined ) {
  1160. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  1161. functionNodesCacheMap.set( shaderNode, functionNode );
  1162. }
  1163. if ( builder.currentFunctionNode !== null ) {
  1164. builder.currentFunctionNode.includes.push( functionNode );
  1165. }
  1166. result = nodeObject( functionNode.call( inputNodes ) );
  1167. } else {
  1168. const jsFunc = shaderNode.jsFunc;
  1169. const outputNode = inputNodes !== null ? jsFunc( inputNodes, builder ) : jsFunc( builder );
  1170. result = nodeObject( outputNode );
  1171. }
  1172. if ( shaderNode.once ) {
  1173. properties.onceOutput = result;
  1174. }
  1175. return result;
  1176. }
  1177. getOutputNode( builder ) {
  1178. const properties = builder.getNodeProperties( this );
  1179. if ( properties.outputNode === null ) {
  1180. properties.outputNode = this.setupOutput( builder );
  1181. }
  1182. return properties.outputNode;
  1183. }
  1184. setup( builder ) {
  1185. return this.getOutputNode( builder );
  1186. }
  1187. setupOutput( builder ) {
  1188. builder.addStack();
  1189. builder.stack.outputNode = this.call( builder );
  1190. return builder.removeStack();
  1191. }
  1192. generate( builder, output ) {
  1193. const outputNode = this.getOutputNode( builder );
  1194. return outputNode.build( builder, output );
  1195. }
  1196. }
  1197. class ShaderNodeInternal extends Node {
  1198. constructor( jsFunc, nodeType ) {
  1199. super( nodeType );
  1200. this.jsFunc = jsFunc;
  1201. this.layout = null;
  1202. this.global = true;
  1203. this.once = false;
  1204. }
  1205. setLayout( layout ) {
  1206. this.layout = layout;
  1207. return this;
  1208. }
  1209. call( inputs = null ) {
  1210. nodeObjects( inputs );
  1211. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  1212. }
  1213. setup() {
  1214. return this.call();
  1215. }
  1216. }
  1217. const bools = [ false, true ];
  1218. const uints = [ 0, 1, 2, 3 ];
  1219. const ints = [ - 1, - 2 ];
  1220. const floats = [ 0.5, 1.5, 1 / 3, 1e-6, 1e6, Math.PI, Math.PI * 2, 1 / Math.PI, 2 / Math.PI, 1 / ( Math.PI * 2 ), Math.PI / 2 ];
  1221. const boolsCacheMap = new Map();
  1222. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  1223. const uintsCacheMap = new Map();
  1224. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  1225. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  1226. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  1227. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  1228. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  1229. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  1230. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  1231. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  1232. const getConstNode = ( value, type ) => {
  1233. if ( constNodesCacheMap.has( value ) ) {
  1234. return constNodesCacheMap.get( value );
  1235. } else if ( value.isNode === true ) {
  1236. return value;
  1237. } else {
  1238. return new ConstNode( value, type );
  1239. }
  1240. };
  1241. const safeGetNodeType = ( node ) => {
  1242. try {
  1243. return node.getNodeType();
  1244. } catch ( _ ) {
  1245. return undefined;
  1246. }
  1247. };
  1248. const ConvertType = function ( type, cacheMap = null ) {
  1249. return ( ...params ) => {
  1250. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  1251. params = [ getValueFromType( type, ...params ) ];
  1252. }
  1253. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  1254. return nodeObject( cacheMap.get( params[ 0 ] ) );
  1255. }
  1256. if ( params.length === 1 ) {
  1257. const node = getConstNode( params[ 0 ], type );
  1258. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  1259. return nodeObject( new ConvertNode( node, type ) );
  1260. }
  1261. const nodes = params.map( param => getConstNode( param ) );
  1262. return nodeObject( new JoinNode( nodes, type ) );
  1263. };
  1264. };
  1265. // exports
  1266. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  1267. // utils
  1268. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  1269. // shader node base
  1270. function ShaderNode( jsFunc, nodeType ) {
  1271. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  1272. }
  1273. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  1274. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  1275. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  1276. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  1277. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  1278. const Fn = ( jsFunc, nodeType ) => {
  1279. const shaderNode = new ShaderNode( jsFunc, nodeType );
  1280. const fn = ( ...params ) => {
  1281. let inputs;
  1282. nodeObjects( params );
  1283. if ( params[ 0 ] && params[ 0 ].isNode ) {
  1284. inputs = [ ...params ];
  1285. } else {
  1286. inputs = params[ 0 ];
  1287. }
  1288. return shaderNode.call( inputs );
  1289. };
  1290. fn.shaderNode = shaderNode;
  1291. fn.setLayout = ( layout ) => {
  1292. shaderNode.setLayout( layout );
  1293. return fn;
  1294. };
  1295. fn.once = () => {
  1296. shaderNode.once = true;
  1297. return fn;
  1298. };
  1299. return fn;
  1300. };
  1301. const tslFn = ( ...params ) => { // @deprecated, r168
  1302. console.warn( 'TSL.ShaderNode: tslFn() has been renamed to Fn().' );
  1303. return Fn( ...params );
  1304. };
  1305. //
  1306. addMethodChaining( 'toGlobal', ( node ) => {
  1307. node.global = true;
  1308. return node;
  1309. } );
  1310. //
  1311. const setCurrentStack = ( stack ) => {
  1312. currentStack = stack;
  1313. };
  1314. const getCurrentStack = () => currentStack;
  1315. const If = ( ...params ) => currentStack.If( ...params );
  1316. function append( node ) {
  1317. if ( currentStack ) currentStack.add( node );
  1318. return node;
  1319. }
  1320. addMethodChaining( 'append', append );
  1321. // types
  1322. const color = new ConvertType( 'color' );
  1323. const float = new ConvertType( 'float', cacheMaps.float );
  1324. const int = new ConvertType( 'int', cacheMaps.ints );
  1325. const uint = new ConvertType( 'uint', cacheMaps.uint );
  1326. const bool = new ConvertType( 'bool', cacheMaps.bool );
  1327. const vec2 = new ConvertType( 'vec2' );
  1328. const ivec2 = new ConvertType( 'ivec2' );
  1329. const uvec2 = new ConvertType( 'uvec2' );
  1330. const bvec2 = new ConvertType( 'bvec2' );
  1331. const vec3 = new ConvertType( 'vec3' );
  1332. const ivec3 = new ConvertType( 'ivec3' );
  1333. const uvec3 = new ConvertType( 'uvec3' );
  1334. const bvec3 = new ConvertType( 'bvec3' );
  1335. const vec4 = new ConvertType( 'vec4' );
  1336. const ivec4 = new ConvertType( 'ivec4' );
  1337. const uvec4 = new ConvertType( 'uvec4' );
  1338. const bvec4 = new ConvertType( 'bvec4' );
  1339. const mat2 = new ConvertType( 'mat2' );
  1340. const mat3 = new ConvertType( 'mat3' );
  1341. const mat4 = new ConvertType( 'mat4' );
  1342. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  1343. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  1344. addMethodChaining( 'toColor', color );
  1345. addMethodChaining( 'toFloat', float );
  1346. addMethodChaining( 'toInt', int );
  1347. addMethodChaining( 'toUint', uint );
  1348. addMethodChaining( 'toBool', bool );
  1349. addMethodChaining( 'toVec2', vec2 );
  1350. addMethodChaining( 'toIVec2', ivec2 );
  1351. addMethodChaining( 'toUVec2', uvec2 );
  1352. addMethodChaining( 'toBVec2', bvec2 );
  1353. addMethodChaining( 'toVec3', vec3 );
  1354. addMethodChaining( 'toIVec3', ivec3 );
  1355. addMethodChaining( 'toUVec3', uvec3 );
  1356. addMethodChaining( 'toBVec3', bvec3 );
  1357. addMethodChaining( 'toVec4', vec4 );
  1358. addMethodChaining( 'toIVec4', ivec4 );
  1359. addMethodChaining( 'toUVec4', uvec4 );
  1360. addMethodChaining( 'toBVec4', bvec4 );
  1361. addMethodChaining( 'toMat2', mat2 );
  1362. addMethodChaining( 'toMat3', mat3 );
  1363. addMethodChaining( 'toMat4', mat4 );
  1364. // basic nodes
  1365. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode );
  1366. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  1367. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  1368. addMethodChaining( 'element', element );
  1369. addMethodChaining( 'convert', convert );
  1370. class UniformGroupNode extends Node {
  1371. static get type() {
  1372. return 'UniformGroupNode';
  1373. }
  1374. constructor( name, shared = false, order = 1 ) {
  1375. super( 'string' );
  1376. this.name = name;
  1377. this.version = 0;
  1378. this.shared = shared;
  1379. this.order = order;
  1380. this.isUniformGroup = true;
  1381. }
  1382. set needsUpdate( value ) {
  1383. if ( value === true ) this.version ++;
  1384. }
  1385. serialize( data ) {
  1386. super.serialize( data );
  1387. data.name = this.name;
  1388. data.version = this.version;
  1389. data.shared = this.shared;
  1390. }
  1391. deserialize( data ) {
  1392. super.deserialize( data );
  1393. this.name = data.name;
  1394. this.version = data.version;
  1395. this.shared = data.shared;
  1396. }
  1397. }
  1398. const uniformGroup = ( name ) => new UniformGroupNode( name );
  1399. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  1400. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  1401. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  1402. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  1403. class UniformNode extends InputNode {
  1404. static get type() {
  1405. return 'UniformNode';
  1406. }
  1407. constructor( value, nodeType = null ) {
  1408. super( value, nodeType );
  1409. this.isUniformNode = true;
  1410. this.name = '';
  1411. this.groupNode = objectGroup;
  1412. }
  1413. label( name ) {
  1414. this.name = name;
  1415. return this;
  1416. }
  1417. setGroup( group ) {
  1418. this.groupNode = group;
  1419. return this;
  1420. }
  1421. getGroup() {
  1422. return this.groupNode;
  1423. }
  1424. getUniformHash( builder ) {
  1425. return this.getHash( builder );
  1426. }
  1427. onUpdate( callback, updateType ) {
  1428. const self = this.getSelf();
  1429. callback = callback.bind( self );
  1430. return super.onUpdate( ( frame ) => {
  1431. const value = callback( frame, self );
  1432. if ( value !== undefined ) {
  1433. this.value = value;
  1434. }
  1435. }, updateType );
  1436. }
  1437. generate( builder, output ) {
  1438. const type = this.getNodeType( builder );
  1439. const hash = this.getUniformHash( builder );
  1440. let sharedNode = builder.getNodeFromHash( hash );
  1441. if ( sharedNode === undefined ) {
  1442. builder.setHashNode( this, hash );
  1443. sharedNode = this;
  1444. }
  1445. const sharedNodeType = sharedNode.getInputType( builder );
  1446. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  1447. const propertyName = builder.getPropertyName( nodeUniform );
  1448. if ( builder.context.label !== undefined ) delete builder.context.label;
  1449. return builder.format( propertyName, type, output );
  1450. }
  1451. }
  1452. const uniform = ( arg1, arg2 ) => {
  1453. const nodeType = getConstNodeType( arg2 || arg1 );
  1454. // @TODO: get ConstNode from .traverse() in the future
  1455. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  1456. return nodeObject( new UniformNode( value, nodeType ) );
  1457. };
  1458. class PropertyNode extends Node {
  1459. static get type() {
  1460. return 'PropertyNode';
  1461. }
  1462. constructor( nodeType, name = null, varying = false ) {
  1463. super( nodeType );
  1464. this.name = name;
  1465. this.varying = varying;
  1466. this.isPropertyNode = true;
  1467. }
  1468. getHash( builder ) {
  1469. return this.name || super.getHash( builder );
  1470. }
  1471. isGlobal( /*builder*/ ) {
  1472. return true;
  1473. }
  1474. generate( builder ) {
  1475. let nodeVar;
  1476. if ( this.varying === true ) {
  1477. nodeVar = builder.getVaryingFromNode( this, this.name );
  1478. nodeVar.needsInterpolation = true;
  1479. } else {
  1480. nodeVar = builder.getVarFromNode( this, this.name );
  1481. }
  1482. return builder.getPropertyName( nodeVar );
  1483. }
  1484. }
  1485. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  1486. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  1487. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  1488. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  1489. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  1490. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  1491. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  1492. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  1493. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  1494. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  1495. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  1496. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  1497. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  1498. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  1499. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  1500. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  1501. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  1502. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  1503. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  1504. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  1505. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  1506. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  1507. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  1508. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  1509. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  1510. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  1511. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  1512. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  1513. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  1514. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  1515. class AssignNode extends TempNode {
  1516. static get type() {
  1517. return 'AssignNode';
  1518. }
  1519. constructor( targetNode, sourceNode ) {
  1520. super();
  1521. this.targetNode = targetNode;
  1522. this.sourceNode = sourceNode;
  1523. }
  1524. hasDependencies() {
  1525. return false;
  1526. }
  1527. getNodeType( builder, output ) {
  1528. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  1529. }
  1530. needsSplitAssign( builder ) {
  1531. const { targetNode } = this;
  1532. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  1533. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  1534. const assignDiferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  1535. return assignDiferentVector;
  1536. }
  1537. return false;
  1538. }
  1539. generate( builder, output ) {
  1540. const { targetNode, sourceNode } = this;
  1541. const needsSplitAssign = this.needsSplitAssign( builder );
  1542. const targetType = targetNode.getNodeType( builder );
  1543. const target = targetNode.context( { assign: true } ).build( builder );
  1544. const source = sourceNode.build( builder, targetType );
  1545. const sourceType = sourceNode.getNodeType( builder );
  1546. const nodeData = builder.getDataFromNode( this );
  1547. //
  1548. let snippet;
  1549. if ( nodeData.initialized === true ) {
  1550. if ( output !== 'void' ) {
  1551. snippet = target;
  1552. }
  1553. } else if ( needsSplitAssign ) {
  1554. const sourceVar = builder.getVarFromNode( this, null, targetType );
  1555. const sourceProperty = builder.getPropertyName( sourceVar );
  1556. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  1557. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  1558. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  1559. const component = targetNode.components[ i ];
  1560. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  1561. }
  1562. if ( output !== 'void' ) {
  1563. snippet = target;
  1564. }
  1565. } else {
  1566. snippet = `${ target } = ${ source }`;
  1567. if ( output === 'void' || sourceType === 'void' ) {
  1568. builder.addLineFlowCode( snippet, this );
  1569. if ( output !== 'void' ) {
  1570. snippet = target;
  1571. }
  1572. }
  1573. }
  1574. nodeData.initialized = true;
  1575. return builder.format( snippet, targetType, output );
  1576. }
  1577. }
  1578. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  1579. addMethodChaining( 'assign', assign );
  1580. class FunctionCallNode extends TempNode {
  1581. static get type() {
  1582. return 'FunctionCallNode';
  1583. }
  1584. constructor( functionNode = null, parameters = {} ) {
  1585. super();
  1586. this.functionNode = functionNode;
  1587. this.parameters = parameters;
  1588. }
  1589. setParameters( parameters ) {
  1590. this.parameters = parameters;
  1591. return this;
  1592. }
  1593. getParameters() {
  1594. return this.parameters;
  1595. }
  1596. getNodeType( builder ) {
  1597. return this.functionNode.getNodeType( builder );
  1598. }
  1599. generate( builder ) {
  1600. const params = [];
  1601. const functionNode = this.functionNode;
  1602. const inputs = functionNode.getInputs( builder );
  1603. const parameters = this.parameters;
  1604. const generateInput = ( node, inputNode ) => {
  1605. const type = inputNode.type;
  1606. const pointer = type === 'pointer';
  1607. let output;
  1608. if ( pointer ) output = '&' + node.build( builder );
  1609. else output = node.build( builder, type );
  1610. return output;
  1611. };
  1612. if ( Array.isArray( parameters ) ) {
  1613. for ( let i = 0; i < parameters.length; i ++ ) {
  1614. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  1615. }
  1616. } else {
  1617. for ( const inputNode of inputs ) {
  1618. const node = parameters[ inputNode.name ];
  1619. if ( node !== undefined ) {
  1620. params.push( generateInput( node, inputNode ) );
  1621. } else {
  1622. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  1623. }
  1624. }
  1625. }
  1626. const functionName = functionNode.build( builder, 'property' );
  1627. return `${functionName}( ${params.join( ', ' )} )`;
  1628. }
  1629. }
  1630. const call = ( func, ...params ) => {
  1631. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  1632. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  1633. };
  1634. addMethodChaining( 'call', call );
  1635. class OperatorNode extends TempNode {
  1636. static get type() {
  1637. return 'OperatorNode';
  1638. }
  1639. constructor( op, aNode, bNode, ...params ) {
  1640. super();
  1641. if ( params.length > 0 ) {
  1642. let finalOp = new OperatorNode( op, aNode, bNode );
  1643. for ( let i = 0; i < params.length - 1; i ++ ) {
  1644. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  1645. }
  1646. aNode = finalOp;
  1647. bNode = params[ params.length - 1 ];
  1648. }
  1649. this.op = op;
  1650. this.aNode = aNode;
  1651. this.bNode = bNode;
  1652. }
  1653. getNodeType( builder, output ) {
  1654. const op = this.op;
  1655. const aNode = this.aNode;
  1656. const bNode = this.bNode;
  1657. const typeA = aNode.getNodeType( builder );
  1658. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  1659. if ( typeA === 'void' || typeB === 'void' ) {
  1660. return 'void';
  1661. } else if ( op === '%' ) {
  1662. return typeA;
  1663. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  1664. return builder.getIntegerType( typeA );
  1665. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  1666. return 'bool';
  1667. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  1668. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  1669. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  1670. } else {
  1671. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  1672. return typeB;
  1673. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  1674. // matrix x vector
  1675. return builder.getVectorFromMatrix( typeA );
  1676. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  1677. // vector x matrix
  1678. return builder.getVectorFromMatrix( typeB );
  1679. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  1680. // anytype x anytype: use the greater length vector
  1681. return typeB;
  1682. }
  1683. return typeA;
  1684. }
  1685. }
  1686. generate( builder, output ) {
  1687. const op = this.op;
  1688. const aNode = this.aNode;
  1689. const bNode = this.bNode;
  1690. const type = this.getNodeType( builder, output );
  1691. let typeA = null;
  1692. let typeB = null;
  1693. if ( type !== 'void' ) {
  1694. typeA = aNode.getNodeType( builder );
  1695. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  1696. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  1697. if ( builder.isVector( typeA ) ) {
  1698. typeB = typeA;
  1699. } else if ( typeA !== typeB ) {
  1700. typeA = typeB = 'float';
  1701. }
  1702. } else if ( op === '>>' || op === '<<' ) {
  1703. typeA = type;
  1704. typeB = builder.changeComponentType( typeB, 'uint' );
  1705. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  1706. // matrix x vector
  1707. typeB = builder.getVectorFromMatrix( typeA );
  1708. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  1709. // vector x matrix
  1710. typeA = builder.getVectorFromMatrix( typeB );
  1711. } else {
  1712. // anytype x anytype
  1713. typeA = typeB = type;
  1714. }
  1715. } else {
  1716. typeA = typeB = type;
  1717. }
  1718. const a = aNode.build( builder, typeA );
  1719. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  1720. const outputLength = builder.getTypeLength( output );
  1721. const fnOpSnippet = builder.getFunctionOperator( op );
  1722. if ( output !== 'void' ) {
  1723. if ( op === '<' && outputLength > 1 ) {
  1724. if ( builder.useComparisonMethod ) {
  1725. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  1726. } else {
  1727. return builder.format( `( ${ a } < ${ b } )`, type, output );
  1728. }
  1729. } else if ( op === '<=' && outputLength > 1 ) {
  1730. if ( builder.useComparisonMethod ) {
  1731. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  1732. } else {
  1733. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  1734. }
  1735. } else if ( op === '>' && outputLength > 1 ) {
  1736. if ( builder.useComparisonMethod ) {
  1737. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  1738. } else {
  1739. return builder.format( `( ${ a } > ${ b } )`, type, output );
  1740. }
  1741. } else if ( op === '>=' && outputLength > 1 ) {
  1742. if ( builder.useComparisonMethod ) {
  1743. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  1744. } else {
  1745. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  1746. }
  1747. } else if ( op === '!' || op === '~' ) {
  1748. return builder.format( `(${op}${a})`, typeA, output );
  1749. } else if ( fnOpSnippet ) {
  1750. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  1751. } else {
  1752. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  1753. }
  1754. } else if ( typeA !== 'void' ) {
  1755. if ( fnOpSnippet ) {
  1756. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  1757. } else {
  1758. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  1759. }
  1760. }
  1761. }
  1762. serialize( data ) {
  1763. super.serialize( data );
  1764. data.op = this.op;
  1765. }
  1766. deserialize( data ) {
  1767. super.deserialize( data );
  1768. this.op = data.op;
  1769. }
  1770. }
  1771. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  1772. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  1773. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  1774. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  1775. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  1776. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  1777. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  1778. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  1779. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  1780. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  1781. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  1782. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  1783. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  1784. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  1785. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  1786. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  1787. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  1788. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  1789. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  1790. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  1791. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  1792. addMethodChaining( 'add', add );
  1793. addMethodChaining( 'sub', sub );
  1794. addMethodChaining( 'mul', mul );
  1795. addMethodChaining( 'div', div );
  1796. addMethodChaining( 'modInt', modInt );
  1797. addMethodChaining( 'equal', equal );
  1798. addMethodChaining( 'notEqual', notEqual );
  1799. addMethodChaining( 'lessThan', lessThan );
  1800. addMethodChaining( 'greaterThan', greaterThan );
  1801. addMethodChaining( 'lessThanEqual', lessThanEqual );
  1802. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  1803. addMethodChaining( 'and', and );
  1804. addMethodChaining( 'or', or );
  1805. addMethodChaining( 'not', not );
  1806. addMethodChaining( 'xor', xor );
  1807. addMethodChaining( 'bitAnd', bitAnd );
  1808. addMethodChaining( 'bitNot', bitNot );
  1809. addMethodChaining( 'bitOr', bitOr );
  1810. addMethodChaining( 'bitXor', bitXor );
  1811. addMethodChaining( 'shiftLeft', shiftLeft );
  1812. addMethodChaining( 'shiftRight', shiftRight );
  1813. const remainder = ( ...params ) => { // @deprecated, r168
  1814. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  1815. return modInt( ...params );
  1816. };
  1817. addMethodChaining( 'remainder', remainder );
  1818. class MathNode extends TempNode {
  1819. static get type() {
  1820. return 'MathNode';
  1821. }
  1822. constructor( method, aNode, bNode = null, cNode = null ) {
  1823. super();
  1824. this.method = method;
  1825. this.aNode = aNode;
  1826. this.bNode = bNode;
  1827. this.cNode = cNode;
  1828. }
  1829. getInputType( builder ) {
  1830. const aType = this.aNode.getNodeType( builder );
  1831. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  1832. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  1833. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  1834. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  1835. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  1836. if ( aLen > bLen && aLen > cLen ) {
  1837. return aType;
  1838. } else if ( bLen > cLen ) {
  1839. return bType;
  1840. } else if ( cLen > aLen ) {
  1841. return cType;
  1842. }
  1843. return aType;
  1844. }
  1845. getNodeType( builder ) {
  1846. const method = this.method;
  1847. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  1848. return 'float';
  1849. } else if ( method === MathNode.CROSS ) {
  1850. return 'vec3';
  1851. } else if ( method === MathNode.ALL ) {
  1852. return 'bool';
  1853. } else if ( method === MathNode.EQUALS ) {
  1854. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  1855. } else if ( method === MathNode.MOD ) {
  1856. return this.aNode.getNodeType( builder );
  1857. } else {
  1858. return this.getInputType( builder );
  1859. }
  1860. }
  1861. generate( builder, output ) {
  1862. const method = this.method;
  1863. const type = this.getNodeType( builder );
  1864. const inputType = this.getInputType( builder );
  1865. const a = this.aNode;
  1866. const b = this.bNode;
  1867. const c = this.cNode;
  1868. const isWebGL = builder.renderer.isWebGLRenderer === true;
  1869. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  1870. // dir can be either a direction vector or a normal vector
  1871. // upper-left 3x3 of matrix is assumed to be orthogonal
  1872. let tA = a;
  1873. let tB = b;
  1874. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  1875. tB = vec4( vec3( tB ), 0.0 );
  1876. } else {
  1877. tA = vec4( vec3( tA ), 0.0 );
  1878. }
  1879. const mulNode = mul( tA, tB ).xyz;
  1880. return normalize( mulNode ).build( builder, output );
  1881. } else if ( method === MathNode.NEGATE ) {
  1882. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  1883. } else if ( method === MathNode.ONE_MINUS ) {
  1884. return sub( 1.0, a ).build( builder, output );
  1885. } else if ( method === MathNode.RECIPROCAL ) {
  1886. return div( 1.0, a ).build( builder, output );
  1887. } else if ( method === MathNode.DIFFERENCE ) {
  1888. return abs( sub( a, b ) ).build( builder, output );
  1889. } else {
  1890. const params = [];
  1891. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  1892. params.push(
  1893. a.build( builder, type ),
  1894. b.build( builder, type )
  1895. );
  1896. } else if ( isWebGL && method === MathNode.STEP ) {
  1897. params.push(
  1898. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  1899. b.build( builder, inputType )
  1900. );
  1901. } else if ( ( isWebGL && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  1902. params.push(
  1903. a.build( builder, inputType ),
  1904. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  1905. );
  1906. } else if ( method === MathNode.REFRACT ) {
  1907. params.push(
  1908. a.build( builder, inputType ),
  1909. b.build( builder, inputType ),
  1910. c.build( builder, 'float' )
  1911. );
  1912. } else if ( method === MathNode.MIX ) {
  1913. params.push(
  1914. a.build( builder, inputType ),
  1915. b.build( builder, inputType ),
  1916. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  1917. );
  1918. } else {
  1919. params.push( a.build( builder, inputType ) );
  1920. if ( b !== null ) params.push( b.build( builder, inputType ) );
  1921. if ( c !== null ) params.push( c.build( builder, inputType ) );
  1922. }
  1923. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  1924. }
  1925. }
  1926. serialize( data ) {
  1927. super.serialize( data );
  1928. data.method = this.method;
  1929. }
  1930. deserialize( data ) {
  1931. super.deserialize( data );
  1932. this.method = data.method;
  1933. }
  1934. }
  1935. // 1 input
  1936. MathNode.ALL = 'all';
  1937. MathNode.ANY = 'any';
  1938. MathNode.EQUALS = 'equals';
  1939. MathNode.RADIANS = 'radians';
  1940. MathNode.DEGREES = 'degrees';
  1941. MathNode.EXP = 'exp';
  1942. MathNode.EXP2 = 'exp2';
  1943. MathNode.LOG = 'log';
  1944. MathNode.LOG2 = 'log2';
  1945. MathNode.SQRT = 'sqrt';
  1946. MathNode.INVERSE_SQRT = 'inversesqrt';
  1947. MathNode.FLOOR = 'floor';
  1948. MathNode.CEIL = 'ceil';
  1949. MathNode.NORMALIZE = 'normalize';
  1950. MathNode.FRACT = 'fract';
  1951. MathNode.SIN = 'sin';
  1952. MathNode.COS = 'cos';
  1953. MathNode.TAN = 'tan';
  1954. MathNode.ASIN = 'asin';
  1955. MathNode.ACOS = 'acos';
  1956. MathNode.ATAN = 'atan';
  1957. MathNode.ABS = 'abs';
  1958. MathNode.SIGN = 'sign';
  1959. MathNode.LENGTH = 'length';
  1960. MathNode.NEGATE = 'negate';
  1961. MathNode.ONE_MINUS = 'oneMinus';
  1962. MathNode.DFDX = 'dFdx';
  1963. MathNode.DFDY = 'dFdy';
  1964. MathNode.ROUND = 'round';
  1965. MathNode.RECIPROCAL = 'reciprocal';
  1966. MathNode.TRUNC = 'trunc';
  1967. MathNode.FWIDTH = 'fwidth';
  1968. MathNode.BITCAST = 'bitcast';
  1969. MathNode.TRANSPOSE = 'transpose';
  1970. // 2 inputs
  1971. MathNode.ATAN2 = 'atan2';
  1972. MathNode.MIN = 'min';
  1973. MathNode.MAX = 'max';
  1974. MathNode.MOD = 'mod';
  1975. MathNode.STEP = 'step';
  1976. MathNode.REFLECT = 'reflect';
  1977. MathNode.DISTANCE = 'distance';
  1978. MathNode.DIFFERENCE = 'difference';
  1979. MathNode.DOT = 'dot';
  1980. MathNode.CROSS = 'cross';
  1981. MathNode.POW = 'pow';
  1982. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  1983. // 3 inputs
  1984. MathNode.MIX = 'mix';
  1985. MathNode.CLAMP = 'clamp';
  1986. MathNode.REFRACT = 'refract';
  1987. MathNode.SMOOTHSTEP = 'smoothstep';
  1988. MathNode.FACEFORWARD = 'faceforward';
  1989. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  1990. const INFINITY = /*@__PURE__*/ float( 1e6 );
  1991. const PI = /*@__PURE__*/ float( Math.PI );
  1992. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  1993. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  1994. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  1995. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  1996. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  1997. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  1998. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  1999. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  2000. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  2001. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  2002. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  2003. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  2004. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  2005. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  2006. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  2007. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  2008. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  2009. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  2010. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  2011. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  2012. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  2013. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  2014. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  2015. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  2016. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  2017. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  2018. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  2019. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  2020. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  2021. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  2022. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  2023. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  2024. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  2025. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  2026. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  2027. const atan2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN2 );
  2028. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  2029. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  2030. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  2031. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  2032. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  2033. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  2034. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  2035. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  2036. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  2037. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  2038. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  2039. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  2040. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  2041. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  2042. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  2043. const lengthSq = ( a ) => dot( a, a );
  2044. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  2045. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  2046. const saturate = ( value ) => clamp( value );
  2047. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  2048. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  2049. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  2050. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  2051. const a = 12.9898, b = 78.233, c = 43758.5453;
  2052. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  2053. return fract( sin( sn ).mul( c ) );
  2054. } );
  2055. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  2056. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  2057. addMethodChaining( 'all', all );
  2058. addMethodChaining( 'any', any );
  2059. addMethodChaining( 'equals', equals );
  2060. addMethodChaining( 'radians', radians );
  2061. addMethodChaining( 'degrees', degrees );
  2062. addMethodChaining( 'exp', exp );
  2063. addMethodChaining( 'exp2', exp2 );
  2064. addMethodChaining( 'log', log );
  2065. addMethodChaining( 'log2', log2 );
  2066. addMethodChaining( 'sqrt', sqrt );
  2067. addMethodChaining( 'inverseSqrt', inverseSqrt );
  2068. addMethodChaining( 'floor', floor );
  2069. addMethodChaining( 'ceil', ceil );
  2070. addMethodChaining( 'normalize', normalize );
  2071. addMethodChaining( 'fract', fract );
  2072. addMethodChaining( 'sin', sin );
  2073. addMethodChaining( 'cos', cos );
  2074. addMethodChaining( 'tan', tan );
  2075. addMethodChaining( 'asin', asin );
  2076. addMethodChaining( 'acos', acos );
  2077. addMethodChaining( 'atan', atan );
  2078. addMethodChaining( 'abs', abs );
  2079. addMethodChaining( 'sign', sign );
  2080. addMethodChaining( 'length', length );
  2081. addMethodChaining( 'lengthSq', lengthSq );
  2082. addMethodChaining( 'negate', negate );
  2083. addMethodChaining( 'oneMinus', oneMinus );
  2084. addMethodChaining( 'dFdx', dFdx );
  2085. addMethodChaining( 'dFdy', dFdy );
  2086. addMethodChaining( 'round', round );
  2087. addMethodChaining( 'reciprocal', reciprocal );
  2088. addMethodChaining( 'trunc', trunc );
  2089. addMethodChaining( 'fwidth', fwidth );
  2090. addMethodChaining( 'atan2', atan2 );
  2091. addMethodChaining( 'min', min$1 );
  2092. addMethodChaining( 'max', max$1 );
  2093. addMethodChaining( 'mod', mod );
  2094. addMethodChaining( 'step', step );
  2095. addMethodChaining( 'reflect', reflect );
  2096. addMethodChaining( 'distance', distance );
  2097. addMethodChaining( 'dot', dot );
  2098. addMethodChaining( 'cross', cross );
  2099. addMethodChaining( 'pow', pow );
  2100. addMethodChaining( 'pow2', pow2 );
  2101. addMethodChaining( 'pow3', pow3 );
  2102. addMethodChaining( 'pow4', pow4 );
  2103. addMethodChaining( 'transformDirection', transformDirection );
  2104. addMethodChaining( 'mix', mixElement );
  2105. addMethodChaining( 'clamp', clamp );
  2106. addMethodChaining( 'refract', refract );
  2107. addMethodChaining( 'smoothstep', smoothstepElement );
  2108. addMethodChaining( 'faceForward', faceForward );
  2109. addMethodChaining( 'difference', difference );
  2110. addMethodChaining( 'saturate', saturate );
  2111. addMethodChaining( 'cbrt', cbrt );
  2112. addMethodChaining( 'transpose', transpose );
  2113. addMethodChaining( 'rand', rand );
  2114. class ConditionalNode extends Node {
  2115. static get type() {
  2116. return 'ConditionalNode';
  2117. }
  2118. constructor( condNode, ifNode, elseNode = null ) {
  2119. super();
  2120. this.condNode = condNode;
  2121. this.ifNode = ifNode;
  2122. this.elseNode = elseNode;
  2123. }
  2124. getNodeType( builder ) {
  2125. const ifType = this.ifNode.getNodeType( builder );
  2126. if ( this.elseNode !== null ) {
  2127. const elseType = this.elseNode.getNodeType( builder );
  2128. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  2129. return elseType;
  2130. }
  2131. }
  2132. return ifType;
  2133. }
  2134. setup( builder ) {
  2135. const condNode = this.condNode.cache();
  2136. const ifNode = this.ifNode.cache();
  2137. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  2138. //
  2139. const currentNodeBlock = builder.context.nodeBlock;
  2140. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  2141. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  2142. //
  2143. const properties = builder.getNodeProperties( this );
  2144. properties.condNode = condNode;
  2145. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  2146. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  2147. }
  2148. generate( builder, output ) {
  2149. const type = this.getNodeType( builder );
  2150. const nodeData = builder.getDataFromNode( this );
  2151. if ( nodeData.nodeProperty !== undefined ) {
  2152. return nodeData.nodeProperty;
  2153. }
  2154. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  2155. const needsOutput = output !== 'void';
  2156. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  2157. nodeData.nodeProperty = nodeProperty;
  2158. const nodeSnippet = condNode.build( builder, 'bool' );
  2159. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  2160. let ifSnippet = ifNode.build( builder, type );
  2161. if ( ifSnippet ) {
  2162. if ( needsOutput ) {
  2163. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  2164. } else {
  2165. ifSnippet = 'return ' + ifSnippet + ';';
  2166. }
  2167. }
  2168. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  2169. if ( elseNode !== null ) {
  2170. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  2171. let elseSnippet = elseNode.build( builder, type );
  2172. if ( elseSnippet ) {
  2173. if ( needsOutput ) {
  2174. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  2175. } else {
  2176. elseSnippet = 'return ' + elseSnippet + ';';
  2177. }
  2178. }
  2179. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  2180. } else {
  2181. builder.addFlowCode( '\n\n' );
  2182. }
  2183. return builder.format( nodeProperty, type, output );
  2184. }
  2185. }
  2186. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  2187. addMethodChaining( 'select', select );
  2188. //
  2189. const cond = ( ...params ) => { // @deprecated, r168
  2190. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  2191. return select( ...params );
  2192. };
  2193. addMethodChaining( 'cond', cond );
  2194. class ContextNode extends Node {
  2195. static get type() {
  2196. return 'ContextNode';
  2197. }
  2198. constructor( node, value = {} ) {
  2199. super();
  2200. this.isContextNode = true;
  2201. this.node = node;
  2202. this.value = value;
  2203. }
  2204. getScope() {
  2205. return this.node.getScope();
  2206. }
  2207. getNodeType( builder ) {
  2208. return this.node.getNodeType( builder );
  2209. }
  2210. analyze( builder ) {
  2211. this.node.build( builder );
  2212. }
  2213. setup( builder ) {
  2214. const previousContext = builder.getContext();
  2215. builder.setContext( { ...builder.context, ...this.value } );
  2216. const node = this.node.build( builder );
  2217. builder.setContext( previousContext );
  2218. return node;
  2219. }
  2220. generate( builder, output ) {
  2221. const previousContext = builder.getContext();
  2222. builder.setContext( { ...builder.context, ...this.value } );
  2223. const snippet = this.node.build( builder, output );
  2224. builder.setContext( previousContext );
  2225. return snippet;
  2226. }
  2227. }
  2228. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  2229. const label = ( node, name ) => context( node, { label: name } );
  2230. addMethodChaining( 'context', context );
  2231. addMethodChaining( 'label', label );
  2232. class VarNode extends Node {
  2233. static get type() {
  2234. return 'VarNode';
  2235. }
  2236. constructor( node, name = null ) {
  2237. super();
  2238. this.node = node;
  2239. this.name = name;
  2240. this.global = true;
  2241. this.isVarNode = true;
  2242. }
  2243. getHash( builder ) {
  2244. return this.name || super.getHash( builder );
  2245. }
  2246. getNodeType( builder ) {
  2247. return this.node.getNodeType( builder );
  2248. }
  2249. generate( builder ) {
  2250. const { node, name } = this;
  2251. const nodeVar = builder.getVarFromNode( this, name, builder.getVectorType( this.getNodeType( builder ) ) );
  2252. const propertyName = builder.getPropertyName( nodeVar );
  2253. const snippet = node.build( builder, nodeVar.type );
  2254. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  2255. return propertyName;
  2256. }
  2257. }
  2258. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  2259. addMethodChaining( 'toVar', ( ...params ) => createVar( ...params ).append() );
  2260. // Deprecated
  2261. const temp = ( node ) => { // @deprecated, r170
  2262. console.warn( 'TSL: "temp" is deprecated. Use ".toVar()" instead.' );
  2263. return createVar( node );
  2264. };
  2265. addMethodChaining( 'temp', temp );
  2266. class VaryingNode extends Node {
  2267. static get type() {
  2268. return 'VaryingNode';
  2269. }
  2270. constructor( node, name = null ) {
  2271. super();
  2272. this.node = node;
  2273. this.name = name;
  2274. this.isVaryingNode = true;
  2275. }
  2276. isGlobal() {
  2277. return true;
  2278. }
  2279. getHash( builder ) {
  2280. return this.name || super.getHash( builder );
  2281. }
  2282. getNodeType( builder ) {
  2283. // VaryingNode is auto type
  2284. return this.node.getNodeType( builder );
  2285. }
  2286. setupVarying( builder ) {
  2287. const properties = builder.getNodeProperties( this );
  2288. let varying = properties.varying;
  2289. if ( varying === undefined ) {
  2290. const name = this.name;
  2291. const type = this.getNodeType( builder );
  2292. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  2293. properties.node = this.node;
  2294. }
  2295. // this property can be used to check if the varying can be optimized for a variable
  2296. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  2297. return varying;
  2298. }
  2299. setup( builder ) {
  2300. this.setupVarying( builder );
  2301. }
  2302. analyze( builder ) {
  2303. this.setupVarying( builder );
  2304. return this.node.analyze( builder );
  2305. }
  2306. generate( builder ) {
  2307. const properties = builder.getNodeProperties( this );
  2308. const varying = this.setupVarying( builder );
  2309. if ( properties.propertyName === undefined ) {
  2310. const type = this.getNodeType( builder );
  2311. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  2312. // force node run in vertex stage
  2313. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  2314. properties.propertyName = propertyName;
  2315. }
  2316. return builder.getPropertyName( varying );
  2317. }
  2318. }
  2319. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  2320. addMethodChaining( 'varying', varying );
  2321. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  2322. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  2323. const b = color.mul( 0.0773993808 );
  2324. const factor = color.lessThanEqual( 0.04045 );
  2325. const rgbResult = mix( a, b, factor );
  2326. return rgbResult;
  2327. } ).setLayout( {
  2328. name: 'sRGBTransferEOTF',
  2329. type: 'vec3',
  2330. inputs: [
  2331. { name: 'color', type: 'vec3' }
  2332. ]
  2333. } );
  2334. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  2335. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  2336. const b = color.mul( 12.92 );
  2337. const factor = color.lessThanEqual( 0.0031308 );
  2338. const rgbResult = mix( a, b, factor );
  2339. return rgbResult;
  2340. } ).setLayout( {
  2341. name: 'sRGBTransferOETF',
  2342. type: 'vec3',
  2343. inputs: [
  2344. { name: 'color', type: 'vec3' }
  2345. ]
  2346. } );
  2347. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  2348. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  2349. class ColorSpaceNode extends TempNode {
  2350. static get type() {
  2351. return 'ColorSpaceNode';
  2352. }
  2353. constructor( colorNode, source, target ) {
  2354. super( 'vec4' );
  2355. this.colorNode = colorNode;
  2356. this.source = source;
  2357. this.target = target;
  2358. }
  2359. resolveColorSpace( builder, colorSpace ) {
  2360. if ( colorSpace === WORKING_COLOR_SPACE ) {
  2361. return ColorManagement.workingColorSpace;
  2362. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  2363. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  2364. }
  2365. return colorSpace;
  2366. }
  2367. setup( builder ) {
  2368. const { colorNode } = this;
  2369. const source = this.resolveColorSpace( builder, this.source );
  2370. const target = this.resolveColorSpace( builder, this.target );
  2371. let outputNode = colorNode;
  2372. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  2373. return outputNode;
  2374. }
  2375. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  2376. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  2377. }
  2378. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  2379. outputNode = vec4(
  2380. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  2381. outputNode.a
  2382. );
  2383. }
  2384. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  2385. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  2386. }
  2387. return outputNode;
  2388. }
  2389. }
  2390. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  2391. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  2392. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  2393. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  2394. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  2395. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  2396. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  2397. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  2398. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  2399. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  2400. static get type() {
  2401. return 'ReferenceElementNode';
  2402. }
  2403. constructor( referenceNode, indexNode ) {
  2404. super( referenceNode, indexNode );
  2405. this.referenceNode = referenceNode;
  2406. this.isReferenceElementNode = true;
  2407. }
  2408. getNodeType() {
  2409. return this.referenceNode.uniformType;
  2410. }
  2411. generate( builder ) {
  2412. const snippet = super.generate( builder );
  2413. const arrayType = this.referenceNode.getNodeType();
  2414. const elementType = this.getNodeType();
  2415. return builder.format( snippet, arrayType, elementType );
  2416. }
  2417. };
  2418. class ReferenceBaseNode extends Node {
  2419. static get type() {
  2420. return 'ReferenceBaseNode';
  2421. }
  2422. constructor( property, uniformType, object = null, count = null ) {
  2423. super();
  2424. this.property = property;
  2425. this.uniformType = uniformType;
  2426. this.object = object;
  2427. this.count = count;
  2428. this.properties = property.split( '.' );
  2429. this.reference = object;
  2430. this.node = null;
  2431. this.group = null;
  2432. this.updateType = NodeUpdateType.OBJECT;
  2433. }
  2434. setGroup( group ) {
  2435. this.group = group;
  2436. return this;
  2437. }
  2438. element( indexNode ) {
  2439. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  2440. }
  2441. setNodeType( uniformType ) {
  2442. const node = uniform( null, uniformType ).getSelf();
  2443. if ( this.group !== null ) {
  2444. node.setGroup( this.group );
  2445. }
  2446. this.node = node;
  2447. }
  2448. getNodeType( builder ) {
  2449. if ( this.node === null ) {
  2450. this.updateReference( builder );
  2451. this.updateValue();
  2452. }
  2453. return this.node.getNodeType( builder );
  2454. }
  2455. getValueFromReference( object = this.reference ) {
  2456. const { properties } = this;
  2457. let value = object[ properties[ 0 ] ];
  2458. for ( let i = 1; i < properties.length; i ++ ) {
  2459. value = value[ properties[ i ] ];
  2460. }
  2461. return value;
  2462. }
  2463. updateReference( state ) {
  2464. this.reference = this.object !== null ? this.object : state.object;
  2465. return this.reference;
  2466. }
  2467. setup() {
  2468. this.updateValue();
  2469. return this.node;
  2470. }
  2471. update( /*frame*/ ) {
  2472. this.updateValue();
  2473. }
  2474. updateValue() {
  2475. if ( this.node === null ) this.setNodeType( this.uniformType );
  2476. const value = this.getValueFromReference();
  2477. if ( Array.isArray( value ) ) {
  2478. this.node.array = value;
  2479. } else {
  2480. this.node.value = value;
  2481. }
  2482. }
  2483. }
  2484. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  2485. class RendererReferenceNode extends ReferenceBaseNode {
  2486. static get type() {
  2487. return 'RendererReferenceNode';
  2488. }
  2489. constructor( property, inputType, renderer = null ) {
  2490. super( property, inputType, renderer );
  2491. this.renderer = renderer;
  2492. this.setGroup( renderGroup );
  2493. }
  2494. updateReference( state ) {
  2495. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  2496. return this.reference;
  2497. }
  2498. }
  2499. const rendererReference = ( name, type, renderer ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  2500. class ToneMappingNode extends TempNode {
  2501. static get type() {
  2502. return 'ToneMappingNode';
  2503. }
  2504. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  2505. super( 'vec3' );
  2506. this.toneMapping = toneMapping;
  2507. this.exposureNode = exposureNode;
  2508. this.colorNode = colorNode;
  2509. }
  2510. getCacheKey() {
  2511. return hash$1( super.getCacheKey(), this.toneMapping );
  2512. }
  2513. setup( builder ) {
  2514. const colorNode = this.colorNode || builder.context.color;
  2515. const toneMapping = this.toneMapping;
  2516. if ( toneMapping === NoToneMapping ) return colorNode;
  2517. let outputNode = null;
  2518. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  2519. if ( toneMappingFn !== null ) {
  2520. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  2521. } else {
  2522. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  2523. outputNode = colorNode;
  2524. }
  2525. return outputNode;
  2526. }
  2527. }
  2528. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  2529. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  2530. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  2531. class BufferAttributeNode extends InputNode {
  2532. static get type() {
  2533. return 'BufferAttributeNode';
  2534. }
  2535. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  2536. super( value, bufferType );
  2537. this.isBufferNode = true;
  2538. this.bufferType = bufferType;
  2539. this.bufferStride = bufferStride;
  2540. this.bufferOffset = bufferOffset;
  2541. this.usage = StaticDrawUsage;
  2542. this.instanced = false;
  2543. this.attribute = null;
  2544. this.global = true;
  2545. if ( value && value.isBufferAttribute === true ) {
  2546. this.attribute = value;
  2547. this.usage = value.usage;
  2548. this.instanced = value.isInstancedBufferAttribute;
  2549. }
  2550. }
  2551. getHash( builder ) {
  2552. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  2553. let bufferData = builder.globalCache.getData( this.value );
  2554. if ( bufferData === undefined ) {
  2555. bufferData = {
  2556. node: this
  2557. };
  2558. builder.globalCache.setData( this.value, bufferData );
  2559. }
  2560. return bufferData.node.uuid;
  2561. }
  2562. return this.uuid;
  2563. }
  2564. getNodeType( builder ) {
  2565. if ( this.bufferType === null ) {
  2566. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  2567. }
  2568. return this.bufferType;
  2569. }
  2570. setup( builder ) {
  2571. if ( this.attribute !== null ) return;
  2572. const type = this.getNodeType( builder );
  2573. const array = this.value;
  2574. const itemSize = builder.getTypeLength( type );
  2575. const stride = this.bufferStride || itemSize;
  2576. const offset = this.bufferOffset;
  2577. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  2578. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  2579. buffer.setUsage( this.usage );
  2580. this.attribute = bufferAttribute;
  2581. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  2582. }
  2583. generate( builder ) {
  2584. const nodeType = this.getNodeType( builder );
  2585. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  2586. const propertyName = builder.getPropertyName( nodeAttribute );
  2587. let output = null;
  2588. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  2589. this.name = propertyName;
  2590. output = propertyName;
  2591. } else {
  2592. const nodeVarying = varying( this );
  2593. output = nodeVarying.build( builder, nodeType );
  2594. }
  2595. return output;
  2596. }
  2597. getInputType( /*builder*/ ) {
  2598. return 'bufferAttribute';
  2599. }
  2600. setUsage( value ) {
  2601. this.usage = value;
  2602. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  2603. this.attribute.usage = value;
  2604. }
  2605. return this;
  2606. }
  2607. setInstanced( value ) {
  2608. this.instanced = value;
  2609. return this;
  2610. }
  2611. }
  2612. const bufferAttribute = ( array, type, stride, offset ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  2613. const dynamicBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  2614. const instancedBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  2615. const instancedDynamicBufferAttribute = ( array, type, stride, offset ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  2616. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  2617. class ComputeNode extends Node {
  2618. static get type() {
  2619. return 'ComputeNode';
  2620. }
  2621. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  2622. super( 'void' );
  2623. this.isComputeNode = true;
  2624. this.computeNode = computeNode;
  2625. this.count = count;
  2626. this.workgroupSize = workgroupSize;
  2627. this.dispatchCount = 0;
  2628. this.version = 1;
  2629. this.updateBeforeType = NodeUpdateType.OBJECT;
  2630. this.onInitFunction = null;
  2631. this.updateDispatchCount();
  2632. }
  2633. dispose() {
  2634. this.dispatchEvent( { type: 'dispose' } );
  2635. }
  2636. set needsUpdate( value ) {
  2637. if ( value === true ) this.version ++;
  2638. }
  2639. updateDispatchCount() {
  2640. const { count, workgroupSize } = this;
  2641. let size = workgroupSize[ 0 ];
  2642. for ( let i = 1; i < workgroupSize.length; i ++ )
  2643. size *= workgroupSize[ i ];
  2644. this.dispatchCount = Math.ceil( count / size );
  2645. }
  2646. onInit( callback ) {
  2647. this.onInitFunction = callback;
  2648. return this;
  2649. }
  2650. updateBefore( { renderer } ) {
  2651. renderer.compute( this );
  2652. }
  2653. generate( builder ) {
  2654. const { shaderStage } = builder;
  2655. if ( shaderStage === 'compute' ) {
  2656. const snippet = this.computeNode.build( builder, 'void' );
  2657. if ( snippet !== '' ) {
  2658. builder.addLineFlowCode( snippet, this );
  2659. }
  2660. }
  2661. }
  2662. }
  2663. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  2664. addMethodChaining( 'compute', compute );
  2665. class CacheNode extends Node {
  2666. static get type() {
  2667. return 'CacheNode';
  2668. }
  2669. constructor( node, parent = true ) {
  2670. super();
  2671. this.node = node;
  2672. this.parent = parent;
  2673. this.isCacheNode = true;
  2674. }
  2675. getNodeType( builder ) {
  2676. return this.node.getNodeType( builder );
  2677. }
  2678. build( builder, ...params ) {
  2679. const previousCache = builder.getCache();
  2680. const cache = builder.getCacheFromNode( this, this.parent );
  2681. builder.setCache( cache );
  2682. const data = this.node.build( builder, ...params );
  2683. builder.setCache( previousCache );
  2684. return data;
  2685. }
  2686. }
  2687. const cache = ( node, ...params ) => nodeObject( new CacheNode( nodeObject( node ), ...params ) );
  2688. addMethodChaining( 'cache', cache );
  2689. class BypassNode extends Node {
  2690. static get type() {
  2691. return 'BypassNode';
  2692. }
  2693. constructor( returnNode, callNode ) {
  2694. super();
  2695. this.isBypassNode = true;
  2696. this.outputNode = returnNode;
  2697. this.callNode = callNode;
  2698. }
  2699. getNodeType( builder ) {
  2700. return this.outputNode.getNodeType( builder );
  2701. }
  2702. generate( builder ) {
  2703. const snippet = this.callNode.build( builder, 'void' );
  2704. if ( snippet !== '' ) {
  2705. builder.addLineFlowCode( snippet, this );
  2706. }
  2707. return this.outputNode.build( builder );
  2708. }
  2709. }
  2710. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  2711. addMethodChaining( 'bypass', bypass );
  2712. class RemapNode extends Node {
  2713. static get type() {
  2714. return 'RemapNode';
  2715. }
  2716. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  2717. super();
  2718. this.node = node;
  2719. this.inLowNode = inLowNode;
  2720. this.inHighNode = inHighNode;
  2721. this.outLowNode = outLowNode;
  2722. this.outHighNode = outHighNode;
  2723. this.doClamp = true;
  2724. }
  2725. setup() {
  2726. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  2727. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  2728. if ( doClamp === true ) t = t.clamp();
  2729. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  2730. }
  2731. }
  2732. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  2733. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  2734. addMethodChaining( 'remap', remap );
  2735. addMethodChaining( 'remapClamp', remapClamp );
  2736. class ExpressionNode extends Node {
  2737. static get type() {
  2738. return 'ExpressionNode';
  2739. }
  2740. constructor( snippet = '', nodeType = 'void' ) {
  2741. super( nodeType );
  2742. this.snippet = snippet;
  2743. }
  2744. generate( builder, output ) {
  2745. const type = this.getNodeType( builder );
  2746. const snippet = this.snippet;
  2747. if ( type === 'void' ) {
  2748. builder.addLineFlowCode( snippet, this );
  2749. } else {
  2750. return builder.format( `( ${ snippet } )`, type, output );
  2751. }
  2752. }
  2753. }
  2754. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  2755. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  2756. const Return = () => expression( 'return' ).append();
  2757. addMethodChaining( 'discard', Discard );
  2758. class RenderOutputNode extends TempNode {
  2759. static get type() {
  2760. return 'RenderOutputNode';
  2761. }
  2762. constructor( colorNode, toneMapping, outputColorSpace ) {
  2763. super( 'vec4' );
  2764. this.colorNode = colorNode;
  2765. this.toneMapping = toneMapping;
  2766. this.outputColorSpace = outputColorSpace;
  2767. this.isRenderOutput = true;
  2768. }
  2769. setup( { context } ) {
  2770. let outputNode = this.colorNode || context.color;
  2771. // tone mapping
  2772. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  2773. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  2774. if ( toneMapping !== NoToneMapping ) {
  2775. outputNode = outputNode.toneMapping( toneMapping );
  2776. }
  2777. // working to output color space
  2778. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  2779. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  2780. }
  2781. return outputNode;
  2782. }
  2783. }
  2784. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  2785. addMethodChaining( 'renderOutput', renderOutput );
  2786. // Non-PURE exports list, side-effects are required here.
  2787. // TSL Base Syntax
  2788. function addNodeElement( name/*, nodeElement*/ ) {
  2789. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  2790. }
  2791. class AttributeNode extends Node {
  2792. static get type() {
  2793. return 'AttributeNode';
  2794. }
  2795. constructor( attributeName, nodeType = null ) {
  2796. super( nodeType );
  2797. this.global = true;
  2798. this._attributeName = attributeName;
  2799. }
  2800. getHash( builder ) {
  2801. return this.getAttributeName( builder );
  2802. }
  2803. getNodeType( builder ) {
  2804. let nodeType = this.nodeType;
  2805. if ( nodeType === null ) {
  2806. const attributeName = this.getAttributeName( builder );
  2807. if ( builder.hasGeometryAttribute( attributeName ) ) {
  2808. const attribute = builder.geometry.getAttribute( attributeName );
  2809. nodeType = builder.getTypeFromAttribute( attribute );
  2810. } else {
  2811. nodeType = 'float';
  2812. }
  2813. }
  2814. return nodeType;
  2815. }
  2816. setAttributeName( attributeName ) {
  2817. this._attributeName = attributeName;
  2818. return this;
  2819. }
  2820. getAttributeName( /*builder*/ ) {
  2821. return this._attributeName;
  2822. }
  2823. generate( builder ) {
  2824. const attributeName = this.getAttributeName( builder );
  2825. const nodeType = this.getNodeType( builder );
  2826. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  2827. if ( geometryAttribute === true ) {
  2828. const attribute = builder.geometry.getAttribute( attributeName );
  2829. const attributeType = builder.getTypeFromAttribute( attribute );
  2830. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  2831. if ( builder.shaderStage === 'vertex' ) {
  2832. return builder.format( nodeAttribute.name, attributeType, nodeType );
  2833. } else {
  2834. const nodeVarying = varying( this );
  2835. return nodeVarying.build( builder, nodeType );
  2836. }
  2837. } else {
  2838. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  2839. return builder.generateConst( nodeType );
  2840. }
  2841. }
  2842. serialize( data ) {
  2843. super.serialize( data );
  2844. data.global = this.global;
  2845. data._attributeName = this._attributeName;
  2846. }
  2847. deserialize( data ) {
  2848. super.deserialize( data );
  2849. this.global = data.global;
  2850. this._attributeName = data._attributeName;
  2851. }
  2852. }
  2853. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  2854. const uv = ( index ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  2855. class TextureSizeNode extends Node {
  2856. static get type() {
  2857. return 'TextureSizeNode';
  2858. }
  2859. constructor( textureNode, levelNode = null ) {
  2860. super( 'uvec2' );
  2861. this.isTextureSizeNode = true;
  2862. this.textureNode = textureNode;
  2863. this.levelNode = levelNode;
  2864. }
  2865. generate( builder, output ) {
  2866. const textureProperty = this.textureNode.build( builder, 'property' );
  2867. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  2868. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  2869. }
  2870. }
  2871. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  2872. class MaxMipLevelNode extends UniformNode {
  2873. static get type() {
  2874. return 'MaxMipLevelNode';
  2875. }
  2876. constructor( textureNode ) {
  2877. super( 0 );
  2878. this._textureNode = textureNode;
  2879. this.updateType = NodeUpdateType.FRAME;
  2880. }
  2881. get textureNode() {
  2882. return this._textureNode;
  2883. }
  2884. get texture() {
  2885. return this._textureNode.value;
  2886. }
  2887. update() {
  2888. const texture = this.texture;
  2889. const images = texture.images;
  2890. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  2891. if ( image && image.width !== undefined ) {
  2892. const { width, height } = image;
  2893. this.value = Math.log2( Math.max( width, height ) );
  2894. }
  2895. }
  2896. }
  2897. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  2898. class TextureNode extends UniformNode {
  2899. static get type() {
  2900. return 'TextureNode';
  2901. }
  2902. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  2903. super( value );
  2904. this.isTextureNode = true;
  2905. this.uvNode = uvNode;
  2906. this.levelNode = levelNode;
  2907. this.biasNode = biasNode;
  2908. this.compareNode = null;
  2909. this.depthNode = null;
  2910. this.gradNode = null;
  2911. this.sampler = true;
  2912. this.updateMatrix = false;
  2913. this.updateType = NodeUpdateType.NONE;
  2914. this.referenceNode = null;
  2915. this._value = value;
  2916. this._matrixUniform = null;
  2917. this.setUpdateMatrix( uvNode === null );
  2918. }
  2919. set value( value ) {
  2920. if ( this.referenceNode ) {
  2921. this.referenceNode.value = value;
  2922. } else {
  2923. this._value = value;
  2924. }
  2925. }
  2926. get value() {
  2927. return this.referenceNode ? this.referenceNode.value : this._value;
  2928. }
  2929. getUniformHash( /*builder*/ ) {
  2930. return this.value.uuid;
  2931. }
  2932. getNodeType( /*builder*/ ) {
  2933. if ( this.value.isDepthTexture === true ) return 'float';
  2934. if ( this.value.type === UnsignedIntType ) {
  2935. return 'uvec4';
  2936. } else if ( this.value.type === IntType ) {
  2937. return 'ivec4';
  2938. }
  2939. return 'vec4';
  2940. }
  2941. getInputType( /*builder*/ ) {
  2942. return 'texture';
  2943. }
  2944. getDefaultUV() {
  2945. return uv( this.value.channel );
  2946. }
  2947. updateReference( /*state*/ ) {
  2948. return this.value;
  2949. }
  2950. getTransformedUV( uvNode ) {
  2951. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  2952. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  2953. }
  2954. setUpdateMatrix( value ) {
  2955. this.updateMatrix = value;
  2956. this.updateType = value ? NodeUpdateType.FRAME : NodeUpdateType.NONE;
  2957. return this;
  2958. }
  2959. setupUV( builder, uvNode ) {
  2960. const texture = this.value;
  2961. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  2962. if ( this.sampler ) {
  2963. uvNode = uvNode.flipY();
  2964. } else {
  2965. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  2966. }
  2967. }
  2968. return uvNode;
  2969. }
  2970. setup( builder ) {
  2971. const properties = builder.getNodeProperties( this );
  2972. properties.referenceNode = this.referenceNode;
  2973. //
  2974. let uvNode = this.uvNode;
  2975. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  2976. uvNode = builder.context.getUV( this );
  2977. }
  2978. if ( ! uvNode ) uvNode = this.getDefaultUV();
  2979. if ( this.updateMatrix === true ) {
  2980. uvNode = this.getTransformedUV( uvNode );
  2981. }
  2982. uvNode = this.setupUV( builder, uvNode );
  2983. //
  2984. let levelNode = this.levelNode;
  2985. if ( levelNode === null && builder.context.getTextureLevel ) {
  2986. levelNode = builder.context.getTextureLevel( this );
  2987. }
  2988. //
  2989. properties.uvNode = uvNode;
  2990. properties.levelNode = levelNode;
  2991. properties.biasNode = this.biasNode;
  2992. properties.compareNode = this.compareNode;
  2993. properties.gradNode = this.gradNode;
  2994. properties.depthNode = this.depthNode;
  2995. }
  2996. generateUV( builder, uvNode ) {
  2997. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  2998. }
  2999. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  3000. const texture = this.value;
  3001. let snippet;
  3002. if ( levelSnippet ) {
  3003. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  3004. } else if ( biasSnippet ) {
  3005. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  3006. } else if ( gradSnippet ) {
  3007. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  3008. } else if ( compareSnippet ) {
  3009. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  3010. } else if ( this.sampler === false ) {
  3011. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  3012. } else {
  3013. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  3014. }
  3015. return snippet;
  3016. }
  3017. generate( builder, output ) {
  3018. const properties = builder.getNodeProperties( this );
  3019. const texture = this.value;
  3020. if ( ! texture || texture.isTexture !== true ) {
  3021. throw new Error( 'TextureNode: Need a three.js texture.' );
  3022. }
  3023. const textureProperty = super.generate( builder, 'property' );
  3024. if ( output === 'sampler' ) {
  3025. return textureProperty + '_sampler';
  3026. } else if ( builder.isReference( output ) ) {
  3027. return textureProperty;
  3028. } else {
  3029. const nodeData = builder.getDataFromNode( this );
  3030. let propertyName = nodeData.propertyName;
  3031. if ( propertyName === undefined ) {
  3032. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  3033. const uvSnippet = this.generateUV( builder, uvNode );
  3034. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  3035. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  3036. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  3037. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  3038. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  3039. const nodeVar = builder.getVarFromNode( this );
  3040. propertyName = builder.getPropertyName( nodeVar );
  3041. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  3042. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  3043. nodeData.snippet = snippet;
  3044. nodeData.propertyName = propertyName;
  3045. }
  3046. let snippet = propertyName;
  3047. const nodeType = this.getNodeType( builder );
  3048. if ( builder.needsToWorkingColorSpace( texture ) ) {
  3049. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  3050. }
  3051. return builder.format( snippet, nodeType, output );
  3052. }
  3053. }
  3054. setSampler( value ) {
  3055. this.sampler = value;
  3056. return this;
  3057. }
  3058. getSampler() {
  3059. return this.sampler;
  3060. }
  3061. // @TODO: Move to TSL
  3062. uv( uvNode ) {
  3063. const textureNode = this.clone();
  3064. textureNode.uvNode = nodeObject( uvNode );
  3065. textureNode.referenceNode = this.getSelf();
  3066. return nodeObject( textureNode );
  3067. }
  3068. blur( amountNode ) {
  3069. const textureNode = this.clone();
  3070. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  3071. textureNode.referenceNode = this.getSelf();
  3072. return nodeObject( textureNode );
  3073. }
  3074. level( levelNode ) {
  3075. const textureNode = this.clone();
  3076. textureNode.levelNode = nodeObject( levelNode );
  3077. textureNode.referenceNode = this.getSelf();
  3078. return nodeObject( textureNode );
  3079. }
  3080. size( levelNode ) {
  3081. return textureSize( this, levelNode );
  3082. }
  3083. bias( biasNode ) {
  3084. const textureNode = this.clone();
  3085. textureNode.biasNode = nodeObject( biasNode );
  3086. textureNode.referenceNode = this.getSelf();
  3087. return nodeObject( textureNode );
  3088. }
  3089. compare( compareNode ) {
  3090. const textureNode = this.clone();
  3091. textureNode.compareNode = nodeObject( compareNode );
  3092. textureNode.referenceNode = this.getSelf();
  3093. return nodeObject( textureNode );
  3094. }
  3095. grad( gradNodeX, gradNodeY ) {
  3096. const textureNode = this.clone();
  3097. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  3098. textureNode.referenceNode = this.getSelf();
  3099. return nodeObject( textureNode );
  3100. }
  3101. depth( depthNode ) {
  3102. const textureNode = this.clone();
  3103. textureNode.depthNode = nodeObject( depthNode );
  3104. textureNode.referenceNode = this.getSelf();
  3105. return nodeObject( textureNode );
  3106. }
  3107. // --
  3108. serialize( data ) {
  3109. super.serialize( data );
  3110. data.value = this.value.toJSON( data.meta ).uuid;
  3111. data.sampler = this.sampler;
  3112. data.updateMatrix = this.updateMatrix;
  3113. data.updateType = this.updateType;
  3114. }
  3115. deserialize( data ) {
  3116. super.deserialize( data );
  3117. this.value = data.meta.textures[ data.value ];
  3118. this.sampler = data.sampler;
  3119. this.updateMatrix = data.updateMatrix;
  3120. this.updateType = data.updateType;
  3121. }
  3122. update() {
  3123. const texture = this.value;
  3124. const matrixUniform = this._matrixUniform;
  3125. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  3126. if ( texture.matrixAutoUpdate === true ) {
  3127. texture.updateMatrix();
  3128. }
  3129. }
  3130. clone() {
  3131. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  3132. newNode.sampler = this.sampler;
  3133. return newNode;
  3134. }
  3135. }
  3136. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  3137. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  3138. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  3139. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  3140. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  3141. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  3142. const cameraProjectionMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  3143. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  3144. const cameraViewMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  3145. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  3146. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  3147. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  3148. class Object3DNode extends Node {
  3149. static get type() {
  3150. return 'Object3DNode';
  3151. }
  3152. constructor( scope, object3d = null ) {
  3153. super();
  3154. this.scope = scope;
  3155. this.object3d = object3d;
  3156. this.updateType = NodeUpdateType.OBJECT;
  3157. this._uniformNode = new UniformNode( null );
  3158. }
  3159. getNodeType() {
  3160. const scope = this.scope;
  3161. if ( scope === Object3DNode.WORLD_MATRIX ) {
  3162. return 'mat4';
  3163. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  3164. return 'vec3';
  3165. }
  3166. }
  3167. update( frame ) {
  3168. const object = this.object3d;
  3169. const uniformNode = this._uniformNode;
  3170. const scope = this.scope;
  3171. if ( scope === Object3DNode.WORLD_MATRIX ) {
  3172. uniformNode.value = object.matrixWorld;
  3173. } else if ( scope === Object3DNode.POSITION ) {
  3174. uniformNode.value = uniformNode.value || new Vector3();
  3175. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  3176. } else if ( scope === Object3DNode.SCALE ) {
  3177. uniformNode.value = uniformNode.value || new Vector3();
  3178. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  3179. } else if ( scope === Object3DNode.DIRECTION ) {
  3180. uniformNode.value = uniformNode.value || new Vector3();
  3181. object.getWorldDirection( uniformNode.value );
  3182. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  3183. const camera = frame.camera;
  3184. uniformNode.value = uniformNode.value || new Vector3();
  3185. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  3186. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  3187. }
  3188. }
  3189. generate( builder ) {
  3190. const scope = this.scope;
  3191. if ( scope === Object3DNode.WORLD_MATRIX ) {
  3192. this._uniformNode.nodeType = 'mat4';
  3193. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  3194. this._uniformNode.nodeType = 'vec3';
  3195. }
  3196. return this._uniformNode.build( builder );
  3197. }
  3198. serialize( data ) {
  3199. super.serialize( data );
  3200. data.scope = this.scope;
  3201. }
  3202. deserialize( data ) {
  3203. super.deserialize( data );
  3204. this.scope = data.scope;
  3205. }
  3206. }
  3207. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  3208. Object3DNode.POSITION = 'position';
  3209. Object3DNode.SCALE = 'scale';
  3210. Object3DNode.VIEW_POSITION = 'viewPosition';
  3211. Object3DNode.DIRECTION = 'direction';
  3212. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  3213. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  3214. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  3215. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  3216. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  3217. class ModelNode extends Object3DNode {
  3218. static get type() {
  3219. return 'ModelNode';
  3220. }
  3221. constructor( scope ) {
  3222. super( scope );
  3223. }
  3224. update( frame ) {
  3225. this.object3d = frame.object;
  3226. super.update( frame );
  3227. }
  3228. }
  3229. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  3230. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  3231. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  3232. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  3233. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  3234. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  3235. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  3236. const modelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix ).toVar( 'modelViewMatrix' );
  3237. const highPrecisionModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  3238. builder.context.isHighPrecisionModelViewMatrix = true;
  3239. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  3240. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  3241. } );
  3242. } ).once() )().toVar( 'highPrecisionModelViewMatrix' );
  3243. const highPrecisionModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  3244. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  3245. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  3246. if ( isHighPrecisionModelViewMatrix !== true ) {
  3247. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  3248. }
  3249. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  3250. } );
  3251. } ).once() )().toVar( 'highPrecisionModelNormalMatrix' );
  3252. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  3253. const positionLocal = /*@__PURE__*/ positionGeometry.varying( 'positionLocal' );
  3254. const positionPrevious = /*@__PURE__*/ positionGeometry.varying( 'positionPrevious' );
  3255. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.varying( 'v_positionWorld' );
  3256. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).varying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' );
  3257. const positionView = /*@__PURE__*/ modelViewMatrix.mul( positionLocal ).xyz.varying( 'v_positionView' );
  3258. const positionViewDirection = /*@__PURE__*/ positionView.negate().varying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  3259. class FrontFacingNode extends Node {
  3260. static get type() {
  3261. return 'FrontFacingNode';
  3262. }
  3263. constructor() {
  3264. super( 'bool' );
  3265. this.isFrontFacingNode = true;
  3266. }
  3267. generate( builder ) {
  3268. const { renderer, material } = builder;
  3269. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  3270. if ( material.side === BackSide ) {
  3271. return 'false';
  3272. }
  3273. }
  3274. return builder.getFrontFacing();
  3275. }
  3276. }
  3277. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  3278. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  3279. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  3280. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  3281. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  3282. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  3283. return vec3( 0, 1, 0 );
  3284. }
  3285. return normalGeometry;
  3286. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  3287. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  3288. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  3289. let node;
  3290. if ( builder.material.flatShading === true ) {
  3291. node = normalFlat;
  3292. } else {
  3293. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  3294. }
  3295. return node;
  3296. }, 'vec3' ).once() )().toVar( 'normalView' );
  3297. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  3298. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  3299. return builder.context.setupNormal();
  3300. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  3301. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  3302. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  3303. return builder.context.setupClearcoatNormal();
  3304. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  3305. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  3306. const m = mat3( matrix );
  3307. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  3308. return m.mul( transformedNormal ).xyz;
  3309. } );
  3310. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  3311. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  3312. if ( modelNormalViewMatrix !== null ) {
  3313. return modelNormalViewMatrix.transformDirection( normal );
  3314. }
  3315. //
  3316. const transformedNormal = modelNormalMatrix.mul( normal );
  3317. return cameraViewMatrix.transformDirection( transformedNormal );
  3318. } );
  3319. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  3320. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  3321. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  3322. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  3323. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  3324. class CubeTextureNode extends TextureNode {
  3325. static get type() {
  3326. return 'CubeTextureNode';
  3327. }
  3328. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  3329. super( value, uvNode, levelNode, biasNode );
  3330. this.isCubeTextureNode = true;
  3331. }
  3332. getInputType( /*builder*/ ) {
  3333. return 'cubeTexture';
  3334. }
  3335. getDefaultUV() {
  3336. const texture = this.value;
  3337. if ( texture.mapping === CubeReflectionMapping ) {
  3338. return reflectVector;
  3339. } else if ( texture.mapping === CubeRefractionMapping ) {
  3340. return refractVector;
  3341. } else {
  3342. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  3343. return vec3( 0, 0, 0 );
  3344. }
  3345. }
  3346. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  3347. setupUV( builder, uvNode ) {
  3348. const texture = this.value;
  3349. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  3350. return vec3( uvNode.x.negate(), uvNode.yz );
  3351. } else {
  3352. return uvNode;
  3353. }
  3354. }
  3355. generateUV( builder, cubeUV ) {
  3356. return cubeUV.build( builder, 'vec3' );
  3357. }
  3358. }
  3359. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  3360. class BufferNode extends UniformNode {
  3361. static get type() {
  3362. return 'BufferNode';
  3363. }
  3364. constructor( value, bufferType, bufferCount = 0 ) {
  3365. super( value, bufferType );
  3366. this.isBufferNode = true;
  3367. this.bufferType = bufferType;
  3368. this.bufferCount = bufferCount;
  3369. }
  3370. getElementType( builder ) {
  3371. return this.getNodeType( builder );
  3372. }
  3373. getInputType( /*builder*/ ) {
  3374. return 'buffer';
  3375. }
  3376. }
  3377. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  3378. class UniformArrayElementNode extends ArrayElementNode {
  3379. static get type() {
  3380. return 'UniformArrayElementNode';
  3381. }
  3382. constructor( arrayBuffer, indexNode ) {
  3383. super( arrayBuffer, indexNode );
  3384. this.isArrayBufferElementNode = true;
  3385. }
  3386. generate( builder ) {
  3387. const snippet = super.generate( builder );
  3388. const type = this.getNodeType();
  3389. return builder.format( snippet, 'vec4', type );
  3390. }
  3391. }
  3392. class UniformArrayNode extends BufferNode {
  3393. static get type() {
  3394. return 'UniformArrayNode';
  3395. }
  3396. constructor( value, elementType = null ) {
  3397. super( null, 'vec4' );
  3398. this.array = value;
  3399. this.elementType = elementType;
  3400. this._elementType = null;
  3401. this._elementLength = 0;
  3402. this.updateType = NodeUpdateType.RENDER;
  3403. this.isArrayBufferNode = true;
  3404. }
  3405. getElementType() {
  3406. return this.elementType || this._elementType;
  3407. }
  3408. getElementLength() {
  3409. return this._elementLength;
  3410. }
  3411. update( /*frame*/ ) {
  3412. const { array, value } = this;
  3413. const elementLength = this.getElementLength();
  3414. const elementType = this.getElementType();
  3415. if ( elementLength === 1 ) {
  3416. for ( let i = 0; i < array.length; i ++ ) {
  3417. const index = i * 4;
  3418. value[ index ] = array[ i ];
  3419. }
  3420. } else if ( elementType === 'color' ) {
  3421. for ( let i = 0; i < array.length; i ++ ) {
  3422. const index = i * 4;
  3423. const vector = array[ i ];
  3424. value[ index ] = vector.r;
  3425. value[ index + 1 ] = vector.g;
  3426. value[ index + 2 ] = vector.b || 0;
  3427. //value[ index + 3 ] = vector.a || 0;
  3428. }
  3429. } else {
  3430. for ( let i = 0; i < array.length; i ++ ) {
  3431. const index = i * 4;
  3432. const vector = array[ i ];
  3433. value[ index ] = vector.x;
  3434. value[ index + 1 ] = vector.y;
  3435. value[ index + 2 ] = vector.z || 0;
  3436. value[ index + 3 ] = vector.w || 0;
  3437. }
  3438. }
  3439. }
  3440. setup( builder ) {
  3441. const length = this.array.length;
  3442. this._elementType = this.elementType === null ? getValueType( this.array[ 0 ] ) : this.elementType;
  3443. this._elementLength = builder.getTypeLength( this._elementType );
  3444. let arrayType = Float32Array;
  3445. if ( this._elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  3446. else if ( this._elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  3447. this.value = new arrayType( length * 4 );
  3448. this.bufferCount = length;
  3449. this.bufferType = builder.changeComponentType( 'vec4', builder.getComponentType( this._elementType ) );
  3450. return super.setup( builder );
  3451. }
  3452. element( indexNode ) {
  3453. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  3454. }
  3455. }
  3456. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  3457. //
  3458. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  3459. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  3460. return nodeObject( new UniformArrayNode( values, nodeType ) );
  3461. };
  3462. class ReferenceElementNode extends ArrayElementNode {
  3463. static get type() {
  3464. return 'ReferenceElementNode';
  3465. }
  3466. constructor( referenceNode, indexNode ) {
  3467. super( referenceNode, indexNode );
  3468. this.referenceNode = referenceNode;
  3469. this.isReferenceElementNode = true;
  3470. }
  3471. getNodeType() {
  3472. return this.referenceNode.uniformType;
  3473. }
  3474. generate( builder ) {
  3475. const snippet = super.generate( builder );
  3476. const arrayType = this.referenceNode.getNodeType();
  3477. const elementType = this.getNodeType();
  3478. return builder.format( snippet, arrayType, elementType );
  3479. }
  3480. }
  3481. // TODO: Extends this from ReferenceBaseNode
  3482. class ReferenceNode extends Node {
  3483. static get type() {
  3484. return 'ReferenceNode';
  3485. }
  3486. constructor( property, uniformType, object = null, count = null ) {
  3487. super();
  3488. this.property = property;
  3489. this.uniformType = uniformType;
  3490. this.object = object;
  3491. this.count = count;
  3492. this.properties = property.split( '.' );
  3493. this.reference = object;
  3494. this.node = null;
  3495. this.group = null;
  3496. this.name = null;
  3497. this.updateType = NodeUpdateType.OBJECT;
  3498. }
  3499. element( indexNode ) {
  3500. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  3501. }
  3502. setGroup( group ) {
  3503. this.group = group;
  3504. return this;
  3505. }
  3506. label( name ) {
  3507. this.name = name;
  3508. return this;
  3509. }
  3510. setNodeType( uniformType ) {
  3511. let node = null;
  3512. if ( this.count !== null ) {
  3513. node = buffer( null, uniformType, this.count );
  3514. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  3515. node = uniformArray( null, uniformType );
  3516. } else if ( uniformType === 'texture' ) {
  3517. node = texture( null );
  3518. } else if ( uniformType === 'cubeTexture' ) {
  3519. node = cubeTexture( null );
  3520. } else {
  3521. node = uniform( null, uniformType );
  3522. }
  3523. if ( this.group !== null ) {
  3524. node.setGroup( this.group );
  3525. }
  3526. if ( this.name !== null ) node.label( this.name );
  3527. this.node = node.getSelf();
  3528. }
  3529. getNodeType( builder ) {
  3530. if ( this.node === null ) {
  3531. this.updateReference( builder );
  3532. this.updateValue();
  3533. }
  3534. return this.node.getNodeType( builder );
  3535. }
  3536. getValueFromReference( object = this.reference ) {
  3537. const { properties } = this;
  3538. let value = object[ properties[ 0 ] ];
  3539. for ( let i = 1; i < properties.length; i ++ ) {
  3540. value = value[ properties[ i ] ];
  3541. }
  3542. return value;
  3543. }
  3544. updateReference( state ) {
  3545. this.reference = this.object !== null ? this.object : state.object;
  3546. return this.reference;
  3547. }
  3548. setup() {
  3549. this.updateValue();
  3550. return this.node;
  3551. }
  3552. update( /*frame*/ ) {
  3553. this.updateValue();
  3554. }
  3555. updateValue() {
  3556. if ( this.node === null ) this.setNodeType( this.uniformType );
  3557. const value = this.getValueFromReference();
  3558. if ( Array.isArray( value ) ) {
  3559. this.node.array = value;
  3560. } else {
  3561. this.node.value = value;
  3562. }
  3563. }
  3564. }
  3565. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  3566. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  3567. class MaterialReferenceNode extends ReferenceNode {
  3568. static get type() {
  3569. return 'MaterialReferenceNode';
  3570. }
  3571. constructor( property, inputType, material = null ) {
  3572. super( property, inputType, material );
  3573. this.material = material;
  3574. //this.updateType = NodeUpdateType.RENDER;
  3575. this.isMaterialReferenceNode = true;
  3576. }
  3577. /*setNodeType( node ) {
  3578. super.setNodeType( node );
  3579. this.node.groupNode = renderGroup;
  3580. }*/
  3581. updateReference( state ) {
  3582. this.reference = this.material !== null ? this.material : state.material;
  3583. return this.reference;
  3584. }
  3585. }
  3586. const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  3587. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  3588. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  3589. builder.geometry.computeTangents();
  3590. }
  3591. return attribute( 'tangent', 'vec4' );
  3592. } )();
  3593. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  3594. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.varying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  3595. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).varying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  3596. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  3597. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  3598. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  3599. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  3600. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  3601. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  3602. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  3603. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  3604. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  3605. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  3606. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  3607. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  3608. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  3609. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  3610. let bentNormal = anisotropyB.cross( positionViewDirection );
  3611. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  3612. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  3613. return bentNormal;
  3614. } )();
  3615. // Normal Mapping Without Precomputed Tangents
  3616. // http://www.thetenthplanet.de/archives/1180
  3617. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  3618. const { eye_pos, surf_norm, mapN, uv } = inputs;
  3619. const q0 = eye_pos.dFdx();
  3620. const q1 = eye_pos.dFdy();
  3621. const st0 = uv.dFdx();
  3622. const st1 = uv.dFdy();
  3623. const N = surf_norm; // normalized
  3624. const q1perp = q1.cross( N );
  3625. const q0perp = N.cross( q0 );
  3626. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  3627. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  3628. const det = T.dot( T ).max( B.dot( B ) );
  3629. const scale = faceDirection.mul( det.inverseSqrt() );
  3630. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  3631. } );
  3632. class NormalMapNode extends TempNode {
  3633. static get type() {
  3634. return 'NormalMapNode';
  3635. }
  3636. constructor( node, scaleNode = null ) {
  3637. super( 'vec3' );
  3638. this.node = node;
  3639. this.scaleNode = scaleNode;
  3640. this.normalMapType = TangentSpaceNormalMap;
  3641. }
  3642. setup( builder ) {
  3643. const { normalMapType, scaleNode } = this;
  3644. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  3645. if ( scaleNode !== null ) {
  3646. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  3647. }
  3648. let outputNode = null;
  3649. if ( normalMapType === ObjectSpaceNormalMap ) {
  3650. outputNode = transformNormalToView( normalMap );
  3651. } else if ( normalMapType === TangentSpaceNormalMap ) {
  3652. const tangent = builder.hasGeometryAttribute( 'tangent' );
  3653. if ( tangent === true ) {
  3654. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  3655. } else {
  3656. outputNode = perturbNormal2Arb( {
  3657. eye_pos: positionView,
  3658. surf_norm: normalView,
  3659. mapN: normalMap,
  3660. uv: uv()
  3661. } );
  3662. }
  3663. }
  3664. return outputNode;
  3665. }
  3666. }
  3667. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  3668. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  3669. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  3670. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  3671. // It's used to preserve the same TextureNode instance
  3672. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  3673. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  3674. return vec2(
  3675. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  3676. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  3677. ).mul( bumpScale );
  3678. } );
  3679. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  3680. const perturbNormalArb = Fn( ( inputs ) => {
  3681. const { surf_pos, surf_norm, dHdxy } = inputs;
  3682. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  3683. const vSigmaX = surf_pos.dFdx().normalize();
  3684. const vSigmaY = surf_pos.dFdy().normalize();
  3685. const vN = surf_norm; // normalized
  3686. const R1 = vSigmaY.cross( vN );
  3687. const R2 = vN.cross( vSigmaX );
  3688. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  3689. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  3690. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  3691. } );
  3692. class BumpMapNode extends TempNode {
  3693. static get type() {
  3694. return 'BumpMapNode';
  3695. }
  3696. constructor( textureNode, scaleNode = null ) {
  3697. super( 'vec3' );
  3698. this.textureNode = textureNode;
  3699. this.scaleNode = scaleNode;
  3700. }
  3701. setup() {
  3702. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  3703. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  3704. return perturbNormalArb( {
  3705. surf_pos: positionView,
  3706. surf_norm: normalView,
  3707. dHdxy
  3708. } );
  3709. }
  3710. }
  3711. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  3712. const _propertyCache = new Map();
  3713. class MaterialNode extends Node {
  3714. static get type() {
  3715. return 'MaterialNode';
  3716. }
  3717. constructor( scope ) {
  3718. super();
  3719. this.scope = scope;
  3720. }
  3721. getCache( property, type ) {
  3722. let node = _propertyCache.get( property );
  3723. if ( node === undefined ) {
  3724. node = materialReference( property, type );
  3725. _propertyCache.set( property, node );
  3726. }
  3727. return node;
  3728. }
  3729. getFloat( property ) {
  3730. return this.getCache( property, 'float' );
  3731. }
  3732. getColor( property ) {
  3733. return this.getCache( property, 'color' );
  3734. }
  3735. getTexture( property ) {
  3736. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  3737. }
  3738. setup( builder ) {
  3739. const material = builder.context.material;
  3740. const scope = this.scope;
  3741. let node = null;
  3742. if ( scope === MaterialNode.COLOR ) {
  3743. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  3744. if ( material.map && material.map.isTexture === true ) {
  3745. node = colorNode.mul( this.getTexture( 'map' ) );
  3746. } else {
  3747. node = colorNode;
  3748. }
  3749. } else if ( scope === MaterialNode.OPACITY ) {
  3750. const opacityNode = this.getFloat( scope );
  3751. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  3752. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  3753. } else {
  3754. node = opacityNode;
  3755. }
  3756. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  3757. if ( material.specularMap && material.specularMap.isTexture === true ) {
  3758. node = this.getTexture( 'specular' ).r;
  3759. } else {
  3760. node = float( 1 );
  3761. }
  3762. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  3763. const specularIntensity = this.getFloat( scope );
  3764. if ( material.specularMap ) {
  3765. node = specularIntensity.mul( this.getTexture( scope ).a );
  3766. } else {
  3767. node = specularIntensity;
  3768. }
  3769. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  3770. const specularColorNode = this.getColor( scope );
  3771. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  3772. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  3773. } else {
  3774. node = specularColorNode;
  3775. }
  3776. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  3777. const roughnessNode = this.getFloat( scope );
  3778. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  3779. node = roughnessNode.mul( this.getTexture( scope ).g );
  3780. } else {
  3781. node = roughnessNode;
  3782. }
  3783. } else if ( scope === MaterialNode.METALNESS ) {
  3784. const metalnessNode = this.getFloat( scope );
  3785. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  3786. node = metalnessNode.mul( this.getTexture( scope ).b );
  3787. } else {
  3788. node = metalnessNode;
  3789. }
  3790. } else if ( scope === MaterialNode.EMISSIVE ) {
  3791. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  3792. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  3793. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  3794. node = emissiveNode.mul( this.getTexture( scope ) );
  3795. } else {
  3796. node = emissiveNode;
  3797. }
  3798. } else if ( scope === MaterialNode.NORMAL ) {
  3799. if ( material.normalMap ) {
  3800. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  3801. node.normalMapType = material.normalMapType;
  3802. } else if ( material.bumpMap ) {
  3803. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  3804. } else {
  3805. node = normalView;
  3806. }
  3807. } else if ( scope === MaterialNode.CLEARCOAT ) {
  3808. const clearcoatNode = this.getFloat( scope );
  3809. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  3810. node = clearcoatNode.mul( this.getTexture( scope ).r );
  3811. } else {
  3812. node = clearcoatNode;
  3813. }
  3814. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  3815. const clearcoatRoughnessNode = this.getFloat( scope );
  3816. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  3817. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  3818. } else {
  3819. node = clearcoatRoughnessNode;
  3820. }
  3821. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  3822. if ( material.clearcoatNormalMap ) {
  3823. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  3824. } else {
  3825. node = normalView;
  3826. }
  3827. } else if ( scope === MaterialNode.SHEEN ) {
  3828. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  3829. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  3830. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  3831. } else {
  3832. node = sheenNode;
  3833. }
  3834. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  3835. const sheenRoughnessNode = this.getFloat( scope );
  3836. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  3837. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  3838. } else {
  3839. node = sheenRoughnessNode;
  3840. }
  3841. node = node.clamp( 0.07, 1.0 );
  3842. } else if ( scope === MaterialNode.ANISOTROPY ) {
  3843. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  3844. const anisotropyPolar = this.getTexture( scope );
  3845. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  3846. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  3847. } else {
  3848. node = materialAnisotropyVector;
  3849. }
  3850. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  3851. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  3852. if ( material.iridescenceThicknessMap ) {
  3853. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  3854. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  3855. } else {
  3856. node = iridescenceThicknessMaximum;
  3857. }
  3858. } else if ( scope === MaterialNode.TRANSMISSION ) {
  3859. const transmissionNode = this.getFloat( scope );
  3860. if ( material.transmissionMap ) {
  3861. node = transmissionNode.mul( this.getTexture( scope ).r );
  3862. } else {
  3863. node = transmissionNode;
  3864. }
  3865. } else if ( scope === MaterialNode.THICKNESS ) {
  3866. const thicknessNode = this.getFloat( scope );
  3867. if ( material.thicknessMap ) {
  3868. node = thicknessNode.mul( this.getTexture( scope ).g );
  3869. } else {
  3870. node = thicknessNode;
  3871. }
  3872. } else if ( scope === MaterialNode.IOR ) {
  3873. node = this.getFloat( scope );
  3874. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  3875. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  3876. } else if ( scope === MaterialNode.AO_MAP ) {
  3877. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  3878. } else {
  3879. const outputType = this.getNodeType( builder );
  3880. node = this.getCache( scope, outputType );
  3881. }
  3882. return node;
  3883. }
  3884. }
  3885. MaterialNode.ALPHA_TEST = 'alphaTest';
  3886. MaterialNode.COLOR = 'color';
  3887. MaterialNode.OPACITY = 'opacity';
  3888. MaterialNode.SHININESS = 'shininess';
  3889. MaterialNode.SPECULAR = 'specular';
  3890. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  3891. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  3892. MaterialNode.SPECULAR_COLOR = 'specularColor';
  3893. MaterialNode.REFLECTIVITY = 'reflectivity';
  3894. MaterialNode.ROUGHNESS = 'roughness';
  3895. MaterialNode.METALNESS = 'metalness';
  3896. MaterialNode.NORMAL = 'normal';
  3897. MaterialNode.CLEARCOAT = 'clearcoat';
  3898. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  3899. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  3900. MaterialNode.EMISSIVE = 'emissive';
  3901. MaterialNode.ROTATION = 'rotation';
  3902. MaterialNode.SHEEN = 'sheen';
  3903. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  3904. MaterialNode.ANISOTROPY = 'anisotropy';
  3905. MaterialNode.IRIDESCENCE = 'iridescence';
  3906. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  3907. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  3908. MaterialNode.IOR = 'ior';
  3909. MaterialNode.TRANSMISSION = 'transmission';
  3910. MaterialNode.THICKNESS = 'thickness';
  3911. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  3912. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  3913. MaterialNode.LINE_SCALE = 'scale';
  3914. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  3915. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  3916. MaterialNode.LINE_WIDTH = 'linewidth';
  3917. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  3918. MaterialNode.POINT_WIDTH = 'pointWidth';
  3919. MaterialNode.DISPERSION = 'dispersion';
  3920. MaterialNode.LIGHT_MAP = 'light';
  3921. MaterialNode.AO_MAP = 'ao';
  3922. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  3923. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  3924. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  3925. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  3926. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  3927. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  3928. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  3929. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  3930. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  3931. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  3932. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  3933. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  3934. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL ).context( { getUV: null } );
  3935. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  3936. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  3937. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL ).context( { getUV: null } );
  3938. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  3939. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  3940. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  3941. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  3942. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  3943. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  3944. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  3945. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  3946. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  3947. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  3948. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  3949. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  3950. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  3951. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  3952. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  3953. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  3954. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  3955. const materialPointWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_WIDTH );
  3956. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  3957. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  3958. const materialAOMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO_MAP );
  3959. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  3960. return frame.material;
  3961. } ).onRenderUpdate( function ( { material } ) {
  3962. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  3963. } );
  3964. class ModelViewProjectionNode extends TempNode {
  3965. static get type() {
  3966. return 'ModelViewProjectionNode';
  3967. }
  3968. constructor( positionNode = null ) {
  3969. super( 'vec4' );
  3970. this.positionNode = positionNode;
  3971. }
  3972. setup( builder ) {
  3973. if ( builder.shaderStage === 'fragment' ) {
  3974. return varying( builder.context.mvp );
  3975. }
  3976. const position = this.positionNode || positionLocal;
  3977. const viewMatrix = builder.renderer.nodes.modelViewMatrix || modelViewMatrix;
  3978. return cameraProjectionMatrix.mul( viewMatrix ).mul( position );
  3979. }
  3980. }
  3981. const modelViewProjection = /*@__PURE__*/ nodeProxy( ModelViewProjectionNode );
  3982. class IndexNode extends Node {
  3983. static get type() {
  3984. return 'IndexNode';
  3985. }
  3986. constructor( scope ) {
  3987. super( 'uint' );
  3988. this.scope = scope;
  3989. this.isInstanceIndexNode = true;
  3990. }
  3991. generate( builder ) {
  3992. const nodeType = this.getNodeType( builder );
  3993. const scope = this.scope;
  3994. let propertyName;
  3995. if ( scope === IndexNode.VERTEX ) {
  3996. // The index of a vertex within a mesh.
  3997. propertyName = builder.getVertexIndex();
  3998. } else if ( scope === IndexNode.INSTANCE ) {
  3999. // The index of either a mesh instance or an invocation of a compute shader.
  4000. propertyName = builder.getInstanceIndex();
  4001. } else if ( scope === IndexNode.DRAW ) {
  4002. // The index of a draw call.
  4003. propertyName = builder.getDrawIndex();
  4004. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  4005. // The index of a compute invocation within the scope of a workgroup load.
  4006. propertyName = builder.getInvocationLocalIndex();
  4007. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  4008. // The index of a compute invocation within the scope of a subgroup.
  4009. propertyName = builder.getInvocationSubgroupIndex();
  4010. } else if ( scope === IndexNode.SUBGROUP ) {
  4011. // The index of the subgroup the current compute invocation belongs to.
  4012. propertyName = builder.getSubgroupIndex();
  4013. } else {
  4014. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  4015. }
  4016. let output;
  4017. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  4018. output = propertyName;
  4019. } else {
  4020. const nodeVarying = varying( this );
  4021. output = nodeVarying.build( builder, nodeType );
  4022. }
  4023. return output;
  4024. }
  4025. }
  4026. IndexNode.VERTEX = 'vertex';
  4027. IndexNode.INSTANCE = 'instance';
  4028. IndexNode.SUBGROUP = 'subgroup';
  4029. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  4030. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  4031. IndexNode.DRAW = 'draw';
  4032. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  4033. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  4034. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  4035. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  4036. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  4037. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  4038. class InstanceNode extends Node {
  4039. static get type() {
  4040. return 'InstanceNode';
  4041. }
  4042. constructor( count, instanceMatrix, instanceColor ) {
  4043. super( 'void' );
  4044. this.count = count;
  4045. this.instanceMatrix = instanceMatrix;
  4046. this.instanceColor = instanceColor;
  4047. this.instanceMatrixNode = null;
  4048. this.instanceColorNode = null;
  4049. this.updateType = NodeUpdateType.FRAME;
  4050. this.buffer = null;
  4051. this.bufferColor = null;
  4052. }
  4053. setup( builder ) {
  4054. const { count, instanceMatrix, instanceColor } = this;
  4055. let { instanceMatrixNode, instanceColorNode } = this;
  4056. if ( instanceMatrixNode === null ) {
  4057. // Both WebGPU and WebGL backends have UBO max limited to 64kb. Matrix count number bigger than 1000 ( 16 * 4 * 1000 = 64kb ) will fallback to attribute.
  4058. if ( count <= 1000 ) {
  4059. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  4060. } else {
  4061. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  4062. this.buffer = buffer;
  4063. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  4064. const instanceBuffers = [
  4065. // F.Signature -> bufferAttribute( array, type, stride, offset )
  4066. bufferFn( buffer, 'vec4', 16, 0 ),
  4067. bufferFn( buffer, 'vec4', 16, 4 ),
  4068. bufferFn( buffer, 'vec4', 16, 8 ),
  4069. bufferFn( buffer, 'vec4', 16, 12 )
  4070. ];
  4071. instanceMatrixNode = mat4( ...instanceBuffers );
  4072. }
  4073. this.instanceMatrixNode = instanceMatrixNode;
  4074. }
  4075. if ( instanceColor && instanceColorNode === null ) {
  4076. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  4077. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  4078. this.bufferColor = buffer;
  4079. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  4080. this.instanceColorNode = instanceColorNode;
  4081. }
  4082. // POSITION
  4083. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  4084. positionLocal.assign( instancePosition );
  4085. // NORMAL
  4086. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  4087. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  4088. // ASSIGNS
  4089. normalLocal.assign( instanceNormal );
  4090. }
  4091. // COLOR
  4092. if ( this.instanceColorNode !== null ) {
  4093. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  4094. }
  4095. }
  4096. update( /*frame*/ ) {
  4097. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer != null && this.instanceMatrix.version !== this.buffer.version ) {
  4098. this.buffer.version = this.instanceMatrix.version;
  4099. }
  4100. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor != null && this.instanceColor.version !== this.bufferColor.version ) {
  4101. this.bufferColor.version = this.instanceColor.version;
  4102. }
  4103. }
  4104. }
  4105. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  4106. class InstancedMeshNode extends InstanceNode {
  4107. static get type() {
  4108. return 'InstancedMeshNode';
  4109. }
  4110. constructor( instanceMesh ) {
  4111. const { count, instanceMatrix, instanceColor } = instanceMesh;
  4112. super( count, instanceMatrix, instanceColor );
  4113. this.instanceMesh = instanceMesh;
  4114. }
  4115. }
  4116. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode );
  4117. class BatchNode extends Node {
  4118. static get type() {
  4119. return 'BatchNode';
  4120. }
  4121. constructor( batchMesh ) {
  4122. super( 'void' );
  4123. this.batchMesh = batchMesh;
  4124. this.batchingIdNode = null;
  4125. }
  4126. setup( builder ) {
  4127. // POSITION
  4128. if ( this.batchingIdNode === null ) {
  4129. if ( builder.getDrawIndex() === null ) {
  4130. this.batchingIdNode = instanceIndex;
  4131. } else {
  4132. this.batchingIdNode = drawIndex;
  4133. }
  4134. }
  4135. const getIndirectIndex = Fn( ( [ id ] ) => {
  4136. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  4137. const x = int( id ).modInt( int( size ) );
  4138. const y = int( id ).div( int( size ) );
  4139. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  4140. } ).setLayout( {
  4141. name: 'getIndirectIndex',
  4142. type: 'uint',
  4143. inputs: [
  4144. { name: 'id', type: 'int' }
  4145. ]
  4146. } );
  4147. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  4148. const matricesTexture = this.batchMesh._matricesTexture;
  4149. const size = textureSize( textureLoad( matricesTexture ), 0 );
  4150. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  4151. const x = j.modInt( size );
  4152. const y = j.div( int( size ) );
  4153. const batchingMatrix = mat4(
  4154. textureLoad( matricesTexture, ivec2( x, y ) ),
  4155. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  4156. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  4157. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  4158. );
  4159. const colorsTexture = this.batchMesh._colorsTexture;
  4160. if ( colorsTexture !== null ) {
  4161. const getBatchingColor = Fn( ( [ id ] ) => {
  4162. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  4163. const j = id;
  4164. const x = j.modInt( size );
  4165. const y = j.div( size );
  4166. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  4167. } ).setLayout( {
  4168. name: 'getBatchingColor',
  4169. type: 'vec3',
  4170. inputs: [
  4171. { name: 'id', type: 'int' }
  4172. ]
  4173. } );
  4174. const color = getBatchingColor( indirectId );
  4175. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  4176. }
  4177. const bm = mat3( batchingMatrix );
  4178. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  4179. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  4180. const batchingNormal = bm.mul( transformedNormal ).xyz;
  4181. normalLocal.assign( batchingNormal );
  4182. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  4183. tangentLocal.mulAssign( bm );
  4184. }
  4185. }
  4186. }
  4187. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  4188. const _frameId = new WeakMap();
  4189. class SkinningNode extends Node {
  4190. static get type() {
  4191. return 'SkinningNode';
  4192. }
  4193. constructor( skinnedMesh, useReference = false ) {
  4194. super( 'void' );
  4195. this.skinnedMesh = skinnedMesh;
  4196. this.useReference = useReference;
  4197. this.updateType = NodeUpdateType.OBJECT;
  4198. //
  4199. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  4200. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  4201. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  4202. if ( useReference ) {
  4203. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  4204. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  4205. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  4206. } else {
  4207. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  4208. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  4209. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  4210. }
  4211. this.bindMatrixNode = bindMatrixNode;
  4212. this.bindMatrixInverseNode = bindMatrixInverseNode;
  4213. this.boneMatricesNode = boneMatricesNode;
  4214. this.previousBoneMatricesNode = null;
  4215. }
  4216. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  4217. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  4218. const boneMatX = boneMatrices.element( skinIndexNode.x );
  4219. const boneMatY = boneMatrices.element( skinIndexNode.y );
  4220. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  4221. const boneMatW = boneMatrices.element( skinIndexNode.w );
  4222. // POSITION
  4223. const skinVertex = bindMatrixNode.mul( position );
  4224. const skinned = add(
  4225. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  4226. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  4227. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  4228. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  4229. );
  4230. return bindMatrixInverseNode.mul( skinned ).xyz;
  4231. }
  4232. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  4233. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  4234. const boneMatX = boneMatrices.element( skinIndexNode.x );
  4235. const boneMatY = boneMatrices.element( skinIndexNode.y );
  4236. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  4237. const boneMatW = boneMatrices.element( skinIndexNode.w );
  4238. // NORMAL
  4239. let skinMatrix = add(
  4240. skinWeightNode.x.mul( boneMatX ),
  4241. skinWeightNode.y.mul( boneMatY ),
  4242. skinWeightNode.z.mul( boneMatZ ),
  4243. skinWeightNode.w.mul( boneMatW )
  4244. );
  4245. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  4246. return skinMatrix.transformDirection( normal ).xyz;
  4247. }
  4248. getPreviousSkinnedPosition( builder ) {
  4249. const skinnedMesh = builder.object;
  4250. if ( this.previousBoneMatricesNode === null ) {
  4251. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  4252. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  4253. }
  4254. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  4255. }
  4256. needsPreviousBoneMatrices( builder ) {
  4257. const mrt = builder.renderer.getMRT();
  4258. return mrt && mrt.has( 'velocity' );
  4259. }
  4260. setup( builder ) {
  4261. if ( this.needsPreviousBoneMatrices( builder ) ) {
  4262. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  4263. }
  4264. const skinPosition = this.getSkinnedPosition();
  4265. positionLocal.assign( skinPosition );
  4266. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  4267. const skinNormal = this.getSkinnedNormal();
  4268. normalLocal.assign( skinNormal );
  4269. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  4270. tangentLocal.assign( skinNormal );
  4271. }
  4272. }
  4273. }
  4274. generate( builder, output ) {
  4275. if ( output !== 'void' ) {
  4276. return positionLocal.build( builder, output );
  4277. }
  4278. }
  4279. update( frame ) {
  4280. const object = this.useReference ? frame.object : this.skinnedMesh;
  4281. const skeleton = object.skeleton;
  4282. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  4283. _frameId.set( skeleton, frame.frameId );
  4284. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  4285. skeleton.update();
  4286. }
  4287. }
  4288. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  4289. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  4290. class LoopNode extends Node {
  4291. static get type() {
  4292. return 'LoopNode';
  4293. }
  4294. constructor( params = [] ) {
  4295. super();
  4296. this.params = params;
  4297. }
  4298. getVarName( index ) {
  4299. return String.fromCharCode( 'i'.charCodeAt() + index );
  4300. }
  4301. getProperties( builder ) {
  4302. const properties = builder.getNodeProperties( this );
  4303. if ( properties.stackNode !== undefined ) return properties;
  4304. //
  4305. const inputs = {};
  4306. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  4307. const param = this.params[ i ];
  4308. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  4309. const type = ( param.isNode !== true && param.type ) || 'int';
  4310. inputs[ name ] = expression( name, type );
  4311. }
  4312. const stack = builder.addStack(); // TODO: cache() it
  4313. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  4314. properties.stackNode = stack;
  4315. builder.removeStack();
  4316. return properties;
  4317. }
  4318. getNodeType( builder ) {
  4319. const { returnsNode } = this.getProperties( builder );
  4320. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  4321. }
  4322. setup( builder ) {
  4323. // setup properties
  4324. this.getProperties( builder );
  4325. }
  4326. generate( builder ) {
  4327. const properties = this.getProperties( builder );
  4328. const params = this.params;
  4329. const stackNode = properties.stackNode;
  4330. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  4331. const param = params[ i ];
  4332. let start = null, end = null, name = null, type = null, condition = null, update = null;
  4333. if ( param.isNode ) {
  4334. type = 'int';
  4335. name = this.getVarName( i );
  4336. start = '0';
  4337. end = param.build( builder, type );
  4338. condition = '<';
  4339. } else {
  4340. type = param.type || 'int';
  4341. name = param.name || this.getVarName( i );
  4342. start = param.start;
  4343. end = param.end;
  4344. condition = param.condition;
  4345. update = param.update;
  4346. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  4347. else if ( start && start.isNode ) start = start.build( builder, type );
  4348. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  4349. else if ( end && end.isNode ) end = end.build( builder, type );
  4350. if ( start !== undefined && end === undefined ) {
  4351. start = start + ' - 1';
  4352. end = '0';
  4353. condition = '>=';
  4354. } else if ( end !== undefined && start === undefined ) {
  4355. start = '0';
  4356. condition = '<';
  4357. }
  4358. if ( condition === undefined ) {
  4359. if ( Number( start ) > Number( end ) ) {
  4360. condition = '>=';
  4361. } else {
  4362. condition = '<';
  4363. }
  4364. }
  4365. }
  4366. const internalParam = { start, end, condition };
  4367. //
  4368. const startSnippet = internalParam.start;
  4369. const endSnippet = internalParam.end;
  4370. let declarationSnippet = '';
  4371. let conditionalSnippet = '';
  4372. let updateSnippet = '';
  4373. if ( ! update ) {
  4374. if ( type === 'int' || type === 'uint' ) {
  4375. if ( condition.includes( '<' ) ) update = '++';
  4376. else update = '--';
  4377. } else {
  4378. if ( condition.includes( '<' ) ) update = '+= 1.';
  4379. else update = '-= 1.';
  4380. }
  4381. }
  4382. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  4383. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  4384. updateSnippet += name + ' ' + update;
  4385. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  4386. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  4387. }
  4388. const stackSnippet = stackNode.build( builder, 'void' );
  4389. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  4390. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  4391. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  4392. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  4393. }
  4394. builder.addFlowTab();
  4395. return returnsSnippet;
  4396. }
  4397. }
  4398. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  4399. const Continue = () => expression( 'continue' ).append();
  4400. const Break = () => expression( 'break' ).append();
  4401. //
  4402. const loop = ( ...params ) => { // @deprecated, r168
  4403. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  4404. return Loop( ...params );
  4405. };
  4406. const _morphTextures = /*@__PURE__*/ new WeakMap();
  4407. const _morphVec4 = /*@__PURE__*/ new Vector4();
  4408. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  4409. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  4410. const y = texelIndex.div( width );
  4411. const x = texelIndex.sub( y.mul( width ) );
  4412. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  4413. return bufferAttrib.mul( influence );
  4414. } );
  4415. function getEntry( geometry ) {
  4416. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  4417. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  4418. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  4419. // instead of using attributes, the WebGL 2 code path encodes morph targets
  4420. // into an array of data textures. Each layer represents a single morph target.
  4421. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  4422. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  4423. let entry = _morphTextures.get( geometry );
  4424. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  4425. if ( entry !== undefined ) entry.texture.dispose();
  4426. const morphTargets = geometry.morphAttributes.position || [];
  4427. const morphNormals = geometry.morphAttributes.normal || [];
  4428. const morphColors = geometry.morphAttributes.color || [];
  4429. let vertexDataCount = 0;
  4430. if ( hasMorphPosition === true ) vertexDataCount = 1;
  4431. if ( hasMorphNormals === true ) vertexDataCount = 2;
  4432. if ( hasMorphColors === true ) vertexDataCount = 3;
  4433. let width = geometry.attributes.position.count * vertexDataCount;
  4434. let height = 1;
  4435. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  4436. if ( width > maxTextureSize ) {
  4437. height = Math.ceil( width / maxTextureSize );
  4438. width = maxTextureSize;
  4439. }
  4440. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  4441. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  4442. bufferTexture.type = FloatType;
  4443. bufferTexture.needsUpdate = true;
  4444. // fill buffer
  4445. const vertexDataStride = vertexDataCount * 4;
  4446. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  4447. const morphTarget = morphTargets[ i ];
  4448. const morphNormal = morphNormals[ i ];
  4449. const morphColor = morphColors[ i ];
  4450. const offset = width * height * 4 * i;
  4451. for ( let j = 0; j < morphTarget.count; j ++ ) {
  4452. const stride = j * vertexDataStride;
  4453. if ( hasMorphPosition === true ) {
  4454. _morphVec4.fromBufferAttribute( morphTarget, j );
  4455. buffer[ offset + stride + 0 ] = _morphVec4.x;
  4456. buffer[ offset + stride + 1 ] = _morphVec4.y;
  4457. buffer[ offset + stride + 2 ] = _morphVec4.z;
  4458. buffer[ offset + stride + 3 ] = 0;
  4459. }
  4460. if ( hasMorphNormals === true ) {
  4461. _morphVec4.fromBufferAttribute( morphNormal, j );
  4462. buffer[ offset + stride + 4 ] = _morphVec4.x;
  4463. buffer[ offset + stride + 5 ] = _morphVec4.y;
  4464. buffer[ offset + stride + 6 ] = _morphVec4.z;
  4465. buffer[ offset + stride + 7 ] = 0;
  4466. }
  4467. if ( hasMorphColors === true ) {
  4468. _morphVec4.fromBufferAttribute( morphColor, j );
  4469. buffer[ offset + stride + 8 ] = _morphVec4.x;
  4470. buffer[ offset + stride + 9 ] = _morphVec4.y;
  4471. buffer[ offset + stride + 10 ] = _morphVec4.z;
  4472. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  4473. }
  4474. }
  4475. }
  4476. entry = {
  4477. count: morphTargetsCount,
  4478. texture: bufferTexture,
  4479. stride: vertexDataCount,
  4480. size: new Vector2( width, height )
  4481. };
  4482. _morphTextures.set( geometry, entry );
  4483. function disposeTexture() {
  4484. bufferTexture.dispose();
  4485. _morphTextures.delete( geometry );
  4486. geometry.removeEventListener( 'dispose', disposeTexture );
  4487. }
  4488. geometry.addEventListener( 'dispose', disposeTexture );
  4489. }
  4490. return entry;
  4491. }
  4492. class MorphNode extends Node {
  4493. static get type() {
  4494. return 'MorphNode';
  4495. }
  4496. constructor( mesh ) {
  4497. super( 'void' );
  4498. this.mesh = mesh;
  4499. this.morphBaseInfluence = uniform( 1 );
  4500. this.updateType = NodeUpdateType.OBJECT;
  4501. }
  4502. setup( builder ) {
  4503. const { geometry } = builder;
  4504. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  4505. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  4506. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  4507. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  4508. // nodes
  4509. const { texture: bufferMap, stride, size } = getEntry( geometry );
  4510. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  4511. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  4512. const width = int( size.width );
  4513. Loop( morphTargetsCount, ( { i } ) => {
  4514. const influence = float( 0 ).toVar();
  4515. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  4516. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  4517. } else {
  4518. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  4519. }
  4520. if ( hasMorphPosition === true ) {
  4521. positionLocal.addAssign( getMorph( {
  4522. bufferMap,
  4523. influence,
  4524. stride,
  4525. width,
  4526. depth: i,
  4527. offset: int( 0 )
  4528. } ) );
  4529. }
  4530. if ( hasMorphNormals === true ) {
  4531. normalLocal.addAssign( getMorph( {
  4532. bufferMap,
  4533. influence,
  4534. stride,
  4535. width,
  4536. depth: i,
  4537. offset: int( 1 )
  4538. } ) );
  4539. }
  4540. } );
  4541. }
  4542. update() {
  4543. const morphBaseInfluence = this.morphBaseInfluence;
  4544. if ( this.mesh.geometry.morphTargetsRelative ) {
  4545. morphBaseInfluence.value = 1;
  4546. } else {
  4547. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  4548. }
  4549. }
  4550. }
  4551. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  4552. class LightingNode extends Node {
  4553. static get type() {
  4554. return 'LightingNode';
  4555. }
  4556. constructor() {
  4557. super( 'vec3' );
  4558. this.isLightingNode = true;
  4559. }
  4560. generate( /*builder*/ ) {
  4561. console.warn( 'Abstract function.' );
  4562. }
  4563. }
  4564. class AONode extends LightingNode {
  4565. static get type() {
  4566. return 'AONode';
  4567. }
  4568. constructor( aoNode = null ) {
  4569. super();
  4570. this.aoNode = aoNode;
  4571. }
  4572. setup( builder ) {
  4573. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  4574. }
  4575. }
  4576. class LightingContextNode extends ContextNode {
  4577. static get type() {
  4578. return 'LightingContextNode';
  4579. }
  4580. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  4581. super( node );
  4582. this.lightingModel = lightingModel;
  4583. this.backdropNode = backdropNode;
  4584. this.backdropAlphaNode = backdropAlphaNode;
  4585. this._value = null;
  4586. }
  4587. getContext() {
  4588. const { backdropNode, backdropAlphaNode } = this;
  4589. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  4590. directSpecular = vec3().toVar( 'directSpecular' ),
  4591. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  4592. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  4593. const reflectedLight = {
  4594. directDiffuse,
  4595. directSpecular,
  4596. indirectDiffuse,
  4597. indirectSpecular
  4598. };
  4599. const context = {
  4600. radiance: vec3().toVar( 'radiance' ),
  4601. irradiance: vec3().toVar( 'irradiance' ),
  4602. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  4603. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  4604. reflectedLight,
  4605. backdrop: backdropNode,
  4606. backdropAlpha: backdropAlphaNode
  4607. };
  4608. return context;
  4609. }
  4610. setup( builder ) {
  4611. this.value = this._value || ( this._value = this.getContext() );
  4612. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  4613. return super.setup( builder );
  4614. }
  4615. }
  4616. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  4617. class IrradianceNode extends LightingNode {
  4618. static get type() {
  4619. return 'IrradianceNode';
  4620. }
  4621. constructor( node ) {
  4622. super();
  4623. this.node = node;
  4624. }
  4625. setup( builder ) {
  4626. builder.context.irradiance.addAssign( this.node );
  4627. }
  4628. }
  4629. let screenSizeVec, viewportVec;
  4630. class ScreenNode extends Node {
  4631. static get type() {
  4632. return 'ScreenNode';
  4633. }
  4634. constructor( scope ) {
  4635. super();
  4636. this.scope = scope;
  4637. this.isViewportNode = true;
  4638. }
  4639. getNodeType() {
  4640. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  4641. else return 'vec2';
  4642. }
  4643. getUpdateType() {
  4644. let updateType = NodeUpdateType.NONE;
  4645. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  4646. updateType = NodeUpdateType.RENDER;
  4647. }
  4648. this.updateType = updateType;
  4649. return updateType;
  4650. }
  4651. update( { renderer } ) {
  4652. const renderTarget = renderer.getRenderTarget();
  4653. if ( this.scope === ScreenNode.VIEWPORT ) {
  4654. if ( renderTarget !== null ) {
  4655. viewportVec.copy( renderTarget.viewport );
  4656. } else {
  4657. renderer.getViewport( viewportVec );
  4658. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  4659. }
  4660. } else {
  4661. if ( renderTarget !== null ) {
  4662. screenSizeVec.width = renderTarget.width;
  4663. screenSizeVec.height = renderTarget.height;
  4664. } else {
  4665. renderer.getDrawingBufferSize( screenSizeVec );
  4666. }
  4667. }
  4668. }
  4669. setup( /*builder*/ ) {
  4670. const scope = this.scope;
  4671. let output = null;
  4672. if ( scope === ScreenNode.SIZE ) {
  4673. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  4674. } else if ( scope === ScreenNode.VIEWPORT ) {
  4675. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  4676. } else {
  4677. output = vec2( screenCoordinate.div( screenSize ) );
  4678. }
  4679. return output;
  4680. }
  4681. generate( builder ) {
  4682. if ( this.scope === ScreenNode.COORDINATE ) {
  4683. let coord = builder.getFragCoord();
  4684. if ( builder.isFlipY() ) {
  4685. // follow webgpu standards
  4686. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  4687. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  4688. }
  4689. return coord;
  4690. }
  4691. return super.generate( builder );
  4692. }
  4693. }
  4694. ScreenNode.COORDINATE = 'coordinate';
  4695. ScreenNode.VIEWPORT = 'viewport';
  4696. ScreenNode.SIZE = 'size';
  4697. ScreenNode.UV = 'uv';
  4698. // Screen
  4699. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  4700. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  4701. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  4702. // Viewport
  4703. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  4704. const viewportSize = viewport.zw;
  4705. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  4706. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  4707. // Deprecated
  4708. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  4709. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  4710. return screenSize;
  4711. }, 'vec2' ).once() )();
  4712. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  4713. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  4714. return screenUV;
  4715. }, 'vec2' ).once() )();
  4716. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  4717. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  4718. return screenUV.flipY();
  4719. }, 'vec2' ).once() )();
  4720. const _size$4 = /*@__PURE__*/ new Vector2();
  4721. class ViewportTextureNode extends TextureNode {
  4722. static get type() {
  4723. return 'ViewportTextureNode';
  4724. }
  4725. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  4726. if ( framebufferTexture === null ) {
  4727. framebufferTexture = new FramebufferTexture();
  4728. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  4729. }
  4730. super( framebufferTexture, uvNode, levelNode );
  4731. this.generateMipmaps = false;
  4732. this.isOutputTextureNode = true;
  4733. this.updateBeforeType = NodeUpdateType.FRAME;
  4734. }
  4735. updateBefore( frame ) {
  4736. const renderer = frame.renderer;
  4737. renderer.getDrawingBufferSize( _size$4 );
  4738. //
  4739. const framebufferTexture = this.value;
  4740. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  4741. framebufferTexture.image.width = _size$4.width;
  4742. framebufferTexture.image.height = _size$4.height;
  4743. framebufferTexture.needsUpdate = true;
  4744. }
  4745. //
  4746. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  4747. framebufferTexture.generateMipmaps = this.generateMipmaps;
  4748. renderer.copyFramebufferToTexture( framebufferTexture );
  4749. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  4750. }
  4751. clone() {
  4752. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  4753. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  4754. return viewportTextureNode;
  4755. }
  4756. }
  4757. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  4758. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  4759. let sharedDepthbuffer = null;
  4760. class ViewportDepthTextureNode extends ViewportTextureNode {
  4761. static get type() {
  4762. return 'ViewportDepthTextureNode';
  4763. }
  4764. constructor( uvNode = screenUV, levelNode = null ) {
  4765. if ( sharedDepthbuffer === null ) {
  4766. sharedDepthbuffer = new DepthTexture();
  4767. }
  4768. super( uvNode, levelNode, sharedDepthbuffer );
  4769. }
  4770. }
  4771. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  4772. class ViewportDepthNode extends Node {
  4773. static get type() {
  4774. return 'ViewportDepthNode';
  4775. }
  4776. constructor( scope, valueNode = null ) {
  4777. super( 'float' );
  4778. this.scope = scope;
  4779. this.valueNode = valueNode;
  4780. this.isViewportDepthNode = true;
  4781. }
  4782. generate( builder ) {
  4783. const { scope } = this;
  4784. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  4785. return builder.getFragDepth();
  4786. }
  4787. return super.generate( builder );
  4788. }
  4789. setup( { camera } ) {
  4790. const { scope } = this;
  4791. const value = this.valueNode;
  4792. let node = null;
  4793. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  4794. if ( value !== null ) {
  4795. node = depthBase().assign( value );
  4796. }
  4797. } else if ( scope === ViewportDepthNode.DEPTH ) {
  4798. if ( camera.isPerspectiveCamera ) {
  4799. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  4800. } else {
  4801. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  4802. }
  4803. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  4804. if ( value !== null ) {
  4805. if ( camera.isPerspectiveCamera ) {
  4806. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  4807. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  4808. } else {
  4809. node = value;
  4810. }
  4811. } else {
  4812. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  4813. }
  4814. }
  4815. return node;
  4816. }
  4817. }
  4818. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  4819. ViewportDepthNode.DEPTH = 'depth';
  4820. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  4821. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  4822. // -near maps to 0; -far maps to 1
  4823. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  4824. // maps orthographic depth in [ 0, 1 ] to viewZ
  4825. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  4826. // NOTE: https://twitter.com/gonnavis/status/1377183786949959682
  4827. // -near maps to 0; -far maps to 1
  4828. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  4829. // maps perspective depth in [ 0, 1 ] to viewZ
  4830. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  4831. // -near maps to 0; -far maps to 1
  4832. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  4833. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  4834. // The final logarithmic depth formula used here is adapted from one described in an
  4835. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  4836. // which was an improvement upon an earlier formula one described in an
  4837. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  4838. // Ulrich's formula is the following:
  4839. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  4840. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  4841. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  4842. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  4843. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  4844. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  4845. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  4846. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  4847. // be used, and ultimately Ulrich's "near plane" version was chosen.
  4848. // Outerra eventually made another improvement to their original "C-constant" variant,
  4849. // but it still does not incorporate the camera near plane (for this version,
  4850. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  4851. // Here we make 4 changes to Ulrich's formula:
  4852. // 1. Clamp the camera near plane so we don't divide by 0.
  4853. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  4854. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  4855. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  4856. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  4857. // so we do the same here, hence the 'viewZ.negate()' call.
  4858. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  4859. near = near.max( 1e-6 ).toVar();
  4860. const numerator = log2( viewZ.negate().div( near ) );
  4861. const denominator = log2( far.div( near ) );
  4862. return numerator.div( denominator );
  4863. };
  4864. // maps logarithmic depth in [ 0, 1 ] to viewZ
  4865. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  4866. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  4867. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  4868. // a negative viewZ).
  4869. const exponent = depth.mul( log( far.div( near ) ) );
  4870. return float( Math.E ).pow( exponent ).mul( near ).negate();
  4871. };
  4872. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  4873. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  4874. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  4875. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  4876. depth.assign = ( value ) => depthBase( value );
  4877. class BuiltinNode extends Node {
  4878. constructor( name ) {
  4879. super( 'float' );
  4880. this.name = name;
  4881. this.isBuiltinNode = true;
  4882. }
  4883. generate( /* builder */ ) {
  4884. return this.name;
  4885. }
  4886. }
  4887. const builtin = nodeProxy( BuiltinNode );
  4888. class ClippingNode extends Node {
  4889. static get type() {
  4890. return 'ClippingNode';
  4891. }
  4892. constructor( scope = ClippingNode.DEFAULT ) {
  4893. super();
  4894. this.scope = scope;
  4895. }
  4896. setup( builder ) {
  4897. super.setup( builder );
  4898. const clippingContext = builder.clippingContext;
  4899. const { intersectionPlanes, unionPlanes } = clippingContext;
  4900. this.hardwareClipping = builder.material.hardwareClipping;
  4901. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  4902. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  4903. } else if ( this.scope === ClippingNode.HARDWARE ) {
  4904. return this.setupHardwareClipping( unionPlanes, builder );
  4905. } else {
  4906. return this.setupDefault( intersectionPlanes, unionPlanes );
  4907. }
  4908. }
  4909. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  4910. return Fn( () => {
  4911. const distanceToPlane = float().toVar( 'distanceToPlane' );
  4912. const distanceGradient = float().toVar( 'distanceToGradient' );
  4913. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  4914. const numUnionPlanes = unionPlanes.length;
  4915. if ( ! this.hardwareClipping && numUnionPlanes > 0 ) {
  4916. const clippingPlanes = uniformArray( unionPlanes );
  4917. Loop( numUnionPlanes, ( { i } ) => {
  4918. const plane = clippingPlanes.element( i );
  4919. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  4920. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  4921. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  4922. } );
  4923. }
  4924. const numIntersectionPlanes = intersectionPlanes.length;
  4925. if ( numIntersectionPlanes > 0 ) {
  4926. const clippingPlanes = uniformArray( intersectionPlanes );
  4927. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  4928. Loop( numIntersectionPlanes, ( { i } ) => {
  4929. const plane = clippingPlanes.element( i );
  4930. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  4931. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  4932. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  4933. } );
  4934. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  4935. }
  4936. diffuseColor.a.mulAssign( clipOpacity );
  4937. diffuseColor.a.equal( 0.0 ).discard();
  4938. } )();
  4939. }
  4940. setupDefault( intersectionPlanes, unionPlanes ) {
  4941. return Fn( () => {
  4942. const numUnionPlanes = unionPlanes.length;
  4943. if ( ! this.hardwareClipping && numUnionPlanes > 0 ) {
  4944. const clippingPlanes = uniformArray( unionPlanes );
  4945. Loop( numUnionPlanes, ( { i } ) => {
  4946. const plane = clippingPlanes.element( i );
  4947. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  4948. } );
  4949. }
  4950. const numIntersectionPlanes = intersectionPlanes.length;
  4951. if ( numIntersectionPlanes > 0 ) {
  4952. const clippingPlanes = uniformArray( intersectionPlanes );
  4953. const clipped = bool( true ).toVar( 'clipped' );
  4954. Loop( numIntersectionPlanes, ( { i } ) => {
  4955. const plane = clippingPlanes.element( i );
  4956. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  4957. } );
  4958. clipped.discard();
  4959. }
  4960. } )();
  4961. }
  4962. setupHardwareClipping( unionPlanes, builder ) {
  4963. const numUnionPlanes = unionPlanes.length;
  4964. builder.enableHardwareClipping( numUnionPlanes );
  4965. return Fn( () => {
  4966. const clippingPlanes = uniformArray( unionPlanes );
  4967. const hw_clip_distances = builtin( builder.getClipDistance() );
  4968. Loop( numUnionPlanes, ( { i } ) => {
  4969. const plane = clippingPlanes.element( i );
  4970. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  4971. hw_clip_distances.element( i ).assign( distance );
  4972. } );
  4973. } )();
  4974. }
  4975. }
  4976. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  4977. ClippingNode.DEFAULT = 'default';
  4978. ClippingNode.HARDWARE = 'hardware';
  4979. const clipping = () => nodeObject( new ClippingNode() );
  4980. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  4981. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  4982. /**
  4983. * See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  4984. */
  4985. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  4986. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  4987. return fract( mul( 1.0e4, sin( mul( 17.0, value.x ).add( mul( 0.1, value.y ) ) ) ).mul( add( 0.1, abs( sin( mul( 13.0, value.y ).add( value.x ) ) ) ) ) );
  4988. } );
  4989. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  4990. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  4991. } );
  4992. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  4993. // Find the discretized derivatives of our coordinates
  4994. const maxDeriv = max$1(
  4995. length( dFdx( position.xyz ) ),
  4996. length( dFdy( position.xyz ) )
  4997. ).toVar( 'maxDeriv' );
  4998. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  4999. // Find two nearest log-discretized noise scales
  5000. const pixScales = vec2(
  5001. exp2( floor( log2( pixScale ) ) ),
  5002. exp2( ceil( log2( pixScale ) ) )
  5003. ).toVar( 'pixScales' );
  5004. // Compute alpha thresholds at our two noise scales
  5005. const alpha = vec2(
  5006. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  5007. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  5008. ).toVar( 'alpha' );
  5009. // Factor to interpolate lerp with
  5010. const lerpFactor = fract( log2( pixScale ) ).toVar( 'lerpFactor' );
  5011. // Interpolate alpha threshold from noise at two scales
  5012. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) ).toVar( 'x' );
  5013. // Pass into CDF to compute uniformly distrib threshold
  5014. const a = min$1( lerpFactor, lerpFactor.oneMinus() ).toVar( 'a' );
  5015. const cases = vec3(
  5016. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  5017. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  5018. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) ).toVar( 'cases' );
  5019. // Find our final, uniformly distributed alpha threshold (ατ)
  5020. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  5021. // Avoids ατ == 0. Could also do ατ =1-ατ
  5022. return clamp( threshold, 1.0e-6, 1.0 );
  5023. } );
  5024. class NodeMaterial extends Material {
  5025. static get type() {
  5026. return 'NodeMaterial';
  5027. }
  5028. get type() {
  5029. return this.constructor.type;
  5030. }
  5031. set type( _value ) { /* */ }
  5032. constructor() {
  5033. super();
  5034. this.isNodeMaterial = true;
  5035. this.forceSinglePass = false;
  5036. this.fog = true;
  5037. this.lights = false;
  5038. this.hardwareClipping = false;
  5039. this.lightsNode = null;
  5040. this.envNode = null;
  5041. this.aoNode = null;
  5042. this.colorNode = null;
  5043. this.normalNode = null;
  5044. this.opacityNode = null;
  5045. this.backdropNode = null;
  5046. this.backdropAlphaNode = null;
  5047. this.alphaTestNode = null;
  5048. this.positionNode = null;
  5049. this.geometryNode = null;
  5050. this.depthNode = null;
  5051. this.shadowPositionNode = null;
  5052. this.receivedShadowNode = null;
  5053. this.castShadowNode = null;
  5054. this.outputNode = null;
  5055. this.mrtNode = null;
  5056. this.fragmentNode = null;
  5057. this.vertexNode = null;
  5058. }
  5059. customProgramCacheKey() {
  5060. return this.type + getCacheKey$1( this );
  5061. }
  5062. build( builder ) {
  5063. this.setup( builder );
  5064. }
  5065. setupObserver( builder ) {
  5066. return new NodeMaterialObserver( builder );
  5067. }
  5068. setup( builder ) {
  5069. builder.context.setupNormal = () => this.setupNormal( builder );
  5070. const renderer = builder.renderer;
  5071. const renderTarget = renderer.getRenderTarget();
  5072. // < VERTEX STAGE >
  5073. builder.addStack();
  5074. builder.stack.outputNode = this.vertexNode || this.setupPosition( builder );
  5075. if ( this.geometryNode !== null ) {
  5076. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  5077. }
  5078. builder.addFlow( 'vertex', builder.removeStack() );
  5079. // < FRAGMENT STAGE >
  5080. builder.addStack();
  5081. let resultNode;
  5082. const clippingNode = this.setupClipping( builder );
  5083. if ( this.depthWrite === true ) {
  5084. // only write depth if depth buffer is configured
  5085. if ( renderTarget !== null ) {
  5086. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  5087. } else {
  5088. if ( renderer.depth === true ) this.setupDepth( builder );
  5089. }
  5090. }
  5091. if ( this.fragmentNode === null ) {
  5092. this.setupDiffuseColor( builder );
  5093. this.setupVariants( builder );
  5094. const outgoingLightNode = this.setupLighting( builder );
  5095. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  5096. // force unsigned floats - useful for RenderTargets
  5097. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  5098. resultNode = this.setupOutput( builder, basicOutput );
  5099. // OUTPUT NODE
  5100. output.assign( resultNode );
  5101. //
  5102. if ( this.outputNode !== null ) resultNode = this.outputNode;
  5103. // MRT
  5104. if ( renderTarget !== null ) {
  5105. const mrt = renderer.getMRT();
  5106. const materialMRT = this.mrtNode;
  5107. if ( mrt !== null ) {
  5108. resultNode = mrt;
  5109. if ( materialMRT !== null ) {
  5110. resultNode = mrt.merge( materialMRT );
  5111. }
  5112. } else if ( materialMRT !== null ) {
  5113. resultNode = materialMRT;
  5114. }
  5115. }
  5116. } else {
  5117. let fragmentNode = this.fragmentNode;
  5118. if ( fragmentNode.isOutputStructNode !== true ) {
  5119. fragmentNode = vec4( fragmentNode );
  5120. }
  5121. resultNode = this.setupOutput( builder, fragmentNode );
  5122. }
  5123. builder.stack.outputNode = resultNode;
  5124. builder.addFlow( 'fragment', builder.removeStack() );
  5125. // < MONITOR >
  5126. builder.monitor = this.setupObserver( builder );
  5127. }
  5128. setupClipping( builder ) {
  5129. if ( builder.clippingContext === null ) return null;
  5130. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  5131. let result = null;
  5132. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  5133. const samples = builder.renderer.samples;
  5134. if ( this.alphaToCoverage && samples > 1 ) {
  5135. // to be added to flow when the color/alpha value has been determined
  5136. result = clippingAlpha();
  5137. } else {
  5138. builder.stack.add( clipping() );
  5139. }
  5140. }
  5141. return result;
  5142. }
  5143. setupHardwareClipping( builder ) {
  5144. this.hardwareClipping = false;
  5145. if ( builder.clippingContext === null ) return;
  5146. const candidateCount = builder.clippingContext.unionPlanes.length;
  5147. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  5148. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  5149. builder.stack.add( hardwareClipping() );
  5150. this.hardwareClipping = true;
  5151. }
  5152. return;
  5153. }
  5154. setupDepth( builder ) {
  5155. const { renderer, camera } = builder;
  5156. // Depth
  5157. let depthNode = this.depthNode;
  5158. if ( depthNode === null ) {
  5159. const mrt = renderer.getMRT();
  5160. if ( mrt && mrt.has( 'depth' ) ) {
  5161. depthNode = mrt.get( 'depth' );
  5162. } else if ( renderer.logarithmicDepthBuffer === true ) {
  5163. if ( camera.isPerspectiveCamera ) {
  5164. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  5165. } else {
  5166. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  5167. }
  5168. }
  5169. }
  5170. if ( depthNode !== null ) {
  5171. depth.assign( depthNode ).append();
  5172. }
  5173. }
  5174. setupPosition( builder ) {
  5175. const { object } = builder;
  5176. const geometry = object.geometry;
  5177. builder.addStack();
  5178. // Vertex
  5179. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  5180. morphReference( object ).append();
  5181. }
  5182. if ( object.isSkinnedMesh === true ) {
  5183. skinningReference( object ).append();
  5184. }
  5185. if ( this.displacementMap ) {
  5186. const displacementMap = materialReference( 'displacementMap', 'texture' );
  5187. const displacementScale = materialReference( 'displacementScale', 'float' );
  5188. const displacementBias = materialReference( 'displacementBias', 'float' );
  5189. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  5190. }
  5191. if ( object.isBatchedMesh ) {
  5192. batch( object ).append();
  5193. }
  5194. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  5195. instancedMesh( object ).append();
  5196. }
  5197. if ( this.positionNode !== null ) {
  5198. positionLocal.assign( this.positionNode );
  5199. }
  5200. this.setupHardwareClipping( builder );
  5201. const mvp = modelViewProjection();
  5202. builder.context.vertex = builder.removeStack();
  5203. builder.context.mvp = mvp;
  5204. return mvp;
  5205. }
  5206. setupDiffuseColor( { object, geometry } ) {
  5207. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  5208. // VERTEX COLORS
  5209. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  5210. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  5211. }
  5212. // Instanced colors
  5213. if ( object.instanceColor ) {
  5214. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  5215. colorNode = instanceColor.mul( colorNode );
  5216. }
  5217. if ( object.isBatchedMesh && object._colorsTexture ) {
  5218. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  5219. colorNode = batchColor.mul( colorNode );
  5220. }
  5221. // COLOR
  5222. diffuseColor.assign( colorNode );
  5223. // OPACITY
  5224. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  5225. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  5226. // ALPHA TEST
  5227. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  5228. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  5229. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  5230. }
  5231. // ALPHA HASH
  5232. if ( this.alphaHash === true ) {
  5233. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  5234. }
  5235. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  5236. diffuseColor.a.assign( 1.0 );
  5237. }
  5238. }
  5239. setupVariants( /*builder*/ ) {
  5240. // Interface function.
  5241. }
  5242. setupOutgoingLight() {
  5243. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  5244. }
  5245. setupNormal() {
  5246. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  5247. }
  5248. setupEnvironment( /*builder*/ ) {
  5249. let node = null;
  5250. if ( this.envNode ) {
  5251. node = this.envNode;
  5252. } else if ( this.envMap ) {
  5253. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  5254. }
  5255. return node;
  5256. }
  5257. setupLightMap( builder ) {
  5258. let node = null;
  5259. if ( builder.material.lightMap ) {
  5260. node = new IrradianceNode( materialLightMap );
  5261. }
  5262. return node;
  5263. }
  5264. setupLights( builder ) {
  5265. const materialLightsNode = [];
  5266. //
  5267. const envNode = this.setupEnvironment( builder );
  5268. if ( envNode && envNode.isLightingNode ) {
  5269. materialLightsNode.push( envNode );
  5270. }
  5271. const lightMapNode = this.setupLightMap( builder );
  5272. if ( lightMapNode && lightMapNode.isLightingNode ) {
  5273. materialLightsNode.push( lightMapNode );
  5274. }
  5275. if ( this.aoNode !== null || builder.material.aoMap ) {
  5276. const aoNode = this.aoNode !== null ? this.aoNode : materialAOMap;
  5277. materialLightsNode.push( new AONode( aoNode ) );
  5278. }
  5279. let lightsN = this.lightsNode || builder.lightsNode;
  5280. if ( materialLightsNode.length > 0 ) {
  5281. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  5282. }
  5283. return lightsN;
  5284. }
  5285. setupLightingModel( /*builder*/ ) {
  5286. // Interface function.
  5287. }
  5288. setupLighting( builder ) {
  5289. const { material } = builder;
  5290. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  5291. // OUTGOING LIGHT
  5292. const lights = this.lights === true || this.lightsNode !== null;
  5293. const lightsNode = lights ? this.setupLights( builder ) : null;
  5294. let outgoingLightNode = this.setupOutgoingLight( builder );
  5295. if ( lightsNode && lightsNode.getScope().hasLights ) {
  5296. const lightingModel = this.setupLightingModel( builder );
  5297. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  5298. } else if ( backdropNode !== null ) {
  5299. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  5300. }
  5301. // EMISSIVE
  5302. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  5303. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  5304. outgoingLightNode = outgoingLightNode.add( emissive );
  5305. }
  5306. return outgoingLightNode;
  5307. }
  5308. setupOutput( builder, outputNode ) {
  5309. // FOG
  5310. if ( this.fog === true ) {
  5311. const fogNode = builder.fogNode;
  5312. if ( fogNode ) outputNode = vec4( fogNode.mix( outputNode.rgb, fogNode.colorNode ), outputNode.a );
  5313. }
  5314. return outputNode;
  5315. }
  5316. setDefaultValues( material ) {
  5317. // This approach is to reuse the native refreshUniforms*
  5318. // and turn available the use of features like transmission and environment in core
  5319. for ( const property in material ) {
  5320. const value = material[ property ];
  5321. if ( this[ property ] === undefined ) {
  5322. this[ property ] = value;
  5323. if ( value && value.clone ) this[ property ] = value.clone();
  5324. }
  5325. }
  5326. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  5327. for ( const key in descriptors ) {
  5328. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  5329. descriptors[ key ].get !== undefined ) {
  5330. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  5331. }
  5332. }
  5333. }
  5334. toJSON( meta ) {
  5335. const isRoot = ( meta === undefined || typeof meta === 'string' );
  5336. if ( isRoot ) {
  5337. meta = {
  5338. textures: {},
  5339. images: {},
  5340. nodes: {}
  5341. };
  5342. }
  5343. const data = Material.prototype.toJSON.call( this, meta );
  5344. const nodeChildren = getNodeChildren( this );
  5345. data.inputNodes = {};
  5346. for ( const { property, childNode } of nodeChildren ) {
  5347. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  5348. }
  5349. // TODO: Copied from Object3D.toJSON
  5350. function extractFromCache( cache ) {
  5351. const values = [];
  5352. for ( const key in cache ) {
  5353. const data = cache[ key ];
  5354. delete data.metadata;
  5355. values.push( data );
  5356. }
  5357. return values;
  5358. }
  5359. if ( isRoot ) {
  5360. const textures = extractFromCache( meta.textures );
  5361. const images = extractFromCache( meta.images );
  5362. const nodes = extractFromCache( meta.nodes );
  5363. if ( textures.length > 0 ) data.textures = textures;
  5364. if ( images.length > 0 ) data.images = images;
  5365. if ( nodes.length > 0 ) data.nodes = nodes;
  5366. }
  5367. return data;
  5368. }
  5369. copy( source ) {
  5370. this.lightsNode = source.lightsNode;
  5371. this.envNode = source.envNode;
  5372. this.colorNode = source.colorNode;
  5373. this.normalNode = source.normalNode;
  5374. this.opacityNode = source.opacityNode;
  5375. this.backdropNode = source.backdropNode;
  5376. this.backdropAlphaNode = source.backdropAlphaNode;
  5377. this.alphaTestNode = source.alphaTestNode;
  5378. this.positionNode = source.positionNode;
  5379. this.geometryNode = source.geometryNode;
  5380. this.depthNode = source.depthNode;
  5381. this.shadowPositionNode = source.shadowPositionNode;
  5382. this.receivedShadowNode = source.receivedShadowNode;
  5383. this.castShadowNode = source.castShadowNode;
  5384. this.outputNode = source.outputNode;
  5385. this.mrtNode = source.mrtNode;
  5386. this.fragmentNode = source.fragmentNode;
  5387. this.vertexNode = source.vertexNode;
  5388. return super.copy( source );
  5389. }
  5390. }
  5391. const _defaultValues$e = /*@__PURE__*/ new PointsMaterial();
  5392. class InstancedPointsNodeMaterial extends NodeMaterial {
  5393. static get type() {
  5394. return 'InstancedPointsNodeMaterial';
  5395. }
  5396. constructor( params = {} ) {
  5397. super();
  5398. this.lights = false;
  5399. this.useAlphaToCoverage = true;
  5400. this.useColor = params.vertexColors;
  5401. this.pointWidth = 1;
  5402. this.pointColorNode = null;
  5403. this.pointWidthNode = null;
  5404. this.setDefaultValues( _defaultValues$e );
  5405. this.setValues( params );
  5406. }
  5407. setup( builder ) {
  5408. this.setupShaders( builder );
  5409. super.setup( builder );
  5410. }
  5411. setupShaders( { renderer } ) {
  5412. const useAlphaToCoverage = this.alphaToCoverage;
  5413. const useColor = this.useColor;
  5414. this.vertexNode = Fn( () => {
  5415. const instancePosition = attribute( 'instancePosition' ).xyz;
  5416. // camera space
  5417. const mvPos = vec4( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  5418. const aspect = viewport.z.div( viewport.w );
  5419. // clip space
  5420. const clipPos = cameraProjectionMatrix.mul( mvPos );
  5421. // offset in ndc space
  5422. const offset = positionGeometry.xy.toVar();
  5423. offset.mulAssign( this.pointWidthNode ? this.pointWidthNode : materialPointWidth );
  5424. offset.assign( offset.div( viewport.z ) );
  5425. offset.y.assign( offset.y.mul( aspect ) );
  5426. // back to clip space
  5427. offset.assign( offset.mul( clipPos.w ) );
  5428. //clipPos.xy += offset;
  5429. clipPos.addAssign( vec4( offset, 0, 0 ) );
  5430. return clipPos;
  5431. } )();
  5432. this.fragmentNode = Fn( () => {
  5433. const alpha = float( 1 ).toVar();
  5434. const len2 = lengthSq( uv().mul( 2 ).sub( 1 ) );
  5435. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  5436. const dlen = float( len2.fwidth() ).toVar();
  5437. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  5438. } else {
  5439. len2.greaterThan( 1.0 ).discard();
  5440. }
  5441. let pointColorNode;
  5442. if ( this.pointColorNode ) {
  5443. pointColorNode = this.pointColorNode;
  5444. } else {
  5445. if ( useColor ) {
  5446. const instanceColor = attribute( 'instanceColor' );
  5447. pointColorNode = instanceColor.mul( materialColor );
  5448. } else {
  5449. pointColorNode = materialColor;
  5450. }
  5451. }
  5452. alpha.mulAssign( materialOpacity );
  5453. return vec4( pointColorNode, alpha );
  5454. } )();
  5455. }
  5456. get alphaToCoverage() {
  5457. return this.useAlphaToCoverage;
  5458. }
  5459. set alphaToCoverage( value ) {
  5460. if ( this.useAlphaToCoverage !== value ) {
  5461. this.useAlphaToCoverage = value;
  5462. this.needsUpdate = true;
  5463. }
  5464. }
  5465. }
  5466. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  5467. class LineBasicNodeMaterial extends NodeMaterial {
  5468. static get type() {
  5469. return 'LineBasicNodeMaterial';
  5470. }
  5471. constructor( parameters ) {
  5472. super();
  5473. this.isLineBasicNodeMaterial = true;
  5474. this.lights = false;
  5475. this.setDefaultValues( _defaultValues$d );
  5476. this.setValues( parameters );
  5477. }
  5478. }
  5479. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  5480. class LineDashedNodeMaterial extends NodeMaterial {
  5481. static get type() {
  5482. return 'LineDashedNodeMaterial';
  5483. }
  5484. constructor( parameters ) {
  5485. super();
  5486. this.isLineDashedNodeMaterial = true;
  5487. this.lights = false;
  5488. this.setDefaultValues( _defaultValues$c );
  5489. this.dashOffset = 0;
  5490. this.offsetNode = null;
  5491. this.dashScaleNode = null;
  5492. this.dashSizeNode = null;
  5493. this.gapSizeNode = null;
  5494. this.setValues( parameters );
  5495. }
  5496. setupVariants() {
  5497. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  5498. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  5499. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  5500. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  5501. dashSize.assign( dashSizeNode );
  5502. gapSize.assign( gapSizeNode );
  5503. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  5504. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  5505. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  5506. }
  5507. }
  5508. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  5509. class Line2NodeMaterial extends NodeMaterial {
  5510. static get type() {
  5511. return 'Line2NodeMaterial';
  5512. }
  5513. constructor( params = {} ) {
  5514. super();
  5515. this.lights = false;
  5516. this.setDefaultValues( _defaultValues$b );
  5517. this.useAlphaToCoverage = true;
  5518. this.useColor = params.vertexColors;
  5519. this.useDash = params.dashed;
  5520. this.useWorldUnits = false;
  5521. this.dashOffset = 0;
  5522. this.lineWidth = 1;
  5523. this.lineColorNode = null;
  5524. this.offsetNode = null;
  5525. this.dashScaleNode = null;
  5526. this.dashSizeNode = null;
  5527. this.gapSizeNode = null;
  5528. this.setValues( params );
  5529. }
  5530. setup( builder ) {
  5531. this.setupShaders( builder );
  5532. super.setup( builder );
  5533. }
  5534. setupShaders( { renderer } ) {
  5535. const useAlphaToCoverage = this.alphaToCoverage;
  5536. const useColor = this.useColor;
  5537. const useDash = this.dashed;
  5538. const useWorldUnits = this.worldUnits;
  5539. const trimSegment = Fn( ( { start, end } ) => {
  5540. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  5541. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  5542. const nearEstimate = b.mul( - 0.5 ).div( a );
  5543. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  5544. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  5545. } ).setLayout( {
  5546. name: 'trimSegment',
  5547. type: 'vec4',
  5548. inputs: [
  5549. { name: 'start', type: 'vec4' },
  5550. { name: 'end', type: 'vec4' }
  5551. ]
  5552. } );
  5553. this.vertexNode = Fn( () => {
  5554. const instanceStart = attribute( 'instanceStart' );
  5555. const instanceEnd = attribute( 'instanceEnd' );
  5556. // camera space
  5557. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  5558. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  5559. if ( useDash ) {
  5560. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  5561. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  5562. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  5563. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  5564. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  5565. lineDistance = lineDistance.add( offsetNode );
  5566. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  5567. }
  5568. if ( useWorldUnits ) {
  5569. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  5570. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  5571. }
  5572. const aspect = viewport.z.div( viewport.w );
  5573. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  5574. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  5575. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  5576. // perhaps there is a more elegant solution -- WestLangley
  5577. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  5578. If( perspective, () => {
  5579. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  5580. end.assign( trimSegment( { start: start, end: end } ) );
  5581. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  5582. start.assign( trimSegment( { start: end, end: start } ) );
  5583. } );
  5584. } );
  5585. // clip space
  5586. const clipStart = cameraProjectionMatrix.mul( start );
  5587. const clipEnd = cameraProjectionMatrix.mul( end );
  5588. // ndc space
  5589. const ndcStart = clipStart.xyz.div( clipStart.w );
  5590. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  5591. // direction
  5592. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  5593. // account for clip-space aspect ratio
  5594. dir.x.assign( dir.x.mul( aspect ) );
  5595. dir.assign( dir.normalize() );
  5596. const clip = vec4().toVar();
  5597. if ( useWorldUnits ) {
  5598. // get the offset direction as perpendicular to the view vector
  5599. const worldDir = end.xyz.sub( start.xyz ).normalize();
  5600. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  5601. const worldUp = worldDir.cross( tmpFwd ).normalize();
  5602. const worldFwd = worldDir.cross( worldUp );
  5603. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  5604. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  5605. // height offset
  5606. const hw = materialLineWidth.mul( 0.5 );
  5607. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  5608. // don't extend the line if we're rendering dashes because we
  5609. // won't be rendering the endcaps
  5610. if ( ! useDash ) {
  5611. // cap extension
  5612. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  5613. // add width to the box
  5614. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  5615. // endcaps
  5616. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  5617. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  5618. } );
  5619. }
  5620. // project the worldpos
  5621. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  5622. // shift the depth of the projected points so the line
  5623. // segments overlap neatly
  5624. const clipPose = vec3().toVar();
  5625. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  5626. clip.z.assign( clipPose.z.mul( clip.w ) );
  5627. } else {
  5628. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  5629. // undo aspect ratio adjustment
  5630. dir.x.assign( dir.x.div( aspect ) );
  5631. offset.x.assign( offset.x.div( aspect ) );
  5632. // sign flip
  5633. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  5634. // endcaps
  5635. If( positionGeometry.y.lessThan( 0.0 ), () => {
  5636. offset.assign( offset.sub( dir ) );
  5637. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  5638. offset.assign( offset.add( dir ) );
  5639. } );
  5640. // adjust for linewidth
  5641. offset.assign( offset.mul( materialLineWidth ) );
  5642. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  5643. offset.assign( offset.div( viewport.w ) );
  5644. // select end
  5645. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  5646. // back to clip space
  5647. offset.assign( offset.mul( clip.w ) );
  5648. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  5649. }
  5650. return clip;
  5651. } )();
  5652. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  5653. const p13 = p1.sub( p3 );
  5654. const p43 = p4.sub( p3 );
  5655. const p21 = p2.sub( p1 );
  5656. const d1343 = p13.dot( p43 );
  5657. const d4321 = p43.dot( p21 );
  5658. const d1321 = p13.dot( p21 );
  5659. const d4343 = p43.dot( p43 );
  5660. const d2121 = p21.dot( p21 );
  5661. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  5662. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  5663. const mua = numer.div( denom ).clamp();
  5664. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  5665. return vec2( mua, mub );
  5666. } );
  5667. this.fragmentNode = Fn( () => {
  5668. const vUv = uv();
  5669. if ( useDash ) {
  5670. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  5671. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  5672. dashSize.assign( dashSizeNode );
  5673. gapSize.assign( gapSizeNode );
  5674. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  5675. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  5676. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  5677. }
  5678. const alpha = float( 1 ).toVar( 'alpha' );
  5679. if ( useWorldUnits ) {
  5680. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  5681. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  5682. // Find the closest points on the view ray and the line segment
  5683. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  5684. const lineDir = worldEnd.sub( worldStart );
  5685. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  5686. const p1 = worldStart.add( lineDir.mul( params.x ) );
  5687. const p2 = rayEnd.mul( params.y );
  5688. const delta = p1.sub( p2 );
  5689. const len = delta.length();
  5690. const norm = len.div( materialLineWidth );
  5691. if ( ! useDash ) {
  5692. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  5693. const dnorm = norm.fwidth();
  5694. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  5695. } else {
  5696. norm.greaterThan( 0.5 ).discard();
  5697. }
  5698. }
  5699. } else {
  5700. // round endcaps
  5701. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  5702. const a = vUv.x;
  5703. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  5704. const len2 = a.mul( a ).add( b.mul( b ) );
  5705. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  5706. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  5707. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  5708. } );
  5709. } else {
  5710. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  5711. const a = vUv.x;
  5712. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  5713. const len2 = a.mul( a ).add( b.mul( b ) );
  5714. len2.greaterThan( 1.0 ).discard();
  5715. } );
  5716. }
  5717. }
  5718. let lineColorNode;
  5719. if ( this.lineColorNode ) {
  5720. lineColorNode = this.lineColorNode;
  5721. } else {
  5722. if ( useColor ) {
  5723. const instanceColorStart = attribute( 'instanceColorStart' );
  5724. const instanceColorEnd = attribute( 'instanceColorEnd' );
  5725. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  5726. lineColorNode = instanceColor.mul( materialColor );
  5727. } else {
  5728. lineColorNode = materialColor;
  5729. }
  5730. }
  5731. return vec4( lineColorNode, alpha );
  5732. } )();
  5733. }
  5734. get worldUnits() {
  5735. return this.useWorldUnits;
  5736. }
  5737. set worldUnits( value ) {
  5738. if ( this.useWorldUnits !== value ) {
  5739. this.useWorldUnits = value;
  5740. this.needsUpdate = true;
  5741. }
  5742. }
  5743. get dashed() {
  5744. return this.useDash;
  5745. }
  5746. set dashed( value ) {
  5747. if ( this.useDash !== value ) {
  5748. this.useDash = value;
  5749. this.needsUpdate = true;
  5750. }
  5751. }
  5752. get alphaToCoverage() {
  5753. return this.useAlphaToCoverage;
  5754. }
  5755. set alphaToCoverage( value ) {
  5756. if ( this.useAlphaToCoverage !== value ) {
  5757. this.useAlphaToCoverage = value;
  5758. this.needsUpdate = true;
  5759. }
  5760. }
  5761. }
  5762. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  5763. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  5764. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  5765. class MeshNormalNodeMaterial extends NodeMaterial {
  5766. static get type() {
  5767. return 'MeshNormalNodeMaterial';
  5768. }
  5769. constructor( parameters ) {
  5770. super();
  5771. this.lights = false;
  5772. this.isMeshNormalNodeMaterial = true;
  5773. this.setDefaultValues( _defaultValues$a );
  5774. this.setValues( parameters );
  5775. }
  5776. setupDiffuseColor() {
  5777. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  5778. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  5779. }
  5780. }
  5781. class EquirectUVNode extends TempNode {
  5782. static get type() {
  5783. return 'EquirectUVNode';
  5784. }
  5785. constructor( dirNode = positionWorldDirection ) {
  5786. super( 'vec2' );
  5787. this.dirNode = dirNode;
  5788. }
  5789. setup() {
  5790. const dir = this.dirNode;
  5791. const u = dir.z.atan2( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  5792. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  5793. return vec2( u, v );
  5794. }
  5795. }
  5796. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  5797. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  5798. class CubeRenderTarget extends WebGLCubeRenderTarget {
  5799. constructor( size = 1, options = {} ) {
  5800. super( size, options );
  5801. this.isCubeRenderTarget = true;
  5802. }
  5803. fromEquirectangularTexture( renderer, texture$1 ) {
  5804. const currentMinFilter = texture$1.minFilter;
  5805. const currentGenerateMipmaps = texture$1.generateMipmaps;
  5806. texture$1.generateMipmaps = true;
  5807. this.texture.type = texture$1.type;
  5808. this.texture.colorSpace = texture$1.colorSpace;
  5809. this.texture.generateMipmaps = texture$1.generateMipmaps;
  5810. this.texture.minFilter = texture$1.minFilter;
  5811. this.texture.magFilter = texture$1.magFilter;
  5812. const geometry = new BoxGeometry( 5, 5, 5 );
  5813. const uvNode = equirectUV( positionWorldDirection );
  5814. const material = new NodeMaterial();
  5815. material.colorNode = texture( texture$1, uvNode, 0 );
  5816. material.side = BackSide;
  5817. material.blending = NoBlending;
  5818. const mesh = new Mesh( geometry, material );
  5819. const scene = new Scene();
  5820. scene.add( mesh );
  5821. // Avoid blurred poles
  5822. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  5823. const camera = new CubeCamera( 1, 10, this );
  5824. const currentMRT = renderer.getMRT();
  5825. renderer.setMRT( null );
  5826. camera.update( renderer, scene );
  5827. renderer.setMRT( currentMRT );
  5828. texture$1.minFilter = currentMinFilter;
  5829. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  5830. mesh.geometry.dispose();
  5831. mesh.material.dispose();
  5832. return this;
  5833. }
  5834. }
  5835. const _cache$1 = new WeakMap();
  5836. class CubeMapNode extends TempNode {
  5837. static get type() {
  5838. return 'CubeMapNode';
  5839. }
  5840. constructor( envNode ) {
  5841. super( 'vec3' );
  5842. this.envNode = envNode;
  5843. this._cubeTexture = null;
  5844. this._cubeTextureNode = cubeTexture();
  5845. const defaultTexture = new CubeTexture();
  5846. defaultTexture.isRenderTargetTexture = true;
  5847. this._defaultTexture = defaultTexture;
  5848. this.updateBeforeType = NodeUpdateType.RENDER;
  5849. }
  5850. updateBefore( frame ) {
  5851. const { renderer, material } = frame;
  5852. const envNode = this.envNode;
  5853. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  5854. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  5855. if ( texture && texture.isTexture ) {
  5856. const mapping = texture.mapping;
  5857. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  5858. // check for converted cubemap map
  5859. if ( _cache$1.has( texture ) ) {
  5860. const cubeMap = _cache$1.get( texture );
  5861. mapTextureMapping( cubeMap, texture.mapping );
  5862. this._cubeTexture = cubeMap;
  5863. } else {
  5864. // create cube map from equirectangular map
  5865. const image = texture.image;
  5866. if ( isEquirectangularMapReady$1( image ) ) {
  5867. const renderTarget = new CubeRenderTarget( image.height );
  5868. renderTarget.fromEquirectangularTexture( renderer, texture );
  5869. mapTextureMapping( renderTarget.texture, texture.mapping );
  5870. this._cubeTexture = renderTarget.texture;
  5871. _cache$1.set( texture, renderTarget.texture );
  5872. texture.addEventListener( 'dispose', onTextureDispose );
  5873. } else {
  5874. // default cube texture as fallback when equirectangular texture is not yet loaded
  5875. this._cubeTexture = this._defaultTexture;
  5876. }
  5877. }
  5878. //
  5879. this._cubeTextureNode.value = this._cubeTexture;
  5880. } else {
  5881. // envNode already refers to a cube map
  5882. this._cubeTextureNode = this.envNode;
  5883. }
  5884. }
  5885. }
  5886. }
  5887. setup( builder ) {
  5888. this.updateBefore( builder );
  5889. return this._cubeTextureNode;
  5890. }
  5891. }
  5892. function isEquirectangularMapReady$1( image ) {
  5893. if ( image === null || image === undefined ) return false;
  5894. return image.height > 0;
  5895. }
  5896. function onTextureDispose( event ) {
  5897. const texture = event.target;
  5898. texture.removeEventListener( 'dispose', onTextureDispose );
  5899. const renderTarget = _cache$1.get( texture );
  5900. if ( renderTarget !== undefined ) {
  5901. _cache$1.delete( texture );
  5902. renderTarget.dispose();
  5903. }
  5904. }
  5905. function mapTextureMapping( texture, mapping ) {
  5906. if ( mapping === EquirectangularReflectionMapping ) {
  5907. texture.mapping = CubeReflectionMapping;
  5908. } else if ( mapping === EquirectangularRefractionMapping ) {
  5909. texture.mapping = CubeRefractionMapping;
  5910. }
  5911. }
  5912. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  5913. class BasicEnvironmentNode extends LightingNode {
  5914. static get type() {
  5915. return 'BasicEnvironmentNode';
  5916. }
  5917. constructor( envNode = null ) {
  5918. super();
  5919. this.envNode = envNode;
  5920. }
  5921. setup( builder ) {
  5922. // environment property is used in the finish() method of BasicLightingModel
  5923. builder.context.environment = cubeMapNode( this.envNode );
  5924. }
  5925. }
  5926. class BasicLightMapNode extends LightingNode {
  5927. static get type() {
  5928. return 'BasicLightMapNode';
  5929. }
  5930. constructor( lightMapNode = null ) {
  5931. super();
  5932. this.lightMapNode = lightMapNode;
  5933. }
  5934. setup( builder ) {
  5935. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  5936. const RECIPROCAL_PI = float( 1 / Math.PI );
  5937. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  5938. }
  5939. }
  5940. class LightingModel {
  5941. start( /*input, stack, builder*/ ) { }
  5942. finish( /*input, stack, builder*/ ) { }
  5943. direct( /*input, stack, builder*/ ) { }
  5944. directRectArea( /*input, stack, builder*/ ) {}
  5945. indirect( /*input, stack, builder*/ ) { }
  5946. ambientOcclusion( /*input, stack, builder*/ ) { }
  5947. }
  5948. class BasicLightingModel extends LightingModel {
  5949. constructor() {
  5950. super();
  5951. }
  5952. indirect( context, stack, builder ) {
  5953. const ambientOcclusion = context.ambientOcclusion;
  5954. const reflectedLight = context.reflectedLight;
  5955. const irradianceLightMap = builder.context.irradianceLightMap;
  5956. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  5957. // accumulation (baked indirect lighting only)
  5958. if ( irradianceLightMap ) {
  5959. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  5960. } else {
  5961. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  5962. }
  5963. // modulation
  5964. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  5965. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  5966. }
  5967. finish( context, stack, builder ) {
  5968. const material = builder.material;
  5969. const outgoingLight = context.outgoingLight;
  5970. const envNode = builder.context.environment;
  5971. if ( envNode ) {
  5972. switch ( material.combine ) {
  5973. case MultiplyOperation:
  5974. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  5975. break;
  5976. case MixOperation:
  5977. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  5978. break;
  5979. case AddOperation:
  5980. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  5981. break;
  5982. default:
  5983. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  5984. break;
  5985. }
  5986. }
  5987. }
  5988. }
  5989. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  5990. class MeshBasicNodeMaterial extends NodeMaterial {
  5991. static get type() {
  5992. return 'MeshBasicNodeMaterial';
  5993. }
  5994. constructor( parameters ) {
  5995. super();
  5996. this.isMeshBasicNodeMaterial = true;
  5997. this.lights = true;
  5998. this.setDefaultValues( _defaultValues$9 );
  5999. this.setValues( parameters );
  6000. }
  6001. setupNormal() {
  6002. return normalView; // see #28839
  6003. }
  6004. setupEnvironment( builder ) {
  6005. const envNode = super.setupEnvironment( builder );
  6006. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  6007. }
  6008. setupLightMap( builder ) {
  6009. let node = null;
  6010. if ( builder.material.lightMap ) {
  6011. node = new BasicLightMapNode( materialLightMap );
  6012. }
  6013. return node;
  6014. }
  6015. setupOutgoingLight() {
  6016. return diffuseColor.rgb;
  6017. }
  6018. setupLightingModel() {
  6019. return new BasicLightingModel();
  6020. }
  6021. }
  6022. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  6023. // Original approximation by Christophe Schlick '94
  6024. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  6025. // Optimized variant (presented by Epic at SIGGRAPH '13)
  6026. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  6027. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  6028. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  6029. } ); // validated
  6030. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  6031. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  6032. } ); // validated
  6033. const G_BlinnPhong_Implicit = () => float( 0.25 );
  6034. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  6035. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  6036. } );
  6037. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  6038. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  6039. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  6040. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  6041. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  6042. const G = G_BlinnPhong_Implicit();
  6043. const D = D_BlinnPhong( { dotNH } );
  6044. return F.mul( G ).mul( D );
  6045. } );
  6046. class PhongLightingModel extends BasicLightingModel {
  6047. constructor( specular = true ) {
  6048. super();
  6049. this.specular = specular;
  6050. }
  6051. direct( { lightDirection, lightColor, reflectedLight } ) {
  6052. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  6053. const irradiance = dotNL.mul( lightColor );
  6054. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  6055. if ( this.specular === true ) {
  6056. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  6057. }
  6058. }
  6059. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  6060. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  6061. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  6062. }
  6063. }
  6064. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  6065. class MeshLambertNodeMaterial extends NodeMaterial {
  6066. static get type() {
  6067. return 'MeshLambertNodeMaterial';
  6068. }
  6069. constructor( parameters ) {
  6070. super();
  6071. this.isMeshLambertNodeMaterial = true;
  6072. this.lights = true;
  6073. this.setDefaultValues( _defaultValues$8 );
  6074. this.setValues( parameters );
  6075. }
  6076. setupEnvironment( builder ) {
  6077. const envNode = super.setupEnvironment( builder );
  6078. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  6079. }
  6080. setupLightingModel( /*builder*/ ) {
  6081. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  6082. }
  6083. }
  6084. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  6085. class MeshPhongNodeMaterial extends NodeMaterial {
  6086. static get type() {
  6087. return 'MeshPhongNodeMaterial';
  6088. }
  6089. constructor( parameters ) {
  6090. super();
  6091. this.isMeshPhongNodeMaterial = true;
  6092. this.lights = true;
  6093. this.shininessNode = null;
  6094. this.specularNode = null;
  6095. this.setDefaultValues( _defaultValues$7 );
  6096. this.setValues( parameters );
  6097. }
  6098. setupEnvironment( builder ) {
  6099. const envNode = super.setupEnvironment( builder );
  6100. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  6101. }
  6102. setupLightingModel( /*builder*/ ) {
  6103. return new PhongLightingModel();
  6104. }
  6105. setupVariants() {
  6106. // SHININESS
  6107. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  6108. shininess.assign( shininessNode );
  6109. // SPECULAR COLOR
  6110. const specularNode = this.specularNode || materialSpecular;
  6111. specularColor.assign( specularNode );
  6112. }
  6113. copy( source ) {
  6114. this.shininessNode = source.shininessNode;
  6115. this.specularNode = source.specularNode;
  6116. return super.copy( source );
  6117. }
  6118. }
  6119. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  6120. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  6121. return float( 0 );
  6122. }
  6123. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  6124. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  6125. return geometryRoughness;
  6126. } );
  6127. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  6128. const { roughness } = inputs;
  6129. const geometryRoughness = getGeometryRoughness();
  6130. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  6131. roughnessFactor = roughnessFactor.add( geometryRoughness );
  6132. roughnessFactor = roughnessFactor.min( 1.0 );
  6133. return roughnessFactor;
  6134. } );
  6135. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  6136. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  6137. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  6138. const a2 = alpha.pow2();
  6139. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  6140. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  6141. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  6142. } ).setLayout( {
  6143. name: 'V_GGX_SmithCorrelated',
  6144. type: 'float',
  6145. inputs: [
  6146. { name: 'alpha', type: 'float' },
  6147. { name: 'dotNL', type: 'float' },
  6148. { name: 'dotNV', type: 'float' }
  6149. ]
  6150. } ); // validated
  6151. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  6152. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  6153. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  6154. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  6155. const v = div( 0.5, gv.add( gl ) );
  6156. return v.saturate();
  6157. } ).setLayout( {
  6158. name: 'V_GGX_SmithCorrelated_Anisotropic',
  6159. type: 'float',
  6160. inputs: [
  6161. { name: 'alphaT', type: 'float', qualifier: 'in' },
  6162. { name: 'alphaB', type: 'float', qualifier: 'in' },
  6163. { name: 'dotTV', type: 'float', qualifier: 'in' },
  6164. { name: 'dotBV', type: 'float', qualifier: 'in' },
  6165. { name: 'dotTL', type: 'float', qualifier: 'in' },
  6166. { name: 'dotBL', type: 'float', qualifier: 'in' },
  6167. { name: 'dotNV', type: 'float', qualifier: 'in' },
  6168. { name: 'dotNL', type: 'float', qualifier: 'in' }
  6169. ]
  6170. } );
  6171. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  6172. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  6173. // alpha is "roughness squared" in Disney’s reparameterization
  6174. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  6175. const a2 = alpha.pow2();
  6176. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  6177. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  6178. } ).setLayout( {
  6179. name: 'D_GGX',
  6180. type: 'float',
  6181. inputs: [
  6182. { name: 'alpha', type: 'float' },
  6183. { name: 'dotNH', type: 'float' }
  6184. ]
  6185. } ); // validated
  6186. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  6187. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  6188. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  6189. const a2 = alphaT.mul( alphaB );
  6190. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  6191. const v2 = v.dot( v );
  6192. const w2 = a2.div( v2 );
  6193. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  6194. } ).setLayout( {
  6195. name: 'D_GGX_Anisotropic',
  6196. type: 'float',
  6197. inputs: [
  6198. { name: 'alphaT', type: 'float', qualifier: 'in' },
  6199. { name: 'alphaB', type: 'float', qualifier: 'in' },
  6200. { name: 'dotNH', type: 'float', qualifier: 'in' },
  6201. { name: 'dotTH', type: 'float', qualifier: 'in' },
  6202. { name: 'dotBH', type: 'float', qualifier: 'in' }
  6203. ]
  6204. } );
  6205. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  6206. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  6207. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  6208. const normalView = inputs.normalView || transformedNormalView;
  6209. const alpha = roughness.pow2(); // UE4's roughness
  6210. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  6211. const dotNL = normalView.dot( lightDirection ).clamp();
  6212. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  6213. const dotNH = normalView.dot( halfDir ).clamp();
  6214. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  6215. let F = F_Schlick( { f0, f90, dotVH } );
  6216. let V, D;
  6217. if ( defined( USE_IRIDESCENCE ) ) {
  6218. F = iridescence.mix( F, f );
  6219. }
  6220. if ( defined( USE_ANISOTROPY ) ) {
  6221. const dotTL = anisotropyT.dot( lightDirection );
  6222. const dotTV = anisotropyT.dot( positionViewDirection );
  6223. const dotTH = anisotropyT.dot( halfDir );
  6224. const dotBL = anisotropyB.dot( lightDirection );
  6225. const dotBV = anisotropyB.dot( positionViewDirection );
  6226. const dotBH = anisotropyB.dot( halfDir );
  6227. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  6228. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  6229. } else {
  6230. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  6231. D = D_GGX( { alpha, dotNH } );
  6232. }
  6233. return F.mul( V ).mul( D );
  6234. } ); // validated
  6235. // Analytical approximation of the DFG LUT, one half of the
  6236. // split-sum approximation used in indirect specular lighting.
  6237. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  6238. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  6239. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  6240. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  6241. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  6242. const r = roughness.mul( c0 ).add( c1 );
  6243. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  6244. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  6245. return fab;
  6246. } ).setLayout( {
  6247. name: 'DFGApprox',
  6248. type: 'vec2',
  6249. inputs: [
  6250. { name: 'roughness', type: 'float' },
  6251. { name: 'dotNV', type: 'vec3' }
  6252. ]
  6253. } );
  6254. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  6255. const { dotNV, specularColor, specularF90, roughness } = inputs;
  6256. const fab = DFGApprox( { dotNV, roughness } );
  6257. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  6258. } );
  6259. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  6260. const x = dotVH.oneMinus().saturate();
  6261. const x2 = x.mul( x );
  6262. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  6263. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  6264. } ).setLayout( {
  6265. name: 'Schlick_to_F0',
  6266. type: 'vec3',
  6267. inputs: [
  6268. { name: 'f', type: 'vec3' },
  6269. { name: 'f90', type: 'float' },
  6270. { name: 'dotVH', type: 'float' }
  6271. ]
  6272. } );
  6273. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  6274. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  6275. const alpha = roughness.pow2();
  6276. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  6277. const invAlpha = float( 1.0 ).div( alpha );
  6278. const cos2h = dotNH.pow2();
  6279. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  6280. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  6281. } ).setLayout( {
  6282. name: 'D_Charlie',
  6283. type: 'float',
  6284. inputs: [
  6285. { name: 'roughness', type: 'float' },
  6286. { name: 'dotNH', type: 'float' }
  6287. ]
  6288. } );
  6289. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  6290. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  6291. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  6292. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  6293. } ).setLayout( {
  6294. name: 'V_Neubelt',
  6295. type: 'float',
  6296. inputs: [
  6297. { name: 'dotNV', type: 'float' },
  6298. { name: 'dotNL', type: 'float' }
  6299. ]
  6300. } );
  6301. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  6302. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  6303. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  6304. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  6305. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  6306. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  6307. const V = V_Neubelt( { dotNV, dotNL } );
  6308. return sheen.mul( D ).mul( V );
  6309. } );
  6310. // Rect Area Light
  6311. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  6312. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  6313. // code: https://github.com/selfshadow/ltc_code/
  6314. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  6315. const LUT_SIZE = 64.0;
  6316. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  6317. const LUT_BIAS = 0.5 / LUT_SIZE;
  6318. const dotNV = N.dot( V ).saturate();
  6319. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  6320. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  6321. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  6322. return uv;
  6323. } ).setLayout( {
  6324. name: 'LTC_Uv',
  6325. type: 'vec2',
  6326. inputs: [
  6327. { name: 'N', type: 'vec3' },
  6328. { name: 'V', type: 'vec3' },
  6329. { name: 'roughness', type: 'float' }
  6330. ]
  6331. } );
  6332. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  6333. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  6334. // An approximation of the form factor of a horizon-clipped rectangle.
  6335. const l = f.length();
  6336. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  6337. } ).setLayout( {
  6338. name: 'LTC_ClippedSphereFormFactor',
  6339. type: 'float',
  6340. inputs: [
  6341. { name: 'f', type: 'vec3' }
  6342. ]
  6343. } );
  6344. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  6345. const x = v1.dot( v2 );
  6346. const y = x.abs().toVar();
  6347. // rational polynomial approximation to theta / sin( theta ) / 2PI
  6348. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  6349. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  6350. const v = a.div( b );
  6351. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  6352. return v1.cross( v2 ).mul( theta_sintheta );
  6353. } ).setLayout( {
  6354. name: 'LTC_EdgeVectorFormFactor',
  6355. type: 'vec3',
  6356. inputs: [
  6357. { name: 'v1', type: 'vec3' },
  6358. { name: 'v2', type: 'vec3' }
  6359. ]
  6360. } );
  6361. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  6362. // bail if point is on back side of plane of light
  6363. // assumes ccw winding order of light vertices
  6364. const v1 = p1.sub( p0 ).toVar();
  6365. const v2 = p3.sub( p0 ).toVar();
  6366. const lightNormal = v1.cross( v2 );
  6367. const result = vec3().toVar();
  6368. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  6369. // construct orthonormal basis around N
  6370. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  6371. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  6372. // compute transform
  6373. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  6374. // transform rect
  6375. // & project rect onto sphere
  6376. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  6377. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  6378. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  6379. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  6380. // calculate vector form factor
  6381. const vectorFormFactor = vec3( 0 ).toVar();
  6382. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  6383. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  6384. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  6385. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  6386. // adjust for horizon clipping
  6387. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  6388. } );
  6389. return result;
  6390. } ).setLayout( {
  6391. name: 'LTC_Evaluate',
  6392. type: 'vec3',
  6393. inputs: [
  6394. { name: 'N', type: 'vec3' },
  6395. { name: 'V', type: 'vec3' },
  6396. { name: 'P', type: 'vec3' },
  6397. { name: 'mInv', type: 'mat3' },
  6398. { name: 'p0', type: 'vec3' },
  6399. { name: 'p1', type: 'vec3' },
  6400. { name: 'p2', type: 'vec3' },
  6401. { name: 'p3', type: 'vec3' }
  6402. ]
  6403. } );
  6404. // Mipped Bicubic Texture Filtering by N8
  6405. // https://www.shadertoy.com/view/Dl2SDW
  6406. const bC = 1.0 / 6.0;
  6407. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  6408. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  6409. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  6410. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  6411. const g0 = ( a ) => w0( a ).add( w1( a ) );
  6412. const g1 = ( a ) => w2( a ).add( w3( a ) );
  6413. // h0 and h1 are the two offset functions
  6414. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  6415. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  6416. const bicubic = ( textureNode, texelSize, lod ) => {
  6417. const uv = textureNode.uvNode;
  6418. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  6419. const iuv = floor( uvScaled );
  6420. const fuv = fract( uvScaled );
  6421. const g0x = g0( fuv.x );
  6422. const g1x = g1( fuv.x );
  6423. const h0x = h0( fuv.x );
  6424. const h1x = h1( fuv.x );
  6425. const h0y = h0( fuv.y );
  6426. const h1y = h1( fuv.y );
  6427. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  6428. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  6429. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  6430. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  6431. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.uv( p0 ).level( lod ) ), g1x.mul( textureNode.uv( p1 ).level( lod ) ) ) );
  6432. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.uv( p2 ).level( lod ) ), g1x.mul( textureNode.uv( p3 ).level( lod ) ) ) );
  6433. return a.add( b );
  6434. };
  6435. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  6436. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  6437. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  6438. const fLodSizeInv = div( 1.0, fLodSize );
  6439. const cLodSizeInv = div( 1.0, cLodSize );
  6440. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  6441. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  6442. return fract( lodNode ).mix( fSample, cSample );
  6443. } );
  6444. //
  6445. // Transmission
  6446. //
  6447. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  6448. // Direction of refracted light.
  6449. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  6450. // Compute rotation-independant scaling of the model matrix.
  6451. const modelScale = vec3(
  6452. length( modelMatrix[ 0 ].xyz ),
  6453. length( modelMatrix[ 1 ].xyz ),
  6454. length( modelMatrix[ 2 ].xyz )
  6455. );
  6456. // The thickness is specified in local space.
  6457. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  6458. } ).setLayout( {
  6459. name: 'getVolumeTransmissionRay',
  6460. type: 'vec3',
  6461. inputs: [
  6462. { name: 'n', type: 'vec3' },
  6463. { name: 'v', type: 'vec3' },
  6464. { name: 'thickness', type: 'float' },
  6465. { name: 'ior', type: 'float' },
  6466. { name: 'modelMatrix', type: 'mat4' }
  6467. ]
  6468. } );
  6469. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  6470. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  6471. // an IOR of 1.5 results in the default amount of microfacet refraction.
  6472. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  6473. } ).setLayout( {
  6474. name: 'applyIorToRoughness',
  6475. type: 'float',
  6476. inputs: [
  6477. { name: 'roughness', type: 'float' },
  6478. { name: 'ior', type: 'float' }
  6479. ]
  6480. } );
  6481. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  6482. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  6483. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  6484. const vTexture = material.side == BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  6485. const transmissionSample = vTexture.uv( fragCoord );
  6486. //const transmissionSample = viewportMipTexture( fragCoord );
  6487. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  6488. return textureBicubic( transmissionSample, lod );
  6489. } );
  6490. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  6491. If( attenuationDistance.notEqual( 0 ), () => {
  6492. // Compute light attenuation using Beer's law.
  6493. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  6494. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  6495. return transmittance;
  6496. } );
  6497. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  6498. return vec3( 1.0 );
  6499. } ).setLayout( {
  6500. name: 'volumeAttenuation',
  6501. type: 'vec3',
  6502. inputs: [
  6503. { name: 'transmissionDistance', type: 'float' },
  6504. { name: 'attenuationColor', type: 'vec3' },
  6505. { name: 'attenuationDistance', type: 'float' }
  6506. ]
  6507. } );
  6508. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  6509. let transmittedLight, transmittance;
  6510. if ( dispersion ) {
  6511. transmittedLight = vec4().toVar();
  6512. transmittance = vec3().toVar();
  6513. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  6514. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  6515. Loop( { start: 0, end: 3 }, ( { i } ) => {
  6516. const ior = iors.element( i );
  6517. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  6518. const refractedRayExit = position.add( transmissionRay );
  6519. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  6520. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  6521. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  6522. refractionCoords.addAssign( 1.0 );
  6523. refractionCoords.divAssign( 2.0 );
  6524. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  6525. // Sample framebuffer to get pixel the refracted ray hits.
  6526. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  6527. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  6528. transmittedLight.a.addAssign( transmissionSample.a );
  6529. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  6530. } );
  6531. transmittedLight.a.divAssign( 3.0 );
  6532. } else {
  6533. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  6534. const refractedRayExit = position.add( transmissionRay );
  6535. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  6536. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  6537. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  6538. refractionCoords.addAssign( 1.0 );
  6539. refractionCoords.divAssign( 2.0 );
  6540. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  6541. // Sample framebuffer to get pixel the refracted ray hits.
  6542. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  6543. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  6544. }
  6545. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  6546. const dotNV = n.dot( v ).clamp();
  6547. // Get the specular component.
  6548. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  6549. dotNV,
  6550. specularColor,
  6551. specularF90,
  6552. roughness
  6553. } ) );
  6554. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  6555. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  6556. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  6557. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  6558. } );
  6559. //
  6560. // Iridescence
  6561. //
  6562. // XYZ to linear-sRGB color space
  6563. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  6564. 3.2404542, - 0.9692660, 0.0556434,
  6565. - 1.5371385, 1.8760108, - 0.2040259,
  6566. - 0.4985314, 0.0415560, 1.0572252
  6567. );
  6568. // Assume air interface for top
  6569. // Note: We don't handle the case fresnel0 == 1
  6570. const Fresnel0ToIor = ( fresnel0 ) => {
  6571. const sqrtF0 = fresnel0.sqrt();
  6572. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  6573. };
  6574. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  6575. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  6576. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  6577. };
  6578. // Fresnel equations for dielectric/dielectric interfaces.
  6579. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  6580. // Evaluation XYZ sensitivity curves in Fourier space
  6581. const evalSensitivity = ( OPD, shift ) => {
  6582. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  6583. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  6584. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  6585. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  6586. const x = float( 9.7470e-14 * Math.sqrt( 2.0 * Math.PI * 4.5282e+09 ) ).mul( phase.mul( 2.2399e+06 ).add( shift.x ).cos() ).mul( phase.pow2().mul( - 4.5282e+09 ).exp() );
  6587. let xyz = val.mul( VAR.mul( 2.0 * Math.PI ).sqrt() ).mul( pos.mul( phase ).add( shift ).cos() ).mul( phase.pow2().negate().mul( VAR ).exp() );
  6588. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  6589. const rgb = XYZ_TO_REC709.mul( xyz );
  6590. return rgb;
  6591. };
  6592. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  6593. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  6594. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  6595. // Evaluate the cosTheta on the base layer (Snell law)
  6596. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  6597. // Handle TIR:
  6598. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  6599. If( cosTheta2Sq.lessThan( 0 ), () => {
  6600. return vec3( 1.0 );
  6601. } );
  6602. const cosTheta2 = cosTheta2Sq.sqrt();
  6603. // First interface
  6604. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  6605. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  6606. //const R21 = R12;
  6607. const T121 = R12.oneMinus();
  6608. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  6609. const phi21 = float( Math.PI ).sub( phi12 );
  6610. // Second interface
  6611. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  6612. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  6613. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  6614. const phi23 = vec3(
  6615. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  6616. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  6617. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  6618. );
  6619. // Phase shift
  6620. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  6621. const phi = vec3( phi21 ).add( phi23 );
  6622. // Compound terms
  6623. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  6624. const r123 = R123.sqrt();
  6625. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  6626. // Reflectance term for m = 0 (DC term amplitude)
  6627. const C0 = R12.add( Rs );
  6628. const I = C0.toVar();
  6629. // Reflectance term for m > 0 (pairs of diracs)
  6630. const Cm = Rs.sub( T121 ).toVar();
  6631. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  6632. Cm.mulAssign( r123 );
  6633. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  6634. I.addAssign( Cm.mul( Sm ) );
  6635. } );
  6636. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  6637. return I.max( vec3( 0.0 ) );
  6638. } ).setLayout( {
  6639. name: 'evalIridescence',
  6640. type: 'vec3',
  6641. inputs: [
  6642. { name: 'outsideIOR', type: 'float' },
  6643. { name: 'eta2', type: 'float' },
  6644. { name: 'cosTheta1', type: 'float' },
  6645. { name: 'thinFilmThickness', type: 'float' },
  6646. { name: 'baseF0', type: 'vec3' }
  6647. ]
  6648. } );
  6649. //
  6650. // Sheen
  6651. //
  6652. // This is a curve-fit approxmation to the "Charlie sheen" BRDF integrated over the hemisphere from
  6653. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  6654. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  6655. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  6656. const dotNV = normal.dot( viewDir ).saturate();
  6657. const r2 = roughness.pow2();
  6658. const a = select(
  6659. roughness.lessThan( 0.25 ),
  6660. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  6661. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  6662. );
  6663. const b = select(
  6664. roughness.lessThan( 0.25 ),
  6665. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  6666. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  6667. );
  6668. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  6669. return DG.mul( 1.0 / Math.PI ).saturate();
  6670. } );
  6671. const clearcoatF0 = vec3( 0.04 );
  6672. const clearcoatF90 = float( 1 );
  6673. //
  6674. class PhysicalLightingModel extends LightingModel {
  6675. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  6676. super();
  6677. this.clearcoat = clearcoat;
  6678. this.sheen = sheen;
  6679. this.iridescence = iridescence;
  6680. this.anisotropy = anisotropy;
  6681. this.transmission = transmission;
  6682. this.dispersion = dispersion;
  6683. this.clearcoatRadiance = null;
  6684. this.clearcoatSpecularDirect = null;
  6685. this.clearcoatSpecularIndirect = null;
  6686. this.sheenSpecularDirect = null;
  6687. this.sheenSpecularIndirect = null;
  6688. this.iridescenceFresnel = null;
  6689. this.iridescenceF0 = null;
  6690. }
  6691. start( context ) {
  6692. if ( this.clearcoat === true ) {
  6693. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  6694. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  6695. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  6696. }
  6697. if ( this.sheen === true ) {
  6698. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  6699. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  6700. }
  6701. if ( this.iridescence === true ) {
  6702. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  6703. this.iridescenceFresnel = evalIridescence( {
  6704. outsideIOR: float( 1.0 ),
  6705. eta2: iridescenceIOR,
  6706. cosTheta1: dotNVi,
  6707. thinFilmThickness: iridescenceThickness,
  6708. baseF0: specularColor
  6709. } );
  6710. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  6711. }
  6712. if ( this.transmission === true ) {
  6713. const position = positionWorld;
  6714. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  6715. const n = transformedNormalWorld;
  6716. context.backdrop = getIBLVolumeRefraction(
  6717. n,
  6718. v,
  6719. roughness,
  6720. diffuseColor,
  6721. specularColor,
  6722. specularF90, // specularF90
  6723. position, // positionWorld
  6724. modelWorldMatrix, // modelMatrix
  6725. cameraViewMatrix, // viewMatrix
  6726. cameraProjectionMatrix, // projMatrix
  6727. ior,
  6728. thickness,
  6729. attenuationColor,
  6730. attenuationDistance,
  6731. this.dispersion ? dispersion : null
  6732. );
  6733. context.backdropAlpha = transmission;
  6734. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  6735. }
  6736. }
  6737. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  6738. // Approximates multiscattering in order to preserve energy.
  6739. // http://www.jcgt.org/published/0008/01/03/
  6740. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  6741. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  6742. const fab = DFGApprox( { roughness, dotNV } );
  6743. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  6744. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  6745. const Ess = fab.x.add( fab.y );
  6746. const Ems = Ess.oneMinus();
  6747. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  6748. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  6749. singleScatter.addAssign( FssEss );
  6750. multiScatter.addAssign( Fms.mul( Ems ) );
  6751. }
  6752. direct( { lightDirection, lightColor, reflectedLight } ) {
  6753. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  6754. const irradiance = dotNL.mul( lightColor );
  6755. if ( this.sheen === true ) {
  6756. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  6757. }
  6758. if ( this.clearcoat === true ) {
  6759. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  6760. const ccIrradiance = dotNLcc.mul( lightColor );
  6761. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  6762. }
  6763. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  6764. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_GGX( { lightDirection, f0: specularColor, f90: 1, roughness, iridescence: this.iridescence, f: this.iridescenceFresnel, USE_IRIDESCENCE: this.iridescence, USE_ANISOTROPY: this.anisotropy } ) ) );
  6765. }
  6766. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  6767. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  6768. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  6769. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  6770. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  6771. const N = transformedNormalView;
  6772. const V = positionViewDirection;
  6773. const P = positionView.toVar();
  6774. const uv = LTC_Uv( { N, V, roughness } );
  6775. const t1 = ltc_1.uv( uv ).toVar();
  6776. const t2 = ltc_2.uv( uv ).toVar();
  6777. const mInv = mat3(
  6778. vec3( t1.x, 0, t1.y ),
  6779. vec3( 0, 1, 0 ),
  6780. vec3( t1.z, 0, t1.w )
  6781. ).toVar();
  6782. // LTC Fresnel Approximation by Stephen Hill
  6783. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  6784. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  6785. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  6786. reflectedLight.directDiffuse.addAssign( lightColor.mul( diffuseColor ).mul( LTC_Evaluate( { N, V, P, mInv: mat3( 1, 0, 0, 0, 1, 0, 0, 0, 1 ), p0, p1, p2, p3 } ) ) );
  6787. }
  6788. indirect( context, stack, builder ) {
  6789. this.indirectDiffuse( context, stack, builder );
  6790. this.indirectSpecular( context, stack, builder );
  6791. this.ambientOcclusion( context, stack, builder );
  6792. }
  6793. indirectDiffuse( { irradiance, reflectedLight } ) {
  6794. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  6795. }
  6796. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  6797. if ( this.sheen === true ) {
  6798. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  6799. sheen,
  6800. IBLSheenBRDF( {
  6801. normal: transformedNormalView,
  6802. viewDir: positionViewDirection,
  6803. roughness: sheenRoughness
  6804. } )
  6805. ) );
  6806. }
  6807. if ( this.clearcoat === true ) {
  6808. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  6809. const clearcoatEnv = EnvironmentBRDF( {
  6810. dotNV: dotNVcc,
  6811. specularColor: clearcoatF0,
  6812. specularF90: clearcoatF90,
  6813. roughness: clearcoatRoughness
  6814. } );
  6815. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  6816. }
  6817. // Both indirect specular and indirect diffuse light accumulate here
  6818. const singleScattering = vec3().toVar( 'singleScattering' );
  6819. const multiScattering = vec3().toVar( 'multiScattering' );
  6820. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  6821. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  6822. const totalScattering = singleScattering.add( multiScattering );
  6823. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  6824. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  6825. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  6826. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  6827. }
  6828. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  6829. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  6830. const aoNV = dotNV.add( ambientOcclusion );
  6831. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  6832. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  6833. if ( this.clearcoat === true ) {
  6834. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  6835. }
  6836. if ( this.sheen === true ) {
  6837. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  6838. }
  6839. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  6840. reflectedLight.indirectSpecular.mulAssign( aoNode );
  6841. }
  6842. finish( context ) {
  6843. const { outgoingLight } = context;
  6844. if ( this.clearcoat === true ) {
  6845. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  6846. const Fcc = F_Schlick( {
  6847. dotVH: dotNVcc,
  6848. f0: clearcoatF0,
  6849. f90: clearcoatF90
  6850. } );
  6851. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  6852. outgoingLight.assign( clearcoatLight );
  6853. }
  6854. if ( this.sheen === true ) {
  6855. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  6856. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  6857. outgoingLight.assign( sheenLight );
  6858. }
  6859. }
  6860. }
  6861. // These defines must match with PMREMGenerator
  6862. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  6863. const cubeUV_m0 = /*@__PURE__*/ float( - 2.0 );
  6864. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  6865. const cubeUV_m1 = /*@__PURE__*/ float( - 1.0 );
  6866. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  6867. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  6868. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  6869. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  6870. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  6871. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  6872. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  6873. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  6874. // These shader functions convert between the UV coordinates of a single face of
  6875. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  6876. // sampling a textureCube (not generally normalized ).
  6877. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  6878. const absDirection = vec3( abs( direction ) ).toVar();
  6879. const face = float( - 1.0 ).toVar();
  6880. If( absDirection.x.greaterThan( absDirection.z ), () => {
  6881. If( absDirection.x.greaterThan( absDirection.y ), () => {
  6882. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  6883. } ).Else( () => {
  6884. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  6885. } );
  6886. } ).Else( () => {
  6887. If( absDirection.z.greaterThan( absDirection.y ), () => {
  6888. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  6889. } ).Else( () => {
  6890. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  6891. } );
  6892. } );
  6893. return face;
  6894. } ).setLayout( {
  6895. name: 'getFace',
  6896. type: 'float',
  6897. inputs: [
  6898. { name: 'direction', type: 'vec3' }
  6899. ]
  6900. } );
  6901. // RH coordinate system; PMREM face-indexing convention
  6902. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  6903. const uv = vec2().toVar();
  6904. If( face.equal( 0.0 ), () => {
  6905. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  6906. } ).ElseIf( face.equal( 1.0 ), () => {
  6907. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  6908. } ).ElseIf( face.equal( 2.0 ), () => {
  6909. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  6910. } ).ElseIf( face.equal( 3.0 ), () => {
  6911. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  6912. } ).ElseIf( face.equal( 4.0 ), () => {
  6913. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  6914. } ).Else( () => {
  6915. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  6916. } );
  6917. return mul( 0.5, uv.add( 1.0 ) );
  6918. } ).setLayout( {
  6919. name: 'getUV',
  6920. type: 'vec2',
  6921. inputs: [
  6922. { name: 'direction', type: 'vec3' },
  6923. { name: 'face', type: 'float' }
  6924. ]
  6925. } );
  6926. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  6927. const mip = float( 0.0 ).toVar();
  6928. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  6929. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  6930. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  6931. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  6932. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  6933. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  6934. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  6935. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  6936. } ).Else( () => {
  6937. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  6938. } );
  6939. return mip;
  6940. } ).setLayout( {
  6941. name: 'roughnessToMip',
  6942. type: 'float',
  6943. inputs: [
  6944. { name: 'roughness', type: 'float' }
  6945. ]
  6946. } );
  6947. // RH coordinate system; PMREM face-indexing convention
  6948. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  6949. const uv = uv_immutable.toVar();
  6950. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  6951. const direction = vec3( uv, 1.0 ).toVar();
  6952. If( face.equal( 0.0 ), () => {
  6953. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  6954. } ).ElseIf( face.equal( 1.0 ), () => {
  6955. direction.assign( direction.xzy );
  6956. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  6957. } ).ElseIf( face.equal( 2.0 ), () => {
  6958. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  6959. } ).ElseIf( face.equal( 3.0 ), () => {
  6960. direction.assign( direction.zyx );
  6961. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  6962. } ).ElseIf( face.equal( 4.0 ), () => {
  6963. direction.assign( direction.xzy );
  6964. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  6965. } ).ElseIf( face.equal( 5.0 ), () => {
  6966. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  6967. } );
  6968. return direction;
  6969. } ).setLayout( {
  6970. name: 'getDirection',
  6971. type: 'vec3',
  6972. inputs: [
  6973. { name: 'uv', type: 'vec2' },
  6974. { name: 'face', type: 'float' }
  6975. ]
  6976. } );
  6977. //
  6978. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  6979. const roughness = float( roughness_immutable );
  6980. const sampleDir = vec3( sampleDir_immutable );
  6981. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  6982. const mipF = fract( mip );
  6983. const mipInt = floor( mip );
  6984. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  6985. If( mipF.notEqual( 0.0 ), () => {
  6986. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  6987. color0.assign( mix( color0, color1, mipF ) );
  6988. } );
  6989. return color0;
  6990. } );
  6991. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  6992. const mipInt = float( mipInt_immutable ).toVar();
  6993. const direction = vec3( direction_immutable );
  6994. const face = float( getFace( direction ) ).toVar();
  6995. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  6996. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  6997. const faceSize = float( exp2( mipInt ) ).toVar();
  6998. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  6999. If( face.greaterThan( 2.0 ), () => {
  7000. uv.y.addAssign( faceSize );
  7001. face.subAssign( 3.0 );
  7002. } );
  7003. uv.x.addAssign( face.mul( faceSize ) );
  7004. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  7005. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  7006. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  7007. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  7008. return envMap.uv( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  7009. } );
  7010. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  7011. const cosTheta = cos( theta );
  7012. // Rodrigues' axis-angle rotation
  7013. const sampleDirection = outputDirection.mul( cosTheta )
  7014. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  7015. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  7016. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  7017. } );
  7018. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  7019. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  7020. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  7021. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  7022. } );
  7023. axis.assign( normalize( axis ) );
  7024. const gl_FragColor = vec3().toVar();
  7025. gl_FragColor.addAssign( weights.element( int( 0 ) ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  7026. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  7027. If( i.greaterThanEqual( samples ), () => {
  7028. Break();
  7029. } );
  7030. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  7031. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta: theta.mul( - 1.0 ), axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  7032. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  7033. } );
  7034. return vec4( gl_FragColor, 1 );
  7035. } );
  7036. let _generator = null;
  7037. const _cache = new WeakMap();
  7038. function _generateCubeUVSize( imageHeight ) {
  7039. const maxMip = Math.log2( imageHeight ) - 2;
  7040. const texelHeight = 1.0 / imageHeight;
  7041. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  7042. return { texelWidth, texelHeight, maxMip };
  7043. }
  7044. function _getPMREMFromTexture( texture ) {
  7045. let cacheTexture = _cache.get( texture );
  7046. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  7047. if ( pmremVersion !== texture.pmremVersion ) {
  7048. const image = texture.image;
  7049. if ( texture.isCubeTexture ) {
  7050. if ( isCubeMapReady( image ) ) {
  7051. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  7052. } else {
  7053. return null;
  7054. }
  7055. } else {
  7056. if ( isEquirectangularMapReady( image ) ) {
  7057. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  7058. } else {
  7059. return null;
  7060. }
  7061. }
  7062. cacheTexture.pmremVersion = texture.pmremVersion;
  7063. _cache.set( texture, cacheTexture );
  7064. }
  7065. return cacheTexture.texture;
  7066. }
  7067. class PMREMNode extends TempNode {
  7068. static get type() {
  7069. return 'PMREMNode';
  7070. }
  7071. constructor( value, uvNode = null, levelNode = null ) {
  7072. super( 'vec3' );
  7073. this._value = value;
  7074. this._pmrem = null;
  7075. this.uvNode = uvNode;
  7076. this.levelNode = levelNode;
  7077. this._generator = null;
  7078. const defaultTexture = new Texture();
  7079. defaultTexture.isRenderTargetTexture = true;
  7080. this._texture = texture( defaultTexture );
  7081. this._width = uniform( 0 );
  7082. this._height = uniform( 0 );
  7083. this._maxMip = uniform( 0 );
  7084. this.updateBeforeType = NodeUpdateType.RENDER;
  7085. }
  7086. set value( value ) {
  7087. this._value = value;
  7088. this._pmrem = null;
  7089. }
  7090. get value() {
  7091. return this._value;
  7092. }
  7093. updateFromTexture( texture ) {
  7094. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  7095. this._texture.value = texture;
  7096. this._width.value = cubeUVSize.texelWidth;
  7097. this._height.value = cubeUVSize.texelHeight;
  7098. this._maxMip.value = cubeUVSize.maxMip;
  7099. }
  7100. updateBefore() {
  7101. let pmrem = this._pmrem;
  7102. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  7103. const texture = this._value;
  7104. if ( pmremVersion !== texture.pmremVersion ) {
  7105. if ( texture.isPMREMTexture === true ) {
  7106. pmrem = texture;
  7107. } else {
  7108. pmrem = _getPMREMFromTexture( texture );
  7109. }
  7110. if ( pmrem !== null ) {
  7111. this._pmrem = pmrem;
  7112. this.updateFromTexture( pmrem );
  7113. }
  7114. }
  7115. }
  7116. setup( builder ) {
  7117. if ( _generator === null ) {
  7118. _generator = builder.createPMREMGenerator();
  7119. }
  7120. //
  7121. this.updateBefore( builder );
  7122. //
  7123. let uvNode = this.uvNode;
  7124. if ( uvNode === null && builder.context.getUV ) {
  7125. uvNode = builder.context.getUV( this );
  7126. }
  7127. //
  7128. const texture = this.value;
  7129. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  7130. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  7131. }
  7132. //
  7133. let levelNode = this.levelNode;
  7134. if ( levelNode === null && builder.context.getTextureLevel ) {
  7135. levelNode = builder.context.getTextureLevel( this );
  7136. }
  7137. //
  7138. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  7139. }
  7140. }
  7141. function isCubeMapReady( image ) {
  7142. if ( image === null || image === undefined ) return false;
  7143. let count = 0;
  7144. const length = 6;
  7145. for ( let i = 0; i < length; i ++ ) {
  7146. if ( image[ i ] !== undefined ) count ++;
  7147. }
  7148. return count === length;
  7149. }
  7150. function isEquirectangularMapReady( image ) {
  7151. if ( image === null || image === undefined ) return false;
  7152. return image.height > 0;
  7153. }
  7154. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  7155. const _envNodeCache = new WeakMap();
  7156. class EnvironmentNode extends LightingNode {
  7157. static get type() {
  7158. return 'EnvironmentNode';
  7159. }
  7160. constructor( envNode = null ) {
  7161. super();
  7162. this.envNode = envNode;
  7163. }
  7164. setup( builder ) {
  7165. const { material } = builder;
  7166. let envNode = this.envNode;
  7167. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  7168. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  7169. let cacheEnvNode = _envNodeCache.get( value );
  7170. if ( cacheEnvNode === undefined ) {
  7171. cacheEnvNode = pmremTexture( value );
  7172. _envNodeCache.set( value, cacheEnvNode );
  7173. }
  7174. envNode = cacheEnvNode;
  7175. }
  7176. //
  7177. const envMap = material.envMap;
  7178. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  7179. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  7180. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  7181. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  7182. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  7183. const isolateRadiance = cache( radiance );
  7184. const isolateIrradiance = cache( irradiance );
  7185. //
  7186. builder.context.radiance.addAssign( isolateRadiance );
  7187. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  7188. //
  7189. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  7190. if ( clearcoatRadiance ) {
  7191. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  7192. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  7193. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  7194. }
  7195. }
  7196. }
  7197. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  7198. let reflectVec = null;
  7199. return {
  7200. getUV: () => {
  7201. if ( reflectVec === null ) {
  7202. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  7203. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  7204. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  7205. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  7206. }
  7207. return reflectVec;
  7208. },
  7209. getTextureLevel: () => {
  7210. return roughnessNode;
  7211. }
  7212. };
  7213. };
  7214. const createIrradianceContext = ( normalWorldNode ) => {
  7215. return {
  7216. getUV: () => {
  7217. return normalWorldNode;
  7218. },
  7219. getTextureLevel: () => {
  7220. return float( 1.0 );
  7221. }
  7222. };
  7223. };
  7224. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  7225. class MeshStandardNodeMaterial extends NodeMaterial {
  7226. static get type() {
  7227. return 'MeshStandardNodeMaterial';
  7228. }
  7229. constructor( parameters ) {
  7230. super();
  7231. this.isMeshStandardNodeMaterial = true;
  7232. this.lights = true;
  7233. this.emissiveNode = null;
  7234. this.metalnessNode = null;
  7235. this.roughnessNode = null;
  7236. this.setDefaultValues( _defaultValues$6 );
  7237. this.setValues( parameters );
  7238. }
  7239. setupEnvironment( builder ) {
  7240. let envNode = super.setupEnvironment( builder );
  7241. if ( envNode === null && builder.environmentNode ) {
  7242. envNode = builder.environmentNode;
  7243. }
  7244. return envNode ? new EnvironmentNode( envNode ) : null;
  7245. }
  7246. setupLightingModel( /*builder*/ ) {
  7247. return new PhysicalLightingModel();
  7248. }
  7249. setupSpecular() {
  7250. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  7251. specularColor.assign( specularColorNode );
  7252. specularF90.assign( 1.0 );
  7253. }
  7254. setupVariants() {
  7255. // METALNESS
  7256. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  7257. metalness.assign( metalnessNode );
  7258. // ROUGHNESS
  7259. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  7260. roughnessNode = getRoughness( { roughness: roughnessNode } );
  7261. roughness.assign( roughnessNode );
  7262. // SPECULAR COLOR
  7263. this.setupSpecular();
  7264. // DIFFUSE COLOR
  7265. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  7266. }
  7267. copy( source ) {
  7268. this.emissiveNode = source.emissiveNode;
  7269. this.metalnessNode = source.metalnessNode;
  7270. this.roughnessNode = source.roughnessNode;
  7271. return super.copy( source );
  7272. }
  7273. }
  7274. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  7275. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  7276. static get type() {
  7277. return 'MeshPhysicalNodeMaterial';
  7278. }
  7279. constructor( parameters ) {
  7280. super();
  7281. this.isMeshPhysicalNodeMaterial = true;
  7282. this.clearcoatNode = null;
  7283. this.clearcoatRoughnessNode = null;
  7284. this.clearcoatNormalNode = null;
  7285. this.sheenNode = null;
  7286. this.sheenRoughnessNode = null;
  7287. this.iridescenceNode = null;
  7288. this.iridescenceIORNode = null;
  7289. this.iridescenceThicknessNode = null;
  7290. this.specularIntensityNode = null;
  7291. this.specularColorNode = null;
  7292. this.iorNode = null;
  7293. this.transmissionNode = null;
  7294. this.thicknessNode = null;
  7295. this.attenuationDistanceNode = null;
  7296. this.attenuationColorNode = null;
  7297. this.dispersionNode = null;
  7298. this.anisotropyNode = null;
  7299. this.setDefaultValues( _defaultValues$5 );
  7300. this.setValues( parameters );
  7301. }
  7302. get useClearcoat() {
  7303. return this.clearcoat > 0 || this.clearcoatNode !== null;
  7304. }
  7305. get useIridescence() {
  7306. return this.iridescence > 0 || this.iridescenceNode !== null;
  7307. }
  7308. get useSheen() {
  7309. return this.sheen > 0 || this.sheenNode !== null;
  7310. }
  7311. get useAnisotropy() {
  7312. return this.anisotropy > 0 || this.anisotropyNode !== null;
  7313. }
  7314. get useTransmission() {
  7315. return this.transmission > 0 || this.transmissionNode !== null;
  7316. }
  7317. get useDispersion() {
  7318. return this.dispersion > 0 || this.dispersionNode !== null;
  7319. }
  7320. setupSpecular() {
  7321. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  7322. ior.assign( iorNode );
  7323. specularColor.assign( mix( min$1( pow2( ior.sub( 1.0 ).div( ior.add( 1.0 ) ) ).mul( materialSpecularColor ), vec3( 1.0 ) ).mul( materialSpecularIntensity ), diffuseColor.rgb, metalness ) );
  7324. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  7325. }
  7326. setupLightingModel( /*builder*/ ) {
  7327. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  7328. }
  7329. setupVariants( builder ) {
  7330. super.setupVariants( builder );
  7331. // CLEARCOAT
  7332. if ( this.useClearcoat ) {
  7333. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  7334. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  7335. clearcoat.assign( clearcoatNode );
  7336. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  7337. }
  7338. // SHEEN
  7339. if ( this.useSheen ) {
  7340. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  7341. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  7342. sheen.assign( sheenNode );
  7343. sheenRoughness.assign( sheenRoughnessNode );
  7344. }
  7345. // IRIDESCENCE
  7346. if ( this.useIridescence ) {
  7347. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  7348. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  7349. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  7350. iridescence.assign( iridescenceNode );
  7351. iridescenceIOR.assign( iridescenceIORNode );
  7352. iridescenceThickness.assign( iridescenceThicknessNode );
  7353. }
  7354. // ANISOTROPY
  7355. if ( this.useAnisotropy ) {
  7356. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  7357. anisotropy.assign( anisotropyV.length() );
  7358. If( anisotropy.equal( 0.0 ), () => {
  7359. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  7360. } ).Else( () => {
  7361. anisotropyV.divAssign( vec2( anisotropy ) );
  7362. anisotropy.assign( anisotropy.saturate() );
  7363. } );
  7364. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  7365. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  7366. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  7367. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  7368. }
  7369. // TRANSMISSION
  7370. if ( this.useTransmission ) {
  7371. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  7372. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  7373. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  7374. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  7375. transmission.assign( transmissionNode );
  7376. thickness.assign( thicknessNode );
  7377. attenuationDistance.assign( attenuationDistanceNode );
  7378. attenuationColor.assign( attenuationColorNode );
  7379. if ( this.useDispersion ) {
  7380. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  7381. dispersion.assign( dispersionNode );
  7382. }
  7383. }
  7384. }
  7385. setupClearcoatNormal() {
  7386. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  7387. }
  7388. setup( builder ) {
  7389. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  7390. super.setup( builder );
  7391. }
  7392. copy( source ) {
  7393. this.clearcoatNode = source.clearcoatNode;
  7394. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  7395. this.clearcoatNormalNode = source.clearcoatNormalNode;
  7396. this.sheenNode = source.sheenNode;
  7397. this.sheenRoughnessNode = source.sheenRoughnessNode;
  7398. this.iridescenceNode = source.iridescenceNode;
  7399. this.iridescenceIORNode = source.iridescenceIORNode;
  7400. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  7401. this.specularIntensityNode = source.specularIntensityNode;
  7402. this.specularColorNode = source.specularColorNode;
  7403. this.transmissionNode = source.transmissionNode;
  7404. this.thicknessNode = source.thicknessNode;
  7405. this.attenuationDistanceNode = source.attenuationDistanceNode;
  7406. this.attenuationColorNode = source.attenuationColorNode;
  7407. this.dispersionNode = source.dispersionNode;
  7408. this.anisotropyNode = source.anisotropyNode;
  7409. return super.copy( source );
  7410. }
  7411. }
  7412. class SSSLightingModel extends PhysicalLightingModel {
  7413. constructor( useClearcoat, useSheen, useIridescence, useSSS ) {
  7414. super( useClearcoat, useSheen, useIridescence );
  7415. this.useSSS = useSSS;
  7416. }
  7417. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  7418. if ( this.useSSS === true ) {
  7419. const material = builder.material;
  7420. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  7421. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  7422. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  7423. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  7424. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  7425. }
  7426. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  7427. }
  7428. }
  7429. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  7430. static get type() {
  7431. return 'MeshSSSNodeMaterial';
  7432. }
  7433. constructor( parameters ) {
  7434. super( parameters );
  7435. this.thicknessColorNode = null;
  7436. this.thicknessDistortionNode = float( 0.1 );
  7437. this.thicknessAmbientNode = float( 0.0 );
  7438. this.thicknessAttenuationNode = float( .1 );
  7439. this.thicknessPowerNode = float( 2.0 );
  7440. this.thicknessScaleNode = float( 10.0 );
  7441. }
  7442. get useSSS() {
  7443. return this.thicknessColorNode !== null;
  7444. }
  7445. setupLightingModel( /*builder*/ ) {
  7446. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useSSS );
  7447. }
  7448. copy( source ) {
  7449. this.thicknessColorNode = source.thicknessColorNode;
  7450. this.thicknessDistortionNode = source.thicknessDistortionNode;
  7451. this.thicknessAmbientNode = source.thicknessAmbientNode;
  7452. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  7453. this.thicknessPowerNode = source.thicknessPowerNode;
  7454. this.thicknessScaleNode = source.thicknessScaleNode;
  7455. return super.copy( source );
  7456. }
  7457. }
  7458. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  7459. // dotNL will be from -1.0 to 1.0
  7460. const dotNL = normal.dot( lightDirection );
  7461. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  7462. if ( builder.material.gradientMap ) {
  7463. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  7464. return vec3( gradientMap.r );
  7465. } else {
  7466. const fw = coord.fwidth().mul( 0.5 );
  7467. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  7468. }
  7469. } );
  7470. class ToonLightingModel extends LightingModel {
  7471. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  7472. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  7473. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  7474. }
  7475. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  7476. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  7477. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  7478. }
  7479. }
  7480. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  7481. class MeshToonNodeMaterial extends NodeMaterial {
  7482. static get type() {
  7483. return 'MeshToonNodeMaterial';
  7484. }
  7485. constructor( parameters ) {
  7486. super();
  7487. this.isMeshToonNodeMaterial = true;
  7488. this.lights = true;
  7489. this.setDefaultValues( _defaultValues$4 );
  7490. this.setValues( parameters );
  7491. }
  7492. setupLightingModel( /*builder*/ ) {
  7493. return new ToonLightingModel();
  7494. }
  7495. }
  7496. class MatcapUVNode extends TempNode {
  7497. static get type() {
  7498. return 'MatcapUVNode';
  7499. }
  7500. constructor() {
  7501. super( 'vec2' );
  7502. }
  7503. setup() {
  7504. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  7505. const y = positionViewDirection.cross( x );
  7506. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  7507. }
  7508. }
  7509. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  7510. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  7511. class MeshMatcapNodeMaterial extends NodeMaterial {
  7512. static get type() {
  7513. return 'MeshMatcapNodeMaterial';
  7514. }
  7515. constructor( parameters ) {
  7516. super();
  7517. this.lights = false;
  7518. this.isMeshMatcapNodeMaterial = true;
  7519. this.setDefaultValues( _defaultValues$3 );
  7520. this.setValues( parameters );
  7521. }
  7522. setupVariants( builder ) {
  7523. const uv = matcapUV;
  7524. let matcapColor;
  7525. if ( builder.material.matcap ) {
  7526. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  7527. } else {
  7528. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  7529. }
  7530. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  7531. }
  7532. }
  7533. const _defaultValues$2 = /*@__PURE__*/ new PointsMaterial();
  7534. class PointsNodeMaterial extends NodeMaterial {
  7535. static get type() {
  7536. return 'PointsNodeMaterial';
  7537. }
  7538. constructor( parameters ) {
  7539. super();
  7540. this.isPointsNodeMaterial = true;
  7541. this.lights = false;
  7542. this.transparent = true;
  7543. this.sizeNode = null;
  7544. this.setDefaultValues( _defaultValues$2 );
  7545. this.setValues( parameters );
  7546. }
  7547. copy( source ) {
  7548. this.sizeNode = source.sizeNode;
  7549. return super.copy( source );
  7550. }
  7551. }
  7552. class RotateNode extends TempNode {
  7553. static get type() {
  7554. return 'RotateNode';
  7555. }
  7556. constructor( positionNode, rotationNode ) {
  7557. super();
  7558. this.positionNode = positionNode;
  7559. this.rotationNode = rotationNode;
  7560. }
  7561. getNodeType( builder ) {
  7562. return this.positionNode.getNodeType( builder );
  7563. }
  7564. setup( builder ) {
  7565. const { rotationNode, positionNode } = this;
  7566. const nodeType = this.getNodeType( builder );
  7567. if ( nodeType === 'vec2' ) {
  7568. const cosAngle = rotationNode.cos();
  7569. const sinAngle = rotationNode.sin();
  7570. const rotationMatrix = mat2(
  7571. cosAngle, sinAngle,
  7572. sinAngle.negate(), cosAngle
  7573. );
  7574. return rotationMatrix.mul( positionNode );
  7575. } else {
  7576. const rotation = rotationNode;
  7577. const rotationXMatrix = mat4( vec4( 1.0, 0.0, 0.0, 0.0 ), vec4( 0.0, cos( rotation.x ), sin( rotation.x ).negate(), 0.0 ), vec4( 0.0, sin( rotation.x ), cos( rotation.x ), 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) );
  7578. const rotationYMatrix = mat4( vec4( cos( rotation.y ), 0.0, sin( rotation.y ), 0.0 ), vec4( 0.0, 1.0, 0.0, 0.0 ), vec4( sin( rotation.y ).negate(), 0.0, cos( rotation.y ), 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) );
  7579. const rotationZMatrix = mat4( vec4( cos( rotation.z ), sin( rotation.z ).negate(), 0.0, 0.0 ), vec4( sin( rotation.z ), cos( rotation.z ), 0.0, 0.0 ), vec4( 0.0, 0.0, 1.0, 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) );
  7580. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  7581. }
  7582. }
  7583. }
  7584. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  7585. const _defaultValues$1 = /*@__PURE__*/ new SpriteMaterial();
  7586. class SpriteNodeMaterial extends NodeMaterial {
  7587. static get type() {
  7588. return 'SpriteNodeMaterial';
  7589. }
  7590. constructor( parameters ) {
  7591. super();
  7592. this.isSpriteNodeMaterial = true;
  7593. this.lights = false;
  7594. this._useSizeAttenuation = true;
  7595. this.positionNode = null;
  7596. this.rotationNode = null;
  7597. this.scaleNode = null;
  7598. this.setDefaultValues( _defaultValues$1 );
  7599. this.setValues( parameters );
  7600. }
  7601. setupPosition( { object, camera, context } ) {
  7602. const sizeAttenuation = this.sizeAttenuation;
  7603. // < VERTEX STAGE >
  7604. const { positionNode, rotationNode, scaleNode } = this;
  7605. const vertex = positionLocal;
  7606. let mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  7607. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  7608. if ( scaleNode !== null ) {
  7609. scale = scale.mul( scaleNode );
  7610. }
  7611. if ( ! sizeAttenuation ) {
  7612. if ( camera.isPerspectiveCamera ) {
  7613. scale = scale.mul( mvPosition.z.negate() );
  7614. } else {
  7615. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  7616. scale = scale.mul( orthoScale.mul( 2 ) );
  7617. }
  7618. }
  7619. let alignedPosition = vertex.xy;
  7620. if ( object.center && object.center.isVector2 === true ) {
  7621. const center = reference$1( 'center', 'vec2' );
  7622. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  7623. }
  7624. alignedPosition = alignedPosition.mul( scale );
  7625. const rotation = float( rotationNode || materialRotation );
  7626. const rotatedPosition = rotate( alignedPosition, rotation );
  7627. mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  7628. const modelViewProjection = cameraProjectionMatrix.mul( mvPosition );
  7629. context.vertex = vertex;
  7630. return modelViewProjection;
  7631. }
  7632. copy( source ) {
  7633. this.positionNode = source.positionNode;
  7634. this.rotationNode = source.rotationNode;
  7635. this.scaleNode = source.scaleNode;
  7636. return super.copy( source );
  7637. }
  7638. get sizeAttenuation() {
  7639. return this._useSizeAttenuation;
  7640. }
  7641. set sizeAttenuation( value ) {
  7642. if ( this._useSizeAttenuation !== value ) {
  7643. this._useSizeAttenuation = value;
  7644. this.needsUpdate = true;
  7645. }
  7646. }
  7647. }
  7648. class ShadowMaskModel extends LightingModel {
  7649. constructor() {
  7650. super();
  7651. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  7652. }
  7653. direct( { shadowMask } ) {
  7654. this.shadowNode.mulAssign( shadowMask );
  7655. }
  7656. finish( context ) {
  7657. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  7658. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  7659. }
  7660. }
  7661. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  7662. class ShadowNodeMaterial extends NodeMaterial {
  7663. static get type() {
  7664. return 'ShadowNodeMaterial';
  7665. }
  7666. constructor( parameters ) {
  7667. super();
  7668. this.isShadowNodeMaterial = true;
  7669. this.lights = true;
  7670. this.setDefaultValues( _defaultValues );
  7671. this.setValues( parameters );
  7672. }
  7673. setupLightingModel( /*builder*/ ) {
  7674. return new ShadowMaskModel();
  7675. }
  7676. }
  7677. const normal = Fn( ( { texture, uv } ) => {
  7678. const epsilon = 0.0001;
  7679. const ret = vec3().toVar();
  7680. If( uv.x.lessThan( epsilon ), () => {
  7681. ret.assign( vec3( 1, 0, 0 ) );
  7682. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  7683. ret.assign( vec3( 0, 1, 0 ) );
  7684. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  7685. ret.assign( vec3( 0, 0, 1 ) );
  7686. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  7687. ret.assign( vec3( - 1, 0, 0 ) );
  7688. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  7689. ret.assign( vec3( 0, - 1, 0 ) );
  7690. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  7691. ret.assign( vec3( 0, 0, - 1 ) );
  7692. } ).Else( () => {
  7693. const step = 0.01;
  7694. const x = texture.uv( uv.add( vec3( - step, 0.0, 0.0 ) ) ).r.sub( texture.uv( uv.add( vec3( step, 0.0, 0.0 ) ) ).r );
  7695. const y = texture.uv( uv.add( vec3( 0.0, - step, 0.0 ) ) ).r.sub( texture.uv( uv.add( vec3( 0.0, step, 0.0 ) ) ).r );
  7696. const z = texture.uv( uv.add( vec3( 0.0, 0.0, - step ) ) ).r.sub( texture.uv( uv.add( vec3( 0.0, 0.0, step ) ) ).r );
  7697. ret.assign( vec3( x, y, z ) );
  7698. } );
  7699. return ret.normalize();
  7700. } );
  7701. class Texture3DNode extends TextureNode {
  7702. static get type() {
  7703. return 'Texture3DNode';
  7704. }
  7705. constructor( value, uvNode = null, levelNode = null ) {
  7706. super( value, uvNode, levelNode );
  7707. this.isTexture3DNode = true;
  7708. }
  7709. getInputType( /*builder*/ ) {
  7710. return 'texture3D';
  7711. }
  7712. getDefaultUV() {
  7713. return vec3( 0.5, 0.5, 0.5 );
  7714. }
  7715. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  7716. setupUV( builder, uvNode ) {
  7717. return uvNode;
  7718. }
  7719. generateUV( builder, uvNode ) {
  7720. return uvNode.build( builder, 'vec3' );
  7721. }
  7722. normal( uvNode ) {
  7723. return normal( { texture: this, uv: uvNode } );
  7724. }
  7725. }
  7726. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  7727. class VolumeNodeMaterial extends NodeMaterial {
  7728. static get type() {
  7729. return 'VolumeNodeMaterial';
  7730. }
  7731. constructor( params = {} ) {
  7732. super();
  7733. this.lights = false;
  7734. this.isVolumeNodeMaterial = true;
  7735. this.testNode = null;
  7736. this.setValues( params );
  7737. }
  7738. setup( builder ) {
  7739. const map = texture3D( this.map, null, 0 );
  7740. const hitBox = Fn( ( { orig, dir } ) => {
  7741. const box_min = vec3( - 0.5 );
  7742. const box_max = vec3( 0.5 );
  7743. const inv_dir = dir.reciprocal();
  7744. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  7745. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  7746. const tmin = min$1( tmin_tmp, tmax_tmp );
  7747. const tmax = max$1( tmin_tmp, tmax_tmp );
  7748. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  7749. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  7750. return vec2( t0, t1 );
  7751. } );
  7752. this.fragmentNode = Fn( () => {
  7753. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  7754. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  7755. const rayDir = vDirection.normalize();
  7756. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  7757. bounds.x.greaterThan( bounds.y ).discard();
  7758. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  7759. const p = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  7760. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  7761. const delta = float( min$1( inc.x, min$1( inc.y, inc.z ) ) ).toVar( 'delta' ); // used 'delta' name in loop
  7762. delta.divAssign( materialReference( 'steps', 'float' ) );
  7763. const ac = vec4( materialReference( 'base', 'color' ), 0.0 ).toVar();
  7764. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  7765. const d = property( 'float', 'd' ).assign( map.uv( p.add( 0.5 ) ).r );
  7766. if ( this.testNode !== null ) {
  7767. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  7768. } else {
  7769. // default to show surface of mesh
  7770. ac.a.assign( 1 );
  7771. Break();
  7772. }
  7773. p.addAssign( rayDir.mul( delta ) );
  7774. } );
  7775. ac.a.equal( 0 ).discard();
  7776. return vec4( ac );
  7777. } )();
  7778. super.setup( builder );
  7779. }
  7780. }
  7781. class Animation {
  7782. constructor( nodes, info ) {
  7783. this.nodes = nodes;
  7784. this.info = info;
  7785. this._context = self;
  7786. this._animationLoop = null;
  7787. this._requestId = null;
  7788. }
  7789. start() {
  7790. const update = ( time, frame ) => {
  7791. this._requestId = this._context.requestAnimationFrame( update );
  7792. if ( this.info.autoReset === true ) this.info.reset();
  7793. this.nodes.nodeFrame.update();
  7794. this.info.frame = this.nodes.nodeFrame.frameId;
  7795. if ( this._animationLoop !== null ) this._animationLoop( time, frame );
  7796. };
  7797. update();
  7798. }
  7799. stop() {
  7800. this._context.cancelAnimationFrame( this._requestId );
  7801. this._requestId = null;
  7802. }
  7803. setAnimationLoop( callback ) {
  7804. this._animationLoop = callback;
  7805. }
  7806. setContext( context ) {
  7807. this._context = context;
  7808. }
  7809. dispose() {
  7810. this.stop();
  7811. }
  7812. }
  7813. class ChainMap {
  7814. constructor() {
  7815. this.weakMap = new WeakMap();
  7816. }
  7817. get( keys ) {
  7818. let map = this.weakMap;
  7819. for ( let i = 0; i < keys.length; i ++ ) {
  7820. map = map.get( keys[ i ] );
  7821. if ( map === undefined ) return undefined;
  7822. }
  7823. return map.get( keys[ keys.length - 1 ] );
  7824. }
  7825. set( keys, value ) {
  7826. let map = this.weakMap;
  7827. for ( let i = 0; i < keys.length; i ++ ) {
  7828. const key = keys[ i ];
  7829. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  7830. map = map.get( key );
  7831. }
  7832. return map.set( keys[ keys.length - 1 ], value );
  7833. }
  7834. delete( keys ) {
  7835. let map = this.weakMap;
  7836. for ( let i = 0; i < keys.length; i ++ ) {
  7837. map = map.get( keys[ i ] );
  7838. if ( map === undefined ) return false;
  7839. }
  7840. return map.delete( keys[ keys.length - 1 ] );
  7841. }
  7842. }
  7843. let _id$7 = 0;
  7844. function getKeys( obj ) {
  7845. const keys = Object.keys( obj );
  7846. let proto = Object.getPrototypeOf( obj );
  7847. while ( proto ) {
  7848. const descriptors = Object.getOwnPropertyDescriptors( proto );
  7849. for ( const key in descriptors ) {
  7850. if ( descriptors[ key ] !== undefined ) {
  7851. const descriptor = descriptors[ key ];
  7852. if ( descriptor && typeof descriptor.get === 'function' ) {
  7853. keys.push( key );
  7854. }
  7855. }
  7856. }
  7857. proto = Object.getPrototypeOf( proto );
  7858. }
  7859. return keys;
  7860. }
  7861. class RenderObject {
  7862. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  7863. this._nodes = nodes;
  7864. this._geometries = geometries;
  7865. this.id = _id$7 ++;
  7866. this.renderer = renderer;
  7867. this.object = object;
  7868. this.material = material;
  7869. this.scene = scene;
  7870. this.camera = camera;
  7871. this.lightsNode = lightsNode;
  7872. this.context = renderContext;
  7873. this.geometry = object.geometry;
  7874. this.version = material.version;
  7875. this.drawRange = null;
  7876. this.attributes = null;
  7877. this.pipeline = null;
  7878. this.vertexBuffers = null;
  7879. this.drawParams = null;
  7880. this.bundle = null;
  7881. this.clippingContext = clippingContext;
  7882. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  7883. this.initialNodesCacheKey = this.getDynamicCacheKey();
  7884. this.initialCacheKey = this.getCacheKey();
  7885. this._nodeBuilderState = null;
  7886. this._bindings = null;
  7887. this._monitor = null;
  7888. this.onDispose = null;
  7889. this.isRenderObject = true;
  7890. this.onMaterialDispose = () => {
  7891. this.dispose();
  7892. };
  7893. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  7894. }
  7895. updateClipping( parent ) {
  7896. this.clippingContext = parent;
  7897. }
  7898. get clippingNeedsUpdate() {
  7899. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  7900. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  7901. return true;
  7902. }
  7903. get hardwareClippingPlanes() {
  7904. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  7905. }
  7906. getNodeBuilderState() {
  7907. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  7908. }
  7909. getMonitor() {
  7910. return this._monitor || ( this._monitor = this.getNodeBuilderState().monitor );
  7911. }
  7912. getBindings() {
  7913. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  7914. }
  7915. getIndex() {
  7916. return this._geometries.getIndex( this );
  7917. }
  7918. getIndirect() {
  7919. return this._geometries.getIndirect( this );
  7920. }
  7921. getChainArray() {
  7922. return [ this.object, this.material, this.context, this.lightsNode ];
  7923. }
  7924. setGeometry( geometry ) {
  7925. this.geometry = geometry;
  7926. this.attributes = null;
  7927. }
  7928. getAttributes() {
  7929. if ( this.attributes !== null ) return this.attributes;
  7930. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  7931. const geometry = this.geometry;
  7932. const attributes = [];
  7933. const vertexBuffers = new Set();
  7934. for ( const nodeAttribute of nodeAttributes ) {
  7935. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  7936. if ( attribute === undefined ) continue;
  7937. attributes.push( attribute );
  7938. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  7939. vertexBuffers.add( bufferAttribute );
  7940. }
  7941. this.attributes = attributes;
  7942. this.vertexBuffers = Array.from( vertexBuffers.values() );
  7943. return attributes;
  7944. }
  7945. getVertexBuffers() {
  7946. if ( this.vertexBuffers === null ) this.getAttributes();
  7947. return this.vertexBuffers;
  7948. }
  7949. getDrawParameters() {
  7950. const { object, material, geometry, group, drawRange } = this;
  7951. const drawParams = this.drawParams || ( this.drawParams = {
  7952. vertexCount: 0,
  7953. firstVertex: 0,
  7954. instanceCount: 0,
  7955. firstInstance: 0
  7956. } );
  7957. const index = this.getIndex();
  7958. const hasIndex = ( index !== null );
  7959. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  7960. if ( instanceCount === 0 ) return null;
  7961. drawParams.instanceCount = instanceCount;
  7962. if ( object.isBatchedMesh === true ) return drawParams;
  7963. let rangeFactor = 1;
  7964. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  7965. rangeFactor = 2;
  7966. }
  7967. let firstVertex = drawRange.start * rangeFactor;
  7968. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  7969. if ( group !== null ) {
  7970. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  7971. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  7972. }
  7973. const position = geometry.attributes.position;
  7974. let itemCount = Infinity;
  7975. if ( hasIndex ) {
  7976. itemCount = index.count;
  7977. } else if ( position !== undefined && position !== null ) {
  7978. itemCount = position.count;
  7979. }
  7980. firstVertex = Math.max( firstVertex, 0 );
  7981. lastVertex = Math.min( lastVertex, itemCount );
  7982. const count = lastVertex - firstVertex;
  7983. if ( count < 0 || count === Infinity ) return null;
  7984. drawParams.vertexCount = count;
  7985. drawParams.firstVertex = firstVertex;
  7986. return drawParams;
  7987. }
  7988. getGeometryCacheKey() {
  7989. const { geometry } = this;
  7990. let cacheKey = '';
  7991. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  7992. const attribute = geometry.attributes[ name ];
  7993. cacheKey += name + ',';
  7994. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  7995. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  7996. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  7997. if ( attribute.normalized ) cacheKey += 'n,';
  7998. }
  7999. if ( geometry.index ) {
  8000. cacheKey += 'index,';
  8001. }
  8002. return cacheKey;
  8003. }
  8004. getMaterialCacheKey() {
  8005. const { object, material } = this;
  8006. let cacheKey = material.customProgramCacheKey();
  8007. for ( const property of getKeys( material ) ) {
  8008. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  8009. const value = material[ property ];
  8010. let valueKey;
  8011. if ( value !== null ) {
  8012. // some material values require a formatting
  8013. const type = typeof value;
  8014. if ( type === 'number' ) {
  8015. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  8016. } else if ( type === 'object' ) {
  8017. valueKey = '{';
  8018. if ( value.isTexture ) {
  8019. valueKey += value.mapping;
  8020. }
  8021. valueKey += '}';
  8022. } else {
  8023. valueKey = String( value );
  8024. }
  8025. } else {
  8026. valueKey = String( value );
  8027. }
  8028. cacheKey += /*property + ':' +*/ valueKey + ',';
  8029. }
  8030. cacheKey += this.clippingContextCacheKey + ',';
  8031. if ( object.geometry ) {
  8032. cacheKey += this.getGeometryCacheKey();
  8033. }
  8034. if ( object.skeleton ) {
  8035. cacheKey += object.skeleton.bones.length + ',';
  8036. }
  8037. if ( object.morphTargetInfluences ) {
  8038. cacheKey += object.morphTargetInfluences.length + ',';
  8039. }
  8040. if ( object.isBatchedMesh ) {
  8041. cacheKey += object._matricesTexture.uuid + ',';
  8042. if ( object._colorsTexture !== null ) {
  8043. cacheKey += object._colorsTexture.uuid + ',';
  8044. }
  8045. }
  8046. if ( object.count > 1 ) {
  8047. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  8048. cacheKey += object.uuid + ',';
  8049. }
  8050. return hashString( cacheKey );
  8051. }
  8052. get needsGeometryUpdate() {
  8053. return this.geometry.id !== this.object.geometry.id;
  8054. }
  8055. get needsUpdate() {
  8056. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  8057. }
  8058. getDynamicCacheKey() {
  8059. // Environment Nodes Cache Key
  8060. let cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  8061. if ( this.object.receiveShadow ) {
  8062. cacheKey += 1;
  8063. }
  8064. return cacheKey;
  8065. }
  8066. getCacheKey() {
  8067. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  8068. }
  8069. dispose() {
  8070. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  8071. this.onDispose();
  8072. }
  8073. }
  8074. const chainArray = [];
  8075. class RenderObjects {
  8076. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  8077. this.renderer = renderer;
  8078. this.nodes = nodes;
  8079. this.geometries = geometries;
  8080. this.pipelines = pipelines;
  8081. this.bindings = bindings;
  8082. this.info = info;
  8083. this.chainMaps = {};
  8084. }
  8085. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  8086. const chainMap = this.getChainMap( passId );
  8087. // reuse chainArray
  8088. chainArray[ 0 ] = object;
  8089. chainArray[ 1 ] = material;
  8090. chainArray[ 2 ] = renderContext;
  8091. chainArray[ 3 ] = lightsNode;
  8092. let renderObject = chainMap.get( chainArray );
  8093. if ( renderObject === undefined ) {
  8094. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  8095. chainMap.set( chainArray, renderObject );
  8096. } else {
  8097. renderObject.updateClipping( clippingContext );
  8098. if ( renderObject.needsGeometryUpdate ) {
  8099. renderObject.setGeometry( object.geometry );
  8100. }
  8101. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  8102. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  8103. renderObject.dispose();
  8104. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  8105. } else {
  8106. renderObject.version = material.version;
  8107. }
  8108. }
  8109. }
  8110. return renderObject;
  8111. }
  8112. getChainMap( passId = 'default' ) {
  8113. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  8114. }
  8115. dispose() {
  8116. this.chainMaps = {};
  8117. }
  8118. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  8119. const chainMap = this.getChainMap( passId );
  8120. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  8121. renderObject.onDispose = () => {
  8122. this.pipelines.delete( renderObject );
  8123. this.bindings.delete( renderObject );
  8124. this.nodes.delete( renderObject );
  8125. chainMap.delete( renderObject.getChainArray() );
  8126. };
  8127. return renderObject;
  8128. }
  8129. }
  8130. class DataMap {
  8131. constructor() {
  8132. this.data = new WeakMap();
  8133. }
  8134. get( object ) {
  8135. let map = this.data.get( object );
  8136. if ( map === undefined ) {
  8137. map = {};
  8138. this.data.set( object, map );
  8139. }
  8140. return map;
  8141. }
  8142. delete( object ) {
  8143. let map;
  8144. if ( this.data.has( object ) ) {
  8145. map = this.data.get( object );
  8146. this.data.delete( object );
  8147. }
  8148. return map;
  8149. }
  8150. has( object ) {
  8151. return this.data.has( object );
  8152. }
  8153. dispose() {
  8154. this.data = new WeakMap();
  8155. }
  8156. }
  8157. const AttributeType = {
  8158. VERTEX: 1,
  8159. INDEX: 2,
  8160. STORAGE: 3,
  8161. INDIRECT: 4
  8162. };
  8163. // size of a chunk in bytes (STD140 layout)
  8164. const GPU_CHUNK_BYTES = 16;
  8165. // @TODO: Move to src/constants.js
  8166. const BlendColorFactor = 211;
  8167. const OneMinusBlendColorFactor = 212;
  8168. class Attributes extends DataMap {
  8169. constructor( backend ) {
  8170. super();
  8171. this.backend = backend;
  8172. }
  8173. delete( attribute ) {
  8174. const attributeData = super.delete( attribute );
  8175. if ( attributeData !== undefined ) {
  8176. this.backend.destroyAttribute( attribute );
  8177. }
  8178. return attributeData;
  8179. }
  8180. update( attribute, type ) {
  8181. const data = this.get( attribute );
  8182. if ( data.version === undefined ) {
  8183. if ( type === AttributeType.VERTEX ) {
  8184. this.backend.createAttribute( attribute );
  8185. } else if ( type === AttributeType.INDEX ) {
  8186. this.backend.createIndexAttribute( attribute );
  8187. } else if ( type === AttributeType.STORAGE ) {
  8188. this.backend.createStorageAttribute( attribute );
  8189. } else if ( type === AttributeType.INDIRECT ) {
  8190. this.backend.createIndirectStorageAttribute( attribute );
  8191. }
  8192. data.version = this._getBufferAttribute( attribute ).version;
  8193. } else {
  8194. const bufferAttribute = this._getBufferAttribute( attribute );
  8195. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  8196. this.backend.updateAttribute( attribute );
  8197. data.version = bufferAttribute.version;
  8198. }
  8199. }
  8200. }
  8201. _getBufferAttribute( attribute ) {
  8202. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8203. return attribute;
  8204. }
  8205. }
  8206. function arrayNeedsUint32( array ) {
  8207. // assumes larger values usually on last
  8208. for ( let i = array.length - 1; i >= 0; -- i ) {
  8209. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  8210. }
  8211. return false;
  8212. }
  8213. function getWireframeVersion( geometry ) {
  8214. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  8215. }
  8216. function getWireframeIndex( geometry ) {
  8217. const indices = [];
  8218. const geometryIndex = geometry.index;
  8219. const geometryPosition = geometry.attributes.position;
  8220. if ( geometryIndex !== null ) {
  8221. const array = geometryIndex.array;
  8222. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  8223. const a = array[ i + 0 ];
  8224. const b = array[ i + 1 ];
  8225. const c = array[ i + 2 ];
  8226. indices.push( a, b, b, c, c, a );
  8227. }
  8228. } else {
  8229. const array = geometryPosition.array;
  8230. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  8231. const a = i + 0;
  8232. const b = i + 1;
  8233. const c = i + 2;
  8234. indices.push( a, b, b, c, c, a );
  8235. }
  8236. }
  8237. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  8238. attribute.version = getWireframeVersion( geometry );
  8239. return attribute;
  8240. }
  8241. class Geometries extends DataMap {
  8242. constructor( attributes, info ) {
  8243. super();
  8244. this.attributes = attributes;
  8245. this.info = info;
  8246. this.wireframes = new WeakMap();
  8247. this.attributeCall = new WeakMap();
  8248. }
  8249. has( renderObject ) {
  8250. const geometry = renderObject.geometry;
  8251. return super.has( geometry ) && this.get( geometry ).initialized === true;
  8252. }
  8253. updateForRender( renderObject ) {
  8254. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  8255. this.updateAttributes( renderObject );
  8256. }
  8257. initGeometry( renderObject ) {
  8258. const geometry = renderObject.geometry;
  8259. const geometryData = this.get( geometry );
  8260. geometryData.initialized = true;
  8261. this.info.memory.geometries ++;
  8262. const onDispose = () => {
  8263. this.info.memory.geometries --;
  8264. const index = geometry.index;
  8265. const geometryAttributes = renderObject.getAttributes();
  8266. if ( index !== null ) {
  8267. this.attributes.delete( index );
  8268. }
  8269. for ( const geometryAttribute of geometryAttributes ) {
  8270. this.attributes.delete( geometryAttribute );
  8271. }
  8272. const wireframeAttribute = this.wireframes.get( geometry );
  8273. if ( wireframeAttribute !== undefined ) {
  8274. this.attributes.delete( wireframeAttribute );
  8275. }
  8276. geometry.removeEventListener( 'dispose', onDispose );
  8277. };
  8278. geometry.addEventListener( 'dispose', onDispose );
  8279. }
  8280. updateAttributes( renderObject ) {
  8281. // attributes
  8282. const attributes = renderObject.getAttributes();
  8283. for ( const attribute of attributes ) {
  8284. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  8285. this.updateAttribute( attribute, AttributeType.STORAGE );
  8286. } else {
  8287. this.updateAttribute( attribute, AttributeType.VERTEX );
  8288. }
  8289. }
  8290. // indexes
  8291. const index = this.getIndex( renderObject );
  8292. if ( index !== null ) {
  8293. this.updateAttribute( index, AttributeType.INDEX );
  8294. }
  8295. // indirect
  8296. const indirect = renderObject.geometry.indirect;
  8297. if ( indirect !== null ) {
  8298. this.updateAttribute( indirect, AttributeType.INDIRECT );
  8299. }
  8300. }
  8301. updateAttribute( attribute, type ) {
  8302. const callId = this.info.render.calls;
  8303. if ( ! attribute.isInterleavedBufferAttribute ) {
  8304. if ( this.attributeCall.get( attribute ) !== callId ) {
  8305. this.attributes.update( attribute, type );
  8306. this.attributeCall.set( attribute, callId );
  8307. }
  8308. } else {
  8309. if ( this.attributeCall.get( attribute ) === undefined ) {
  8310. this.attributes.update( attribute, type );
  8311. this.attributeCall.set( attribute, callId );
  8312. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  8313. this.attributes.update( attribute, type );
  8314. this.attributeCall.set( attribute.data, callId );
  8315. this.attributeCall.set( attribute, callId );
  8316. }
  8317. }
  8318. }
  8319. getIndirect( renderObject ) {
  8320. return renderObject.geometry.indirect;
  8321. }
  8322. getIndex( renderObject ) {
  8323. const { geometry, material } = renderObject;
  8324. let index = geometry.index;
  8325. if ( material.wireframe === true ) {
  8326. const wireframes = this.wireframes;
  8327. let wireframeAttribute = wireframes.get( geometry );
  8328. if ( wireframeAttribute === undefined ) {
  8329. wireframeAttribute = getWireframeIndex( geometry );
  8330. wireframes.set( geometry, wireframeAttribute );
  8331. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  8332. this.attributes.delete( wireframeAttribute );
  8333. wireframeAttribute = getWireframeIndex( geometry );
  8334. wireframes.set( geometry, wireframeAttribute );
  8335. }
  8336. index = wireframeAttribute;
  8337. }
  8338. return index;
  8339. }
  8340. }
  8341. class Info {
  8342. constructor() {
  8343. this.autoReset = true;
  8344. this.frame = 0;
  8345. this.calls = 0;
  8346. this.render = {
  8347. calls: 0,
  8348. frameCalls: 0,
  8349. drawCalls: 0,
  8350. triangles: 0,
  8351. points: 0,
  8352. lines: 0,
  8353. timestamp: 0,
  8354. previousFrameCalls: 0,
  8355. timestampCalls: 0
  8356. };
  8357. this.compute = {
  8358. calls: 0,
  8359. frameCalls: 0,
  8360. timestamp: 0,
  8361. previousFrameCalls: 0,
  8362. timestampCalls: 0
  8363. };
  8364. this.memory = {
  8365. geometries: 0,
  8366. textures: 0
  8367. };
  8368. }
  8369. update( object, count, instanceCount ) {
  8370. this.render.drawCalls ++;
  8371. if ( object.isMesh || object.isSprite ) {
  8372. this.render.triangles += instanceCount * ( count / 3 );
  8373. } else if ( object.isPoints ) {
  8374. this.render.points += instanceCount * count;
  8375. } else if ( object.isLineSegments ) {
  8376. this.render.lines += instanceCount * ( count / 2 );
  8377. } else if ( object.isLine ) {
  8378. this.render.lines += instanceCount * ( count - 1 );
  8379. } else {
  8380. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  8381. }
  8382. }
  8383. updateTimestamp( type, time ) {
  8384. if ( this[ type ].timestampCalls === 0 ) {
  8385. this[ type ].timestamp = 0;
  8386. }
  8387. this[ type ].timestamp += time;
  8388. this[ type ].timestampCalls ++;
  8389. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  8390. this[ type ].timestampCalls = 0;
  8391. }
  8392. }
  8393. reset() {
  8394. const previousRenderFrameCalls = this.render.frameCalls;
  8395. this.render.previousFrameCalls = previousRenderFrameCalls;
  8396. const previousComputeFrameCalls = this.compute.frameCalls;
  8397. this.compute.previousFrameCalls = previousComputeFrameCalls;
  8398. this.render.drawCalls = 0;
  8399. this.render.frameCalls = 0;
  8400. this.compute.frameCalls = 0;
  8401. this.render.triangles = 0;
  8402. this.render.points = 0;
  8403. this.render.lines = 0;
  8404. }
  8405. dispose() {
  8406. this.reset();
  8407. this.calls = 0;
  8408. this.render.calls = 0;
  8409. this.compute.calls = 0;
  8410. this.render.timestamp = 0;
  8411. this.compute.timestamp = 0;
  8412. this.memory.geometries = 0;
  8413. this.memory.textures = 0;
  8414. }
  8415. }
  8416. class Pipeline {
  8417. constructor( cacheKey ) {
  8418. this.cacheKey = cacheKey;
  8419. this.usedTimes = 0;
  8420. }
  8421. }
  8422. class RenderPipeline extends Pipeline {
  8423. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  8424. super( cacheKey );
  8425. this.vertexProgram = vertexProgram;
  8426. this.fragmentProgram = fragmentProgram;
  8427. }
  8428. }
  8429. class ComputePipeline extends Pipeline {
  8430. constructor( cacheKey, computeProgram ) {
  8431. super( cacheKey );
  8432. this.computeProgram = computeProgram;
  8433. this.isComputePipeline = true;
  8434. }
  8435. }
  8436. let _id$6 = 0;
  8437. class ProgrammableStage {
  8438. constructor( code, type, transforms = null, attributes = null ) {
  8439. this.id = _id$6 ++;
  8440. this.code = code;
  8441. this.stage = type;
  8442. this.transforms = transforms;
  8443. this.attributes = attributes;
  8444. this.usedTimes = 0;
  8445. }
  8446. }
  8447. class Pipelines extends DataMap {
  8448. constructor( backend, nodes ) {
  8449. super();
  8450. this.backend = backend;
  8451. this.nodes = nodes;
  8452. this.bindings = null; // set by the bindings
  8453. this.caches = new Map();
  8454. this.programs = {
  8455. vertex: new Map(),
  8456. fragment: new Map(),
  8457. compute: new Map()
  8458. };
  8459. }
  8460. getForCompute( computeNode, bindings ) {
  8461. const { backend } = this;
  8462. const data = this.get( computeNode );
  8463. if ( this._needsComputeUpdate( computeNode ) ) {
  8464. const previousPipeline = data.pipeline;
  8465. if ( previousPipeline ) {
  8466. previousPipeline.usedTimes --;
  8467. previousPipeline.computeProgram.usedTimes --;
  8468. }
  8469. // get shader
  8470. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  8471. // programmable stage
  8472. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  8473. if ( stageCompute === undefined ) {
  8474. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  8475. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  8476. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  8477. backend.createProgram( stageCompute );
  8478. }
  8479. // determine compute pipeline
  8480. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  8481. let pipeline = this.caches.get( cacheKey );
  8482. if ( pipeline === undefined ) {
  8483. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  8484. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  8485. }
  8486. // keep track of all used times
  8487. pipeline.usedTimes ++;
  8488. stageCompute.usedTimes ++;
  8489. //
  8490. data.version = computeNode.version;
  8491. data.pipeline = pipeline;
  8492. }
  8493. return data.pipeline;
  8494. }
  8495. getForRender( renderObject, promises = null ) {
  8496. const { backend } = this;
  8497. const data = this.get( renderObject );
  8498. if ( this._needsRenderUpdate( renderObject ) ) {
  8499. const previousPipeline = data.pipeline;
  8500. if ( previousPipeline ) {
  8501. previousPipeline.usedTimes --;
  8502. previousPipeline.vertexProgram.usedTimes --;
  8503. previousPipeline.fragmentProgram.usedTimes --;
  8504. }
  8505. // get shader
  8506. const nodeBuilderState = renderObject.getNodeBuilderState();
  8507. // programmable stages
  8508. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  8509. if ( stageVertex === undefined ) {
  8510. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  8511. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex' );
  8512. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  8513. backend.createProgram( stageVertex );
  8514. }
  8515. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  8516. if ( stageFragment === undefined ) {
  8517. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  8518. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment' );
  8519. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  8520. backend.createProgram( stageFragment );
  8521. }
  8522. // determine render pipeline
  8523. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  8524. let pipeline = this.caches.get( cacheKey );
  8525. if ( pipeline === undefined ) {
  8526. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  8527. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  8528. } else {
  8529. renderObject.pipeline = pipeline;
  8530. }
  8531. // keep track of all used times
  8532. pipeline.usedTimes ++;
  8533. stageVertex.usedTimes ++;
  8534. stageFragment.usedTimes ++;
  8535. //
  8536. data.pipeline = pipeline;
  8537. }
  8538. return data.pipeline;
  8539. }
  8540. delete( object ) {
  8541. const pipeline = this.get( object ).pipeline;
  8542. if ( pipeline ) {
  8543. // pipeline
  8544. pipeline.usedTimes --;
  8545. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  8546. // programs
  8547. if ( pipeline.isComputePipeline ) {
  8548. pipeline.computeProgram.usedTimes --;
  8549. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  8550. } else {
  8551. pipeline.fragmentProgram.usedTimes --;
  8552. pipeline.vertexProgram.usedTimes --;
  8553. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  8554. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  8555. }
  8556. }
  8557. return super.delete( object );
  8558. }
  8559. dispose() {
  8560. super.dispose();
  8561. this.caches = new Map();
  8562. this.programs = {
  8563. vertex: new Map(),
  8564. fragment: new Map(),
  8565. compute: new Map()
  8566. };
  8567. }
  8568. updateForRender( renderObject ) {
  8569. this.getForRender( renderObject );
  8570. }
  8571. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  8572. // check for existing pipeline
  8573. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  8574. let pipeline = this.caches.get( cacheKey );
  8575. if ( pipeline === undefined ) {
  8576. pipeline = new ComputePipeline( cacheKey, stageCompute );
  8577. this.caches.set( cacheKey, pipeline );
  8578. this.backend.createComputePipeline( pipeline, bindings );
  8579. }
  8580. return pipeline;
  8581. }
  8582. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  8583. // check for existing pipeline
  8584. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  8585. let pipeline = this.caches.get( cacheKey );
  8586. if ( pipeline === undefined ) {
  8587. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  8588. this.caches.set( cacheKey, pipeline );
  8589. renderObject.pipeline = pipeline;
  8590. this.backend.createRenderPipeline( renderObject, promises );
  8591. }
  8592. return pipeline;
  8593. }
  8594. _getComputeCacheKey( computeNode, stageCompute ) {
  8595. return computeNode.id + ',' + stageCompute.id;
  8596. }
  8597. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  8598. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  8599. }
  8600. _releasePipeline( pipeline ) {
  8601. this.caches.delete( pipeline.cacheKey );
  8602. }
  8603. _releaseProgram( program ) {
  8604. const code = program.code;
  8605. const stage = program.stage;
  8606. this.programs[ stage ].delete( code );
  8607. }
  8608. _needsComputeUpdate( computeNode ) {
  8609. const data = this.get( computeNode );
  8610. return data.pipeline === undefined || data.version !== computeNode.version;
  8611. }
  8612. _needsRenderUpdate( renderObject ) {
  8613. const data = this.get( renderObject );
  8614. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  8615. }
  8616. }
  8617. class Bindings extends DataMap {
  8618. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  8619. super();
  8620. this.backend = backend;
  8621. this.textures = textures;
  8622. this.pipelines = pipelines;
  8623. this.attributes = attributes;
  8624. this.nodes = nodes;
  8625. this.info = info;
  8626. this.pipelines.bindings = this; // assign bindings to pipelines
  8627. }
  8628. getForRender( renderObject ) {
  8629. const bindings = renderObject.getBindings();
  8630. for ( const bindGroup of bindings ) {
  8631. const groupData = this.get( bindGroup );
  8632. if ( groupData.bindGroup === undefined ) {
  8633. // each object defines an array of bindings (ubos, textures, samplers etc.)
  8634. this._init( bindGroup );
  8635. this.backend.createBindings( bindGroup, bindings, 0 );
  8636. groupData.bindGroup = bindGroup;
  8637. }
  8638. }
  8639. return bindings;
  8640. }
  8641. getForCompute( computeNode ) {
  8642. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  8643. for ( const bindGroup of bindings ) {
  8644. const groupData = this.get( bindGroup );
  8645. if ( groupData.bindGroup === undefined ) {
  8646. this._init( bindGroup );
  8647. this.backend.createBindings( bindGroup, bindings, 0 );
  8648. groupData.bindGroup = bindGroup;
  8649. }
  8650. }
  8651. return bindings;
  8652. }
  8653. updateForCompute( computeNode ) {
  8654. this._updateBindings( this.getForCompute( computeNode ) );
  8655. }
  8656. updateForRender( renderObject ) {
  8657. this._updateBindings( this.getForRender( renderObject ) );
  8658. }
  8659. _updateBindings( bindings ) {
  8660. for ( const bindGroup of bindings ) {
  8661. this._update( bindGroup, bindings );
  8662. }
  8663. }
  8664. _init( bindGroup ) {
  8665. for ( const binding of bindGroup.bindings ) {
  8666. if ( binding.isSampledTexture ) {
  8667. this.textures.updateTexture( binding.texture );
  8668. } else if ( binding.isStorageBuffer ) {
  8669. const attribute = binding.attribute;
  8670. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  8671. this.attributes.update( attribute, attributeType );
  8672. }
  8673. }
  8674. }
  8675. _update( bindGroup, bindings ) {
  8676. const { backend } = this;
  8677. let needsBindingsUpdate = false;
  8678. let cacheBindings = true;
  8679. let cacheIndex = 0;
  8680. let version = 0;
  8681. // iterate over all bindings and check if buffer updates or a new binding group is required
  8682. for ( const binding of bindGroup.bindings ) {
  8683. if ( binding.isNodeUniformsGroup ) {
  8684. const updated = this.nodes.updateGroup( binding );
  8685. if ( ! updated ) continue;
  8686. }
  8687. if ( binding.isUniformBuffer ) {
  8688. const updated = binding.update();
  8689. if ( updated ) {
  8690. backend.updateBinding( binding );
  8691. }
  8692. } else if ( binding.isSampler ) {
  8693. binding.update();
  8694. } else if ( binding.isSampledTexture ) {
  8695. const texturesTextureData = this.textures.get( binding.texture );
  8696. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  8697. const updated = binding.update();
  8698. const texture = binding.texture;
  8699. if ( updated ) {
  8700. this.textures.updateTexture( texture );
  8701. }
  8702. const textureData = backend.get( texture );
  8703. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  8704. cacheBindings = false;
  8705. } else {
  8706. cacheIndex = cacheIndex * 10 + texture.id;
  8707. version += texture.version;
  8708. }
  8709. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  8710. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  8711. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  8712. this.textures.updateTexture( texture );
  8713. needsBindingsUpdate = true;
  8714. }
  8715. if ( texture.isStorageTexture === true ) {
  8716. const textureData = this.get( texture );
  8717. if ( binding.store === true ) {
  8718. textureData.needsMipmap = true;
  8719. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  8720. this.backend.generateMipmaps( texture );
  8721. textureData.needsMipmap = false;
  8722. }
  8723. }
  8724. }
  8725. }
  8726. if ( needsBindingsUpdate === true ) {
  8727. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  8728. }
  8729. }
  8730. }
  8731. function painterSortStable( a, b ) {
  8732. if ( a.groupOrder !== b.groupOrder ) {
  8733. return a.groupOrder - b.groupOrder;
  8734. } else if ( a.renderOrder !== b.renderOrder ) {
  8735. return a.renderOrder - b.renderOrder;
  8736. } else if ( a.material.id !== b.material.id ) {
  8737. return a.material.id - b.material.id;
  8738. } else if ( a.z !== b.z ) {
  8739. return a.z - b.z;
  8740. } else {
  8741. return a.id - b.id;
  8742. }
  8743. }
  8744. function reversePainterSortStable( a, b ) {
  8745. if ( a.groupOrder !== b.groupOrder ) {
  8746. return a.groupOrder - b.groupOrder;
  8747. } else if ( a.renderOrder !== b.renderOrder ) {
  8748. return a.renderOrder - b.renderOrder;
  8749. } else if ( a.z !== b.z ) {
  8750. return b.z - a.z;
  8751. } else {
  8752. return a.id - b.id;
  8753. }
  8754. }
  8755. function needsDoublePass( material ) {
  8756. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  8757. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  8758. }
  8759. class RenderList {
  8760. constructor( lighting, scene, camera ) {
  8761. this.renderItems = [];
  8762. this.renderItemsIndex = 0;
  8763. this.opaque = [];
  8764. this.transparentDoublePass = [];
  8765. this.transparent = [];
  8766. this.bundles = [];
  8767. this.lightsNode = lighting.getNode( scene, camera );
  8768. this.lightsArray = [];
  8769. this.scene = scene;
  8770. this.camera = camera;
  8771. this.occlusionQueryCount = 0;
  8772. }
  8773. begin() {
  8774. this.renderItemsIndex = 0;
  8775. this.opaque.length = 0;
  8776. this.transparentDoublePass.length = 0;
  8777. this.transparent.length = 0;
  8778. this.bundles.length = 0;
  8779. this.lightsArray.length = 0;
  8780. this.occlusionQueryCount = 0;
  8781. return this;
  8782. }
  8783. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  8784. let renderItem = this.renderItems[ this.renderItemsIndex ];
  8785. if ( renderItem === undefined ) {
  8786. renderItem = {
  8787. id: object.id,
  8788. object: object,
  8789. geometry: geometry,
  8790. material: material,
  8791. groupOrder: groupOrder,
  8792. renderOrder: object.renderOrder,
  8793. z: z,
  8794. group: group,
  8795. clippingContext: clippingContext
  8796. };
  8797. this.renderItems[ this.renderItemsIndex ] = renderItem;
  8798. } else {
  8799. renderItem.id = object.id;
  8800. renderItem.object = object;
  8801. renderItem.geometry = geometry;
  8802. renderItem.material = material;
  8803. renderItem.groupOrder = groupOrder;
  8804. renderItem.renderOrder = object.renderOrder;
  8805. renderItem.z = z;
  8806. renderItem.group = group;
  8807. renderItem.clippingContext = clippingContext;
  8808. }
  8809. this.renderItemsIndex ++;
  8810. return renderItem;
  8811. }
  8812. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  8813. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  8814. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  8815. if ( material.transparent === true || material.transmission > 0 ) {
  8816. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  8817. this.transparent.push( renderItem );
  8818. } else {
  8819. this.opaque.push( renderItem );
  8820. }
  8821. }
  8822. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  8823. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  8824. if ( material.transparent === true || material.transmission > 0 ) {
  8825. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  8826. this.transparent.unshift( renderItem );
  8827. } else {
  8828. this.opaque.unshift( renderItem );
  8829. }
  8830. }
  8831. pushBundle( group ) {
  8832. this.bundles.push( group );
  8833. }
  8834. pushLight( light ) {
  8835. this.lightsArray.push( light );
  8836. }
  8837. sort( customOpaqueSort, customTransparentSort ) {
  8838. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  8839. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  8840. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  8841. }
  8842. finish() {
  8843. // update lights
  8844. this.lightsNode.setLights( this.lightsArray );
  8845. // Clear references from inactive renderItems in the list
  8846. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  8847. const renderItem = this.renderItems[ i ];
  8848. if ( renderItem.id === null ) break;
  8849. renderItem.id = null;
  8850. renderItem.object = null;
  8851. renderItem.geometry = null;
  8852. renderItem.material = null;
  8853. renderItem.groupOrder = null;
  8854. renderItem.renderOrder = null;
  8855. renderItem.z = null;
  8856. renderItem.group = null;
  8857. renderItem.clippingContext = null;
  8858. }
  8859. }
  8860. }
  8861. class RenderLists {
  8862. constructor( lighting ) {
  8863. this.lighting = lighting;
  8864. this.lists = new ChainMap();
  8865. }
  8866. get( scene, camera ) {
  8867. const lists = this.lists;
  8868. const keys = [ scene, camera ];
  8869. let list = lists.get( keys );
  8870. if ( list === undefined ) {
  8871. list = new RenderList( this.lighting, scene, camera );
  8872. lists.set( keys, list );
  8873. }
  8874. return list;
  8875. }
  8876. dispose() {
  8877. this.lists = new ChainMap();
  8878. }
  8879. }
  8880. let id$1 = 0;
  8881. class RenderContext {
  8882. constructor() {
  8883. this.id = id$1 ++;
  8884. this.color = true;
  8885. this.clearColor = true;
  8886. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  8887. this.depth = true;
  8888. this.clearDepth = true;
  8889. this.clearDepthValue = 1;
  8890. this.stencil = false;
  8891. this.clearStencil = true;
  8892. this.clearStencilValue = 1;
  8893. this.viewport = false;
  8894. this.viewportValue = new Vector4();
  8895. this.scissor = false;
  8896. this.scissorValue = new Vector4();
  8897. this.textures = null;
  8898. this.depthTexture = null;
  8899. this.activeCubeFace = 0;
  8900. this.sampleCount = 1;
  8901. this.width = 0;
  8902. this.height = 0;
  8903. this.isRenderContext = true;
  8904. }
  8905. getCacheKey() {
  8906. return getCacheKey( this );
  8907. }
  8908. }
  8909. function getCacheKey( renderContext ) {
  8910. const { textures, activeCubeFace } = renderContext;
  8911. const values = [ activeCubeFace ];
  8912. for ( const texture of textures ) {
  8913. values.push( texture.id );
  8914. }
  8915. return hashArray( values );
  8916. }
  8917. class RenderContexts {
  8918. constructor() {
  8919. this.chainMaps = {};
  8920. }
  8921. get( scene, camera, renderTarget = null ) {
  8922. const chainKey = [ scene, camera ];
  8923. let attachmentState;
  8924. if ( renderTarget === null ) {
  8925. attachmentState = 'default';
  8926. } else {
  8927. const format = renderTarget.texture.format;
  8928. const count = renderTarget.textures.length;
  8929. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  8930. }
  8931. const chainMap = this.getChainMap( attachmentState );
  8932. let renderState = chainMap.get( chainKey );
  8933. if ( renderState === undefined ) {
  8934. renderState = new RenderContext();
  8935. chainMap.set( chainKey, renderState );
  8936. }
  8937. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  8938. return renderState;
  8939. }
  8940. getChainMap( attachmentState ) {
  8941. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  8942. }
  8943. dispose() {
  8944. this.chainMaps = {};
  8945. }
  8946. }
  8947. const _size$3 = /*@__PURE__*/ new Vector3();
  8948. class Textures extends DataMap {
  8949. constructor( renderer, backend, info ) {
  8950. super();
  8951. this.renderer = renderer;
  8952. this.backend = backend;
  8953. this.info = info;
  8954. }
  8955. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  8956. const renderTargetData = this.get( renderTarget );
  8957. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  8958. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  8959. const textures = renderTarget.textures;
  8960. const size = this.getSize( textures[ 0 ] );
  8961. const mipWidth = size.width >> activeMipmapLevel;
  8962. const mipHeight = size.height >> activeMipmapLevel;
  8963. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  8964. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  8965. let textureNeedsUpdate = false;
  8966. if ( depthTexture === undefined && useDepthTexture ) {
  8967. depthTexture = new DepthTexture();
  8968. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  8969. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  8970. depthTexture.image.width = mipWidth;
  8971. depthTexture.image.height = mipHeight;
  8972. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  8973. }
  8974. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  8975. textureNeedsUpdate = true;
  8976. if ( depthTexture ) {
  8977. depthTexture.needsUpdate = true;
  8978. depthTexture.image.width = mipWidth;
  8979. depthTexture.image.height = mipHeight;
  8980. }
  8981. }
  8982. renderTargetData.width = size.width;
  8983. renderTargetData.height = size.height;
  8984. renderTargetData.textures = textures;
  8985. renderTargetData.depthTexture = depthTexture || null;
  8986. renderTargetData.depth = renderTarget.depthBuffer;
  8987. renderTargetData.stencil = renderTarget.stencilBuffer;
  8988. renderTargetData.renderTarget = renderTarget;
  8989. if ( renderTargetData.sampleCount !== sampleCount ) {
  8990. textureNeedsUpdate = true;
  8991. if ( depthTexture ) {
  8992. depthTexture.needsUpdate = true;
  8993. }
  8994. renderTargetData.sampleCount = sampleCount;
  8995. }
  8996. //
  8997. const options = { sampleCount };
  8998. for ( let i = 0; i < textures.length; i ++ ) {
  8999. const texture = textures[ i ];
  9000. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  9001. this.updateTexture( texture, options );
  9002. }
  9003. if ( depthTexture ) {
  9004. this.updateTexture( depthTexture, options );
  9005. }
  9006. // dispose handler
  9007. if ( renderTargetData.initialized !== true ) {
  9008. renderTargetData.initialized = true;
  9009. // dispose
  9010. const onDispose = () => {
  9011. renderTarget.removeEventListener( 'dispose', onDispose );
  9012. for ( let i = 0; i < textures.length; i ++ ) {
  9013. this._destroyTexture( textures[ i ] );
  9014. }
  9015. if ( depthTexture ) {
  9016. this._destroyTexture( depthTexture );
  9017. }
  9018. this.delete( renderTarget );
  9019. };
  9020. renderTarget.addEventListener( 'dispose', onDispose );
  9021. }
  9022. }
  9023. updateTexture( texture, options = {} ) {
  9024. const textureData = this.get( texture );
  9025. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  9026. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  9027. const backend = this.backend;
  9028. if ( isRenderTarget && textureData.initialized === true ) {
  9029. // it's an update
  9030. backend.destroySampler( texture );
  9031. backend.destroyTexture( texture );
  9032. }
  9033. //
  9034. if ( texture.isFramebufferTexture ) {
  9035. const renderTarget = this.renderer.getRenderTarget();
  9036. if ( renderTarget ) {
  9037. texture.type = renderTarget.texture.type;
  9038. } else {
  9039. texture.type = UnsignedByteType;
  9040. }
  9041. }
  9042. //
  9043. const { width, height, depth } = this.getSize( texture );
  9044. options.width = width;
  9045. options.height = height;
  9046. options.depth = depth;
  9047. options.needsMipmaps = this.needsMipmaps( texture );
  9048. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  9049. //
  9050. if ( isRenderTarget || texture.isStorageTexture === true ) {
  9051. backend.createSampler( texture );
  9052. backend.createTexture( texture, options );
  9053. textureData.generation = texture.version;
  9054. } else {
  9055. const needsCreate = textureData.initialized !== true;
  9056. if ( needsCreate ) backend.createSampler( texture );
  9057. if ( texture.version > 0 ) {
  9058. const image = texture.image;
  9059. if ( image === undefined ) {
  9060. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  9061. } else if ( image.complete === false ) {
  9062. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  9063. } else {
  9064. if ( texture.images ) {
  9065. const images = [];
  9066. for ( const image of texture.images ) {
  9067. images.push( image );
  9068. }
  9069. options.images = images;
  9070. } else {
  9071. options.image = image;
  9072. }
  9073. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  9074. backend.createTexture( texture, options );
  9075. textureData.isDefaultTexture = false;
  9076. textureData.generation = texture.version;
  9077. }
  9078. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  9079. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  9080. }
  9081. } else {
  9082. // async update
  9083. backend.createDefaultTexture( texture );
  9084. textureData.isDefaultTexture = true;
  9085. textureData.generation = texture.version;
  9086. }
  9087. }
  9088. // dispose handler
  9089. if ( textureData.initialized !== true ) {
  9090. textureData.initialized = true;
  9091. textureData.generation = texture.version;
  9092. //
  9093. this.info.memory.textures ++;
  9094. // dispose
  9095. const onDispose = () => {
  9096. texture.removeEventListener( 'dispose', onDispose );
  9097. this._destroyTexture( texture );
  9098. this.info.memory.textures --;
  9099. };
  9100. texture.addEventListener( 'dispose', onDispose );
  9101. }
  9102. //
  9103. textureData.version = texture.version;
  9104. }
  9105. getSize( texture, target = _size$3 ) {
  9106. let image = texture.images ? texture.images[ 0 ] : texture.image;
  9107. if ( image ) {
  9108. if ( image.image !== undefined ) image = image.image;
  9109. target.width = image.width || 1;
  9110. target.height = image.height || 1;
  9111. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  9112. } else {
  9113. target.width = target.height = target.depth = 1;
  9114. }
  9115. return target;
  9116. }
  9117. getMipLevels( texture, width, height ) {
  9118. let mipLevelCount;
  9119. if ( texture.isCompressedTexture ) {
  9120. if ( texture.mipmaps ) {
  9121. mipLevelCount = texture.mipmaps.length;
  9122. } else {
  9123. mipLevelCount = 1;
  9124. }
  9125. } else {
  9126. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  9127. }
  9128. return mipLevelCount;
  9129. }
  9130. needsMipmaps( texture ) {
  9131. return this.isEnvironmentTexture( texture ) || texture.isCompressedTexture === true || texture.generateMipmaps;
  9132. }
  9133. isEnvironmentTexture( texture ) {
  9134. const mapping = texture.mapping;
  9135. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  9136. }
  9137. _destroyTexture( texture ) {
  9138. this.backend.destroySampler( texture );
  9139. this.backend.destroyTexture( texture );
  9140. this.delete( texture );
  9141. }
  9142. }
  9143. class Color4 extends Color {
  9144. constructor( r, g, b, a = 1 ) {
  9145. super( r, g, b );
  9146. this.a = a;
  9147. }
  9148. set( r, g, b, a = 1 ) {
  9149. this.a = a;
  9150. return super.set( r, g, b );
  9151. }
  9152. copy( color ) {
  9153. if ( color.a !== undefined ) this.a = color.a;
  9154. return super.copy( color );
  9155. }
  9156. clone() {
  9157. return new this.constructor( this.r, this.g, this.b, this.a );
  9158. }
  9159. }
  9160. class ParameterNode extends PropertyNode {
  9161. static get type() {
  9162. return 'ParameterNode';
  9163. }
  9164. constructor( nodeType, name = null ) {
  9165. super( nodeType, name );
  9166. this.isParameterNode = true;
  9167. }
  9168. getHash() {
  9169. return this.uuid;
  9170. }
  9171. generate() {
  9172. return this.name;
  9173. }
  9174. }
  9175. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  9176. class StackNode extends Node {
  9177. static get type() {
  9178. return 'StackNode';
  9179. }
  9180. constructor( parent = null ) {
  9181. super();
  9182. this.nodes = [];
  9183. this.outputNode = null;
  9184. this.parent = parent;
  9185. this._currentCond = null;
  9186. this.isStackNode = true;
  9187. }
  9188. getNodeType( builder ) {
  9189. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  9190. }
  9191. add( node ) {
  9192. this.nodes.push( node );
  9193. return this;
  9194. }
  9195. If( boolNode, method ) {
  9196. const methodNode = new ShaderNode( method );
  9197. this._currentCond = select( boolNode, methodNode );
  9198. return this.add( this._currentCond );
  9199. }
  9200. ElseIf( boolNode, method ) {
  9201. const methodNode = new ShaderNode( method );
  9202. const ifNode = select( boolNode, methodNode );
  9203. this._currentCond.elseNode = ifNode;
  9204. this._currentCond = ifNode;
  9205. return this;
  9206. }
  9207. Else( method ) {
  9208. this._currentCond.elseNode = new ShaderNode( method );
  9209. return this;
  9210. }
  9211. build( builder, ...params ) {
  9212. const previousStack = getCurrentStack();
  9213. setCurrentStack( this );
  9214. for ( const node of this.nodes ) {
  9215. node.build( builder, 'void' );
  9216. }
  9217. setCurrentStack( previousStack );
  9218. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  9219. }
  9220. //
  9221. else( ...params ) { // @deprecated, r168
  9222. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  9223. return this.Else( ...params );
  9224. }
  9225. elseif( ...params ) { // @deprecated, r168
  9226. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  9227. return this.ElseIf( ...params );
  9228. }
  9229. }
  9230. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  9231. class StructTypeNode extends Node {
  9232. static get type() {
  9233. return 'StructTypeNode';
  9234. }
  9235. constructor( types ) {
  9236. super();
  9237. this.types = types;
  9238. this.isStructTypeNode = true;
  9239. }
  9240. getMemberTypes() {
  9241. return this.types;
  9242. }
  9243. }
  9244. class OutputStructNode extends Node {
  9245. static get type() {
  9246. return 'OutputStructNode';
  9247. }
  9248. constructor( ...members ) {
  9249. super();
  9250. this.members = members;
  9251. this.isOutputStructNode = true;
  9252. }
  9253. setup( builder ) {
  9254. super.setup( builder );
  9255. const members = this.members;
  9256. const types = [];
  9257. for ( let i = 0; i < members.length; i ++ ) {
  9258. types.push( members[ i ].getNodeType( builder ) );
  9259. }
  9260. this.nodeType = builder.getStructTypeFromNode( new StructTypeNode( types ) ).name;
  9261. }
  9262. generate( builder, output ) {
  9263. const propertyName = builder.getOutputStructName();
  9264. const members = this.members;
  9265. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  9266. for ( let i = 0; i < members.length; i ++ ) {
  9267. const snippet = members[ i ].build( builder, output );
  9268. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  9269. }
  9270. return propertyName;
  9271. }
  9272. }
  9273. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  9274. function getTextureIndex( textures, name ) {
  9275. for ( let i = 0; i < textures.length; i ++ ) {
  9276. if ( textures[ i ].name === name ) {
  9277. return i;
  9278. }
  9279. }
  9280. return - 1;
  9281. }
  9282. class MRTNode extends OutputStructNode {
  9283. static get type() {
  9284. return 'MRTNode';
  9285. }
  9286. constructor( outputNodes ) {
  9287. super();
  9288. this.outputNodes = outputNodes;
  9289. this.isMRTNode = true;
  9290. }
  9291. has( name ) {
  9292. return this.outputNodes[ name ] !== undefined;
  9293. }
  9294. get( name ) {
  9295. return this.outputNodes[ name ];
  9296. }
  9297. merge( mrtNode ) {
  9298. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  9299. return mrt( outputs );
  9300. }
  9301. setup( builder ) {
  9302. const outputNodes = this.outputNodes;
  9303. const mrt = builder.renderer.getRenderTarget();
  9304. const members = [];
  9305. const textures = mrt.textures;
  9306. for ( const name in outputNodes ) {
  9307. const index = getTextureIndex( textures, name );
  9308. members[ index ] = vec4( outputNodes[ name ] );
  9309. }
  9310. this.members = members;
  9311. return super.setup( builder );
  9312. }
  9313. }
  9314. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  9315. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  9316. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  9317. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  9318. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  9319. const result = word.shiftRight( 22 ).bitXor( word );
  9320. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  9321. } );
  9322. // remapping functions https://iquilezles.org/articles/functions/
  9323. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  9324. 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 ) );
  9325. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  9326. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  9327. // https://github.com/cabbibo/glsl-tri-noise-3d
  9328. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  9329. return x.fract().sub( .5 ).abs();
  9330. } ).setLayout( {
  9331. name: 'tri',
  9332. type: 'float',
  9333. inputs: [
  9334. { name: 'x', type: 'float' }
  9335. ]
  9336. } );
  9337. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  9338. 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. ) ) ) ) );
  9339. } ).setLayout( {
  9340. name: 'tri3',
  9341. type: 'vec3',
  9342. inputs: [
  9343. { name: 'p', type: 'vec3' }
  9344. ]
  9345. } );
  9346. const triNoise3D = /*@__PURE__*/ Fn( ( [ p_immutable, spd, time ] ) => {
  9347. const p = vec3( p_immutable ).toVar();
  9348. const z = float( 1.4 ).toVar();
  9349. const rz = float( 0.0 ).toVar();
  9350. const bp = vec3( p ).toVar();
  9351. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  9352. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  9353. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) );
  9354. bp.mulAssign( 1.8 );
  9355. z.mulAssign( 1.5 );
  9356. p.mulAssign( 1.2 );
  9357. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  9358. rz.addAssign( t.div( z ) );
  9359. bp.addAssign( 0.14 );
  9360. } );
  9361. return rz;
  9362. } ).setLayout( {
  9363. name: 'triNoise3D',
  9364. type: 'float',
  9365. inputs: [
  9366. { name: 'p', type: 'vec3' },
  9367. { name: 'spd', type: 'float' },
  9368. { name: 'time', type: 'float' }
  9369. ]
  9370. } );
  9371. class FunctionOverloadingNode extends Node {
  9372. static get type() {
  9373. return 'FunctionOverloadingNode';
  9374. }
  9375. constructor( functionNodes = [], ...parametersNodes ) {
  9376. super();
  9377. this.functionNodes = functionNodes;
  9378. this.parametersNodes = parametersNodes;
  9379. this._candidateFnCall = null;
  9380. this.global = true;
  9381. }
  9382. getNodeType() {
  9383. return this.functionNodes[ 0 ].shaderNode.layout.type;
  9384. }
  9385. setup( builder ) {
  9386. const params = this.parametersNodes;
  9387. let candidateFnCall = this._candidateFnCall;
  9388. if ( candidateFnCall === null ) {
  9389. let candidateFn = null;
  9390. let candidateScore = - 1;
  9391. for ( const functionNode of this.functionNodes ) {
  9392. const shaderNode = functionNode.shaderNode;
  9393. const layout = shaderNode.layout;
  9394. if ( layout === null ) {
  9395. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  9396. }
  9397. const inputs = layout.inputs;
  9398. if ( params.length === inputs.length ) {
  9399. let score = 0;
  9400. for ( let i = 0; i < params.length; i ++ ) {
  9401. const param = params[ i ];
  9402. const input = inputs[ i ];
  9403. if ( param.getNodeType( builder ) === input.type ) {
  9404. score ++;
  9405. } else {
  9406. score = 0;
  9407. }
  9408. }
  9409. if ( score > candidateScore ) {
  9410. candidateFn = functionNode;
  9411. candidateScore = score;
  9412. }
  9413. }
  9414. }
  9415. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  9416. }
  9417. return candidateFnCall;
  9418. }
  9419. }
  9420. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  9421. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  9422. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  9423. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  9424. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  9425. // Deprecated
  9426. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  9427. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  9428. return time.mul( timeScale );
  9429. };
  9430. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  9431. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  9432. return time.mul( timeScale );
  9433. };
  9434. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  9435. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  9436. return deltaTime.mul( timeScale );
  9437. };
  9438. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  9439. const oscSquare = ( t = time ) => t.fract().round();
  9440. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  9441. const oscSawtooth = ( t = time ) => t.fract();
  9442. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  9443. return rotate( uv.sub( center ), rotation ).add( center );
  9444. } );
  9445. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  9446. const delta = uv.sub( center );
  9447. const delta2 = delta.dot( delta );
  9448. const delta4 = delta2.mul( delta2 );
  9449. const deltaOffset = delta4.mul( strength );
  9450. return uv.add( delta.mul( deltaOffset ) );
  9451. } );
  9452. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  9453. let worldMatrix;
  9454. if ( position !== null ) {
  9455. worldMatrix = modelWorldMatrix.toVar();
  9456. worldMatrix[ 3 ][ 0 ] = position.x;
  9457. worldMatrix[ 3 ][ 1 ] = position.y;
  9458. worldMatrix[ 3 ][ 2 ] = position.z;
  9459. } else {
  9460. worldMatrix = modelWorldMatrix;
  9461. }
  9462. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  9463. if ( defined( horizontal ) ) {
  9464. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  9465. modelViewMatrix[ 0 ][ 1 ] = 0;
  9466. modelViewMatrix[ 0 ][ 2 ] = 0;
  9467. }
  9468. if ( defined( vertical ) ) {
  9469. modelViewMatrix[ 1 ][ 0 ] = 0;
  9470. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  9471. modelViewMatrix[ 1 ][ 2 ] = 0;
  9472. }
  9473. modelViewMatrix[ 2 ][ 0 ] = 0;
  9474. modelViewMatrix[ 2 ][ 1 ] = 0;
  9475. modelViewMatrix[ 2 ][ 2 ] = 1;
  9476. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  9477. } );
  9478. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  9479. const depth = linearDepth();
  9480. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  9481. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  9482. return finalUV;
  9483. } );
  9484. class SpriteSheetUVNode extends Node {
  9485. static get type() {
  9486. return 'SpriteSheetUVNode';
  9487. }
  9488. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  9489. super( 'vec2' );
  9490. this.countNode = countNode;
  9491. this.uvNode = uvNode;
  9492. this.frameNode = frameNode;
  9493. }
  9494. setup() {
  9495. const { frameNode, uvNode, countNode } = this;
  9496. const { width, height } = countNode;
  9497. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  9498. const column = frameNum.mod( width );
  9499. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  9500. const scale = countNode.reciprocal();
  9501. const uvFrameOffset = vec2( column, row );
  9502. return uvNode.add( uvFrameOffset ).mul( scale );
  9503. }
  9504. }
  9505. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  9506. class TriplanarTexturesNode extends Node {
  9507. static get type() {
  9508. return 'TriplanarTexturesNode';
  9509. }
  9510. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  9511. super( 'vec4' );
  9512. this.textureXNode = textureXNode;
  9513. this.textureYNode = textureYNode;
  9514. this.textureZNode = textureZNode;
  9515. this.scaleNode = scaleNode;
  9516. this.positionNode = positionNode;
  9517. this.normalNode = normalNode;
  9518. }
  9519. setup() {
  9520. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  9521. // Ref: https://github.com/keijiro/StandardTriplanar
  9522. // Blending factor of triplanar mapping
  9523. let bf = normalNode.abs().normalize();
  9524. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  9525. // Triplanar mapping
  9526. const tx = positionNode.yz.mul( scaleNode );
  9527. const ty = positionNode.zx.mul( scaleNode );
  9528. const tz = positionNode.xy.mul( scaleNode );
  9529. // Base color
  9530. const textureX = textureXNode.value;
  9531. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  9532. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  9533. const cx = texture( textureX, tx ).mul( bf.x );
  9534. const cy = texture( textureY, ty ).mul( bf.y );
  9535. const cz = texture( textureZ, tz ).mul( bf.z );
  9536. return add( cx, cy, cz );
  9537. }
  9538. }
  9539. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  9540. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  9541. const _reflectorPlane = new Plane();
  9542. const _normal = new Vector3();
  9543. const _reflectorWorldPosition = new Vector3();
  9544. const _cameraWorldPosition = new Vector3();
  9545. const _rotationMatrix = new Matrix4();
  9546. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  9547. const clipPlane = new Vector4();
  9548. const _view = new Vector3();
  9549. const _target = new Vector3();
  9550. const _q = new Vector4();
  9551. const _size$2 = new Vector2();
  9552. const _defaultRT = new RenderTarget();
  9553. const _defaultUV = screenUV.flipX();
  9554. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  9555. let _inReflector = false;
  9556. class ReflectorNode extends TextureNode {
  9557. static get type() {
  9558. return 'ReflectorNode';
  9559. }
  9560. constructor( parameters = {} ) {
  9561. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  9562. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  9563. this._depthNode = null;
  9564. this.setUpdateMatrix( false );
  9565. }
  9566. get reflector() {
  9567. return this._reflectorBaseNode;
  9568. }
  9569. get target() {
  9570. return this._reflectorBaseNode.target;
  9571. }
  9572. getDepthNode() {
  9573. if ( this._depthNode === null ) {
  9574. if ( this._reflectorBaseNode.depth !== true ) {
  9575. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  9576. }
  9577. this._depthNode = nodeObject( new ReflectorNode( {
  9578. defaultTexture: _defaultRT.depthTexture,
  9579. reflector: this._reflectorBaseNode
  9580. } ) );
  9581. }
  9582. return this._depthNode;
  9583. }
  9584. setup( builder ) {
  9585. // ignore if used in post-processing
  9586. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  9587. return super.setup( builder );
  9588. }
  9589. clone() {
  9590. const texture = new this.constructor( this.reflectorNode );
  9591. texture._reflectorBaseNode = this._reflectorBaseNode;
  9592. return texture;
  9593. }
  9594. }
  9595. class ReflectorBaseNode extends Node {
  9596. static get type() {
  9597. return 'ReflectorBaseNode';
  9598. }
  9599. constructor( textureNode, parameters = {} ) {
  9600. super();
  9601. const {
  9602. target = new Object3D(),
  9603. resolution = 1,
  9604. generateMipmaps = false,
  9605. bounces = true,
  9606. depth = false
  9607. } = parameters;
  9608. //
  9609. this.textureNode = textureNode;
  9610. this.target = target;
  9611. this.resolution = resolution;
  9612. this.generateMipmaps = generateMipmaps;
  9613. this.bounces = bounces;
  9614. this.depth = depth;
  9615. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  9616. this.virtualCameras = new WeakMap();
  9617. this.renderTargets = new WeakMap();
  9618. }
  9619. _updateResolution( renderTarget, renderer ) {
  9620. const resolution = this.resolution;
  9621. renderer.getDrawingBufferSize( _size$2 );
  9622. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  9623. }
  9624. setup( builder ) {
  9625. this._updateResolution( _defaultRT, builder.renderer );
  9626. return super.setup( builder );
  9627. }
  9628. getVirtualCamera( camera ) {
  9629. let virtualCamera = this.virtualCameras.get( camera );
  9630. if ( virtualCamera === undefined ) {
  9631. virtualCamera = camera.clone();
  9632. this.virtualCameras.set( camera, virtualCamera );
  9633. }
  9634. return virtualCamera;
  9635. }
  9636. getRenderTarget( camera ) {
  9637. let renderTarget = this.renderTargets.get( camera );
  9638. if ( renderTarget === undefined ) {
  9639. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  9640. if ( this.generateMipmaps === true ) {
  9641. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  9642. renderTarget.texture.generateMipmaps = true;
  9643. }
  9644. if ( this.depth === true ) {
  9645. renderTarget.depthTexture = new DepthTexture();
  9646. }
  9647. this.renderTargets.set( camera, renderTarget );
  9648. }
  9649. return renderTarget;
  9650. }
  9651. updateBefore( frame ) {
  9652. if ( this.bounces === false && _inReflector ) return;
  9653. _inReflector = true;
  9654. const { scene, camera, renderer, material } = frame;
  9655. const { target } = this;
  9656. const virtualCamera = this.getVirtualCamera( camera );
  9657. const renderTarget = this.getRenderTarget( virtualCamera );
  9658. renderer.getDrawingBufferSize( _size$2 );
  9659. this._updateResolution( renderTarget, renderer );
  9660. //
  9661. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  9662. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  9663. _rotationMatrix.extractRotation( target.matrixWorld );
  9664. _normal.set( 0, 0, 1 );
  9665. _normal.applyMatrix4( _rotationMatrix );
  9666. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  9667. // Avoid rendering when reflector is facing away
  9668. if ( _view.dot( _normal ) > 0 ) return;
  9669. _view.reflect( _normal ).negate();
  9670. _view.add( _reflectorWorldPosition );
  9671. _rotationMatrix.extractRotation( camera.matrixWorld );
  9672. _lookAtPosition.set( 0, 0, - 1 );
  9673. _lookAtPosition.applyMatrix4( _rotationMatrix );
  9674. _lookAtPosition.add( _cameraWorldPosition );
  9675. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  9676. _target.reflect( _normal ).negate();
  9677. _target.add( _reflectorWorldPosition );
  9678. //
  9679. virtualCamera.coordinateSystem = camera.coordinateSystem;
  9680. virtualCamera.position.copy( _view );
  9681. virtualCamera.up.set( 0, 1, 0 );
  9682. virtualCamera.up.applyMatrix4( _rotationMatrix );
  9683. virtualCamera.up.reflect( _normal );
  9684. virtualCamera.lookAt( _target );
  9685. virtualCamera.near = camera.near;
  9686. virtualCamera.far = camera.far;
  9687. virtualCamera.updateMatrixWorld();
  9688. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  9689. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  9690. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  9691. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  9692. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  9693. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  9694. const projectionMatrix = virtualCamera.projectionMatrix;
  9695. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  9696. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  9697. _q.z = - 1.0;
  9698. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  9699. // Calculate the scaled plane vector
  9700. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  9701. const clipBias = 0;
  9702. // Replacing the third row of the projection matrix
  9703. projectionMatrix.elements[ 2 ] = clipPlane.x;
  9704. projectionMatrix.elements[ 6 ] = clipPlane.y;
  9705. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  9706. projectionMatrix.elements[ 14 ] = clipPlane.w;
  9707. //
  9708. this.textureNode.value = renderTarget.texture;
  9709. if ( this.depth === true ) {
  9710. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  9711. }
  9712. material.visible = false;
  9713. const currentRenderTarget = renderer.getRenderTarget();
  9714. const currentMRT = renderer.getMRT();
  9715. renderer.setMRT( null );
  9716. renderer.setRenderTarget( renderTarget );
  9717. renderer.render( scene, virtualCamera );
  9718. renderer.setMRT( currentMRT );
  9719. renderer.setRenderTarget( currentRenderTarget );
  9720. material.visible = true;
  9721. _inReflector = false;
  9722. }
  9723. }
  9724. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  9725. // Helper for passes that need to fill the viewport with a single quad.
  9726. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  9727. // https://github.com/mrdoob/three.js/pull/21358
  9728. class QuadGeometry extends BufferGeometry {
  9729. constructor( flipY = false ) {
  9730. super();
  9731. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  9732. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  9733. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  9734. }
  9735. }
  9736. const _geometry = /*@__PURE__*/ new QuadGeometry();
  9737. class QuadMesh extends Mesh {
  9738. constructor( material = null ) {
  9739. super( _geometry, material );
  9740. this.camera = _camera;
  9741. this.isQuadMesh = true;
  9742. }
  9743. renderAsync( renderer ) {
  9744. return renderer.renderAsync( this, _camera );
  9745. }
  9746. render( renderer ) {
  9747. renderer.render( this, _camera );
  9748. }
  9749. }
  9750. const _size$1 = /*@__PURE__*/ new Vector2();
  9751. class RTTNode extends TextureNode {
  9752. static get type() {
  9753. return 'RTTNode';
  9754. }
  9755. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  9756. const renderTarget = new RenderTarget( width, height, options );
  9757. super( renderTarget.texture, uv() );
  9758. this.node = node;
  9759. this.width = width;
  9760. this.height = height;
  9761. this.renderTarget = renderTarget;
  9762. this.textureNeedsUpdate = true;
  9763. this.autoUpdate = true;
  9764. this.updateMap = new WeakMap();
  9765. this._rttNode = null;
  9766. this._quadMesh = new QuadMesh( new NodeMaterial() );
  9767. this.updateBeforeType = NodeUpdateType.RENDER;
  9768. }
  9769. get autoSize() {
  9770. return this.width === null;
  9771. }
  9772. setup( builder ) {
  9773. this._rttNode = this.node.context( builder.getSharedContext() );
  9774. this._quadMesh.material.name = 'RTT';
  9775. this._quadMesh.material.needsUpdate = true;
  9776. return super.setup( builder );
  9777. }
  9778. setSize( width, height ) {
  9779. this.width = width;
  9780. this.height = height;
  9781. const effectiveWidth = width * this.pixelRatio;
  9782. const effectiveHeight = height * this.pixelRatio;
  9783. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  9784. this.textureNeedsUpdate = true;
  9785. }
  9786. setPixelRatio( pixelRatio ) {
  9787. this.pixelRatio = pixelRatio;
  9788. this.setSize( this.width, this.height );
  9789. }
  9790. updateBefore( { renderer } ) {
  9791. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  9792. this.textureNeedsUpdate = false;
  9793. //
  9794. if ( this.autoSize === true ) {
  9795. this.pixelRatio = renderer.getPixelRatio();
  9796. const size = renderer.getSize( _size$1 );
  9797. this.setSize( size.width, size.height );
  9798. }
  9799. //
  9800. this._quadMesh.material.fragmentNode = this._rttNode;
  9801. //
  9802. const currentRenderTarget = renderer.getRenderTarget();
  9803. renderer.setRenderTarget( this.renderTarget );
  9804. this._quadMesh.render( renderer );
  9805. renderer.setRenderTarget( currentRenderTarget );
  9806. }
  9807. clone() {
  9808. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  9809. newNode.sampler = this.sampler;
  9810. newNode.referenceNode = this;
  9811. return newNode;
  9812. }
  9813. }
  9814. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  9815. const convertToTexture = ( node, ...params ) => node.isTextureNode ? node : rtt( node, ...params );
  9816. /**
  9817. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  9818. * depth value and the camera's inverse projection matrix.
  9819. *
  9820. * @param {vec2} screenPosition - The fragment's screen position expressed as uv coordinates.
  9821. * @param {float} depth - The fragment's depth value.
  9822. * @param {mat4} projectionMatrixInverse - The camera's inverse projection matrix.
  9823. * @return {vec3} The fragments position in view space.
  9824. */
  9825. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  9826. let clipSpacePosition;
  9827. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  9828. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  9829. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  9830. } else {
  9831. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  9832. }
  9833. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  9834. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  9835. } );
  9836. /**
  9837. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  9838. * and the camera's projection matrix
  9839. *
  9840. * @param {vec3} viewPosition - The fragments position in view space.
  9841. * @param {mat4} projectionMatrix - The camera's projection matrix.
  9842. * @return {vec2} The fragment's screen position expressed as uv coordinates.
  9843. */
  9844. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  9845. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  9846. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  9847. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  9848. } );
  9849. /**
  9850. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  9851. * target is available or if flat surface normals are required.
  9852. *
  9853. * @param {vec2} uv - The texture coordinate.
  9854. * @param {DepthTexture} depthTexture - The depth texture.
  9855. * @param {mat4} projectionMatrixInverse - The camera's inverse projection matrix.
  9856. * @return {vec3} The computed normal vector.
  9857. */
  9858. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  9859. const size = textureSize( textureLoad( depthTexture ) );
  9860. const p = ivec2( uv.mul( size ) ).toVar();
  9861. const c0 = textureLoad( depthTexture, p ).toVar();
  9862. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  9863. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  9864. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  9865. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  9866. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  9867. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  9868. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  9869. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  9870. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  9871. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  9872. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  9873. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  9874. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  9875. 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 ) ) );
  9876. 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 ) ) );
  9877. return normalize( cross( dpdx, dpdy ) );
  9878. } );
  9879. class VertexColorNode extends AttributeNode {
  9880. static get type() {
  9881. return 'VertexColorNode';
  9882. }
  9883. constructor( index = 0 ) {
  9884. super( null, 'vec4' );
  9885. this.isVertexColorNode = true;
  9886. this.index = index;
  9887. }
  9888. getAttributeName( /*builder*/ ) {
  9889. const index = this.index;
  9890. return 'color' + ( index > 0 ? index : '' );
  9891. }
  9892. generate( builder ) {
  9893. const attributeName = this.getAttributeName( builder );
  9894. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  9895. let result;
  9896. if ( geometryAttribute === true ) {
  9897. result = super.generate( builder );
  9898. } else {
  9899. // Vertex color fallback should be white
  9900. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  9901. }
  9902. return result;
  9903. }
  9904. serialize( data ) {
  9905. super.serialize( data );
  9906. data.index = this.index;
  9907. }
  9908. deserialize( data ) {
  9909. super.deserialize( data );
  9910. this.index = data.index;
  9911. }
  9912. }
  9913. const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) );
  9914. class PointUVNode extends Node {
  9915. static get type() {
  9916. return 'PointUVNode';
  9917. }
  9918. constructor() {
  9919. super( 'vec2' );
  9920. this.isPointUVNode = true;
  9921. }
  9922. generate( /*builder*/ ) {
  9923. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  9924. }
  9925. }
  9926. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  9927. const _e1 = /*@__PURE__*/ new Euler();
  9928. const _m1 = /*@__PURE__*/ new Matrix4();
  9929. class SceneNode extends Node {
  9930. static get type() {
  9931. return 'SceneNode';
  9932. }
  9933. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  9934. super();
  9935. this.scope = scope;
  9936. this.scene = scene;
  9937. }
  9938. setup( builder ) {
  9939. const scope = this.scope;
  9940. const scene = this.scene !== null ? this.scene : builder.scene;
  9941. let output;
  9942. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  9943. output = reference( 'backgroundBlurriness', 'float', scene );
  9944. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  9945. output = reference( 'backgroundIntensity', 'float', scene );
  9946. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  9947. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  9948. const background = scene.background;
  9949. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  9950. _e1.copy( scene.backgroundRotation );
  9951. // accommodate left-handed frame
  9952. _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1;
  9953. _m1.makeRotationFromEuler( _e1 );
  9954. } else {
  9955. _m1.identity();
  9956. }
  9957. return _m1;
  9958. } );
  9959. } else {
  9960. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  9961. }
  9962. return output;
  9963. }
  9964. }
  9965. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  9966. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  9967. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  9968. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  9969. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  9970. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  9971. class StorageArrayElementNode extends ArrayElementNode {
  9972. static get type() {
  9973. return 'StorageArrayElementNode';
  9974. }
  9975. constructor( storageBufferNode, indexNode ) {
  9976. super( storageBufferNode, indexNode );
  9977. this.isStorageArrayElementNode = true;
  9978. }
  9979. set storageBufferNode( value ) {
  9980. this.node = value;
  9981. }
  9982. get storageBufferNode() {
  9983. return this.node;
  9984. }
  9985. setup( builder ) {
  9986. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  9987. if ( this.node.bufferObject === true ) {
  9988. builder.setupPBO( this.node );
  9989. }
  9990. }
  9991. return super.setup( builder );
  9992. }
  9993. generate( builder, output ) {
  9994. let snippet;
  9995. const isAssignContext = builder.context.assign;
  9996. //
  9997. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  9998. if ( this.node.bufferObject === true && isAssignContext !== true ) {
  9999. snippet = builder.generatePBO( this );
  10000. } else {
  10001. snippet = this.node.build( builder );
  10002. }
  10003. } else {
  10004. snippet = super.generate( builder );
  10005. }
  10006. if ( isAssignContext !== true ) {
  10007. const type = this.getNodeType( builder );
  10008. snippet = builder.format( snippet, type, output );
  10009. }
  10010. return snippet;
  10011. }
  10012. }
  10013. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  10014. const GPUPrimitiveTopology = {
  10015. PointList: 'point-list',
  10016. LineList: 'line-list',
  10017. LineStrip: 'line-strip',
  10018. TriangleList: 'triangle-list',
  10019. TriangleStrip: 'triangle-strip',
  10020. };
  10021. const GPUCompareFunction = {
  10022. Never: 'never',
  10023. Less: 'less',
  10024. Equal: 'equal',
  10025. LessEqual: 'less-equal',
  10026. Greater: 'greater',
  10027. NotEqual: 'not-equal',
  10028. GreaterEqual: 'greater-equal',
  10029. Always: 'always'
  10030. };
  10031. const GPUStoreOp = {
  10032. Store: 'store',
  10033. Discard: 'discard'
  10034. };
  10035. const GPULoadOp = {
  10036. Load: 'load',
  10037. Clear: 'clear'
  10038. };
  10039. const GPUFrontFace = {
  10040. CCW: 'ccw',
  10041. CW: 'cw'
  10042. };
  10043. const GPUCullMode = {
  10044. None: 'none',
  10045. Front: 'front',
  10046. Back: 'back'
  10047. };
  10048. const GPUIndexFormat = {
  10049. Uint16: 'uint16',
  10050. Uint32: 'uint32'
  10051. };
  10052. const GPUTextureFormat = {
  10053. // 8-bit formats
  10054. R8Unorm: 'r8unorm',
  10055. R8Snorm: 'r8snorm',
  10056. R8Uint: 'r8uint',
  10057. R8Sint: 'r8sint',
  10058. // 16-bit formats
  10059. R16Uint: 'r16uint',
  10060. R16Sint: 'r16sint',
  10061. R16Float: 'r16float',
  10062. RG8Unorm: 'rg8unorm',
  10063. RG8Snorm: 'rg8snorm',
  10064. RG8Uint: 'rg8uint',
  10065. RG8Sint: 'rg8sint',
  10066. // 32-bit formats
  10067. R32Uint: 'r32uint',
  10068. R32Sint: 'r32sint',
  10069. R32Float: 'r32float',
  10070. RG16Uint: 'rg16uint',
  10071. RG16Sint: 'rg16sint',
  10072. RG16Float: 'rg16float',
  10073. RGBA8Unorm: 'rgba8unorm',
  10074. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  10075. RGBA8Snorm: 'rgba8snorm',
  10076. RGBA8Uint: 'rgba8uint',
  10077. RGBA8Sint: 'rgba8sint',
  10078. BGRA8Unorm: 'bgra8unorm',
  10079. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  10080. // Packed 32-bit formats
  10081. RGB9E5UFloat: 'rgb9e5ufloat',
  10082. RGB10A2Unorm: 'rgb10a2unorm',
  10083. RG11B10uFloat: 'rgb10a2unorm',
  10084. // 64-bit formats
  10085. RG32Uint: 'rg32uint',
  10086. RG32Sint: 'rg32sint',
  10087. RG32Float: 'rg32float',
  10088. RGBA16Uint: 'rgba16uint',
  10089. RGBA16Sint: 'rgba16sint',
  10090. RGBA16Float: 'rgba16float',
  10091. // 128-bit formats
  10092. RGBA32Uint: 'rgba32uint',
  10093. RGBA32Sint: 'rgba32sint',
  10094. RGBA32Float: 'rgba32float',
  10095. // Depth and stencil formats
  10096. Stencil8: 'stencil8',
  10097. Depth16Unorm: 'depth16unorm',
  10098. Depth24Plus: 'depth24plus',
  10099. Depth24PlusStencil8: 'depth24plus-stencil8',
  10100. Depth32Float: 'depth32float',
  10101. // 'depth32float-stencil8' extension
  10102. Depth32FloatStencil8: 'depth32float-stencil8',
  10103. // BC compressed formats usable if 'texture-compression-bc' is both
  10104. // supported by the device/user agent and enabled in requestDevice.
  10105. BC1RGBAUnorm: 'bc1-rgba-unorm',
  10106. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  10107. BC2RGBAUnorm: 'bc2-rgba-unorm',
  10108. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  10109. BC3RGBAUnorm: 'bc3-rgba-unorm',
  10110. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  10111. BC4RUnorm: 'bc4-r-unorm',
  10112. BC4RSnorm: 'bc4-r-snorm',
  10113. BC5RGUnorm: 'bc5-rg-unorm',
  10114. BC5RGSnorm: 'bc5-rg-snorm',
  10115. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  10116. BC6HRGBFloat: 'bc6h-rgb-float',
  10117. BC7RGBAUnorm: 'bc7-rgba-unorm',
  10118. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  10119. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  10120. // supported by the device/user agent and enabled in requestDevice.
  10121. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  10122. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  10123. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  10124. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  10125. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  10126. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  10127. EACR11Unorm: 'eac-r11unorm',
  10128. EACR11Snorm: 'eac-r11snorm',
  10129. EACRG11Unorm: 'eac-rg11unorm',
  10130. EACRG11Snorm: 'eac-rg11snorm',
  10131. // ASTC compressed formats usable if 'texture-compression-astc' is both
  10132. // supported by the device/user agent and enabled in requestDevice.
  10133. ASTC4x4Unorm: 'astc-4x4-unorm',
  10134. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  10135. ASTC5x4Unorm: 'astc-5x4-unorm',
  10136. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  10137. ASTC5x5Unorm: 'astc-5x5-unorm',
  10138. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  10139. ASTC6x5Unorm: 'astc-6x5-unorm',
  10140. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  10141. ASTC6x6Unorm: 'astc-6x6-unorm',
  10142. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  10143. ASTC8x5Unorm: 'astc-8x5-unorm',
  10144. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  10145. ASTC8x6Unorm: 'astc-8x6-unorm',
  10146. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  10147. ASTC8x8Unorm: 'astc-8x8-unorm',
  10148. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  10149. ASTC10x5Unorm: 'astc-10x5-unorm',
  10150. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  10151. ASTC10x6Unorm: 'astc-10x6-unorm',
  10152. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  10153. ASTC10x8Unorm: 'astc-10x8-unorm',
  10154. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  10155. ASTC10x10Unorm: 'astc-10x10-unorm',
  10156. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  10157. ASTC12x10Unorm: 'astc-12x10-unorm',
  10158. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  10159. ASTC12x12Unorm: 'astc-12x12-unorm',
  10160. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  10161. };
  10162. const GPUAddressMode = {
  10163. ClampToEdge: 'clamp-to-edge',
  10164. Repeat: 'repeat',
  10165. MirrorRepeat: 'mirror-repeat'
  10166. };
  10167. const GPUFilterMode = {
  10168. Linear: 'linear',
  10169. Nearest: 'nearest'
  10170. };
  10171. const GPUBlendFactor = {
  10172. Zero: 'zero',
  10173. One: 'one',
  10174. Src: 'src',
  10175. OneMinusSrc: 'one-minus-src',
  10176. SrcAlpha: 'src-alpha',
  10177. OneMinusSrcAlpha: 'one-minus-src-alpha',
  10178. Dst: 'dst',
  10179. OneMinusDstColor: 'one-minus-dst',
  10180. DstAlpha: 'dst-alpha',
  10181. OneMinusDstAlpha: 'one-minus-dst-alpha',
  10182. SrcAlphaSaturated: 'src-alpha-saturated',
  10183. Constant: 'constant',
  10184. OneMinusConstant: 'one-minus-constant'
  10185. };
  10186. const GPUBlendOperation = {
  10187. Add: 'add',
  10188. Subtract: 'subtract',
  10189. ReverseSubtract: 'reverse-subtract',
  10190. Min: 'min',
  10191. Max: 'max'
  10192. };
  10193. const GPUColorWriteFlags = {
  10194. None: 0,
  10195. Red: 0x1,
  10196. Green: 0x2,
  10197. Blue: 0x4,
  10198. Alpha: 0x8,
  10199. All: 0xF
  10200. };
  10201. const GPUStencilOperation = {
  10202. Keep: 'keep',
  10203. Zero: 'zero',
  10204. Replace: 'replace',
  10205. Invert: 'invert',
  10206. IncrementClamp: 'increment-clamp',
  10207. DecrementClamp: 'decrement-clamp',
  10208. IncrementWrap: 'increment-wrap',
  10209. DecrementWrap: 'decrement-wrap'
  10210. };
  10211. const GPUBufferBindingType = {
  10212. Uniform: 'uniform',
  10213. Storage: 'storage',
  10214. ReadOnlyStorage: 'read-only-storage'
  10215. };
  10216. const GPUStorageTextureAccess = {
  10217. WriteOnly: 'write-only',
  10218. ReadOnly: 'read-only',
  10219. ReadWrite: 'read-write',
  10220. };
  10221. const GPUTextureSampleType = {
  10222. Float: 'float',
  10223. UnfilterableFloat: 'unfilterable-float',
  10224. Depth: 'depth',
  10225. SInt: 'sint',
  10226. UInt: 'uint'
  10227. };
  10228. const GPUTextureDimension = {
  10229. OneD: '1d',
  10230. TwoD: '2d',
  10231. ThreeD: '3d'
  10232. };
  10233. const GPUTextureViewDimension = {
  10234. OneD: '1d',
  10235. TwoD: '2d',
  10236. TwoDArray: '2d-array',
  10237. Cube: 'cube',
  10238. CubeArray: 'cube-array',
  10239. ThreeD: '3d'
  10240. };
  10241. const GPUTextureAspect = {
  10242. All: 'all',
  10243. StencilOnly: 'stencil-only',
  10244. DepthOnly: 'depth-only'
  10245. };
  10246. const GPUInputStepMode = {
  10247. Vertex: 'vertex',
  10248. Instance: 'instance'
  10249. };
  10250. const GPUFeatureName = {
  10251. DepthClipControl: 'depth-clip-control',
  10252. Depth32FloatStencil8: 'depth32float-stencil8',
  10253. TextureCompressionBC: 'texture-compression-bc',
  10254. TextureCompressionETC2: 'texture-compression-etc2',
  10255. TextureCompressionASTC: 'texture-compression-astc',
  10256. TimestampQuery: 'timestamp-query',
  10257. IndirectFirstInstance: 'indirect-first-instance',
  10258. ShaderF16: 'shader-f16',
  10259. RG11B10UFloat: 'rg11b10ufloat-renderable',
  10260. BGRA8UNormStorage: 'bgra8unorm-storage',
  10261. Float32Filterable: 'float32-filterable',
  10262. ClipDistances: 'clip-distances',
  10263. DualSourceBlending: 'dual-source-blending',
  10264. Subgroups: 'subgroups'
  10265. };
  10266. class StorageBufferNode extends BufferNode {
  10267. static get type() {
  10268. return 'StorageBufferNode';
  10269. }
  10270. constructor( value, bufferType, bufferCount = 0 ) {
  10271. super( value, bufferType, bufferCount );
  10272. this.isStorageBufferNode = true;
  10273. this.access = GPUBufferBindingType.Storage;
  10274. this.isAtomic = false;
  10275. this.bufferObject = false;
  10276. this.bufferCount = bufferCount;
  10277. this._attribute = null;
  10278. this._varying = null;
  10279. this.global = true;
  10280. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  10281. // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  10282. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  10283. else value.isStorageBufferAttribute = true;
  10284. }
  10285. }
  10286. getHash( builder ) {
  10287. if ( this.bufferCount === 0 ) {
  10288. let bufferData = builder.globalCache.getData( this.value );
  10289. if ( bufferData === undefined ) {
  10290. bufferData = {
  10291. node: this
  10292. };
  10293. builder.globalCache.setData( this.value, bufferData );
  10294. }
  10295. return bufferData.node.uuid;
  10296. }
  10297. return this.uuid;
  10298. }
  10299. getInputType( /*builder*/ ) {
  10300. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  10301. }
  10302. element( indexNode ) {
  10303. return storageElement( this, indexNode );
  10304. }
  10305. setBufferObject( value ) {
  10306. this.bufferObject = value;
  10307. return this;
  10308. }
  10309. setAccess( value ) {
  10310. this.access = value;
  10311. return this;
  10312. }
  10313. toReadOnly() {
  10314. return this.setAccess( GPUBufferBindingType.ReadOnlyStorage );
  10315. }
  10316. setAtomic( value ) {
  10317. this.isAtomic = value;
  10318. return this;
  10319. }
  10320. toAtomic() {
  10321. return this.setAtomic( true );
  10322. }
  10323. getAttributeData() {
  10324. if ( this._attribute === null ) {
  10325. this._attribute = bufferAttribute( this.value );
  10326. this._varying = varying( this._attribute );
  10327. }
  10328. return {
  10329. attribute: this._attribute,
  10330. varying: this._varying
  10331. };
  10332. }
  10333. getNodeType( builder ) {
  10334. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  10335. return super.getNodeType( builder );
  10336. }
  10337. const { attribute } = this.getAttributeData();
  10338. return attribute.getNodeType( builder );
  10339. }
  10340. generate( builder ) {
  10341. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  10342. return super.generate( builder );
  10343. }
  10344. const { attribute, varying } = this.getAttributeData();
  10345. const output = varying.build( builder );
  10346. builder.registerTransform( output, attribute );
  10347. return output;
  10348. }
  10349. }
  10350. // Read-Write Storage
  10351. const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) );
  10352. const storageObject = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ).setBufferObject( true ) );
  10353. class StorageTextureNode extends TextureNode {
  10354. static get type() {
  10355. return 'StorageTextureNode';
  10356. }
  10357. constructor( value, uvNode, storeNode = null ) {
  10358. super( value, uvNode );
  10359. this.storeNode = storeNode;
  10360. this.isStorageTextureNode = true;
  10361. this.access = GPUStorageTextureAccess.WriteOnly;
  10362. }
  10363. getInputType( /*builder*/ ) {
  10364. return 'storageTexture';
  10365. }
  10366. setup( builder ) {
  10367. super.setup( builder );
  10368. const properties = builder.getNodeProperties( this );
  10369. properties.storeNode = this.storeNode;
  10370. }
  10371. setAccess( value ) {
  10372. this.access = value;
  10373. return this;
  10374. }
  10375. generate( builder, output ) {
  10376. let snippet;
  10377. if ( this.storeNode !== null ) {
  10378. snippet = this.generateStore( builder );
  10379. } else {
  10380. snippet = super.generate( builder, output );
  10381. }
  10382. return snippet;
  10383. }
  10384. toReadOnly() {
  10385. return this.setAccess( GPUStorageTextureAccess.ReadOnly );
  10386. }
  10387. toWriteOnly() {
  10388. return this.setAccess( GPUStorageTextureAccess.WriteOnly );
  10389. }
  10390. generateStore( builder ) {
  10391. const properties = builder.getNodeProperties( this );
  10392. const { uvNode, storeNode } = properties;
  10393. const textureProperty = super.generate( builder, 'property' );
  10394. const uvSnippet = uvNode.build( builder, 'uvec2' );
  10395. const storeSnippet = storeNode.build( builder, 'vec4' );
  10396. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  10397. builder.addLineFlowCode( snippet, this );
  10398. }
  10399. }
  10400. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  10401. const textureStore = ( value, uvNode, storeNode ) => {
  10402. const node = storageTexture( value, uvNode, storeNode );
  10403. if ( storeNode !== null ) node.append();
  10404. return node;
  10405. };
  10406. class UserDataNode extends ReferenceNode {
  10407. static get type() {
  10408. return 'UserDataNode';
  10409. }
  10410. constructor( property, inputType, userData = null ) {
  10411. super( property, inputType, userData );
  10412. this.userData = userData;
  10413. }
  10414. updateReference( state ) {
  10415. this.reference = this.userData !== null ? this.userData : state.object.userData;
  10416. return this.reference;
  10417. }
  10418. }
  10419. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  10420. const _objectData = new WeakMap();
  10421. class VelocityNode extends TempNode {
  10422. static get type() {
  10423. return 'VelocityNode';
  10424. }
  10425. constructor() {
  10426. super( 'vec2' );
  10427. this.projectionMatrix = null;
  10428. this.updateType = NodeUpdateType.OBJECT;
  10429. this.updateAfterType = NodeUpdateType.OBJECT;
  10430. this.previousModelWorldMatrix = uniform( new Matrix4() );
  10431. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  10432. this.previousCameraViewMatrix = uniform( new Matrix4() );
  10433. }
  10434. setProjectionMatrix( projectionMatrix ) {
  10435. this.projectionMatrix = projectionMatrix;
  10436. }
  10437. update( { frameId, camera, object } ) {
  10438. const previousModelMatrix = getPreviousMatrix( object );
  10439. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  10440. //
  10441. const cameraData = getData( camera );
  10442. if ( cameraData.frameId !== frameId ) {
  10443. cameraData.frameId = frameId;
  10444. if ( cameraData.previousProjectionMatrix === undefined ) {
  10445. cameraData.previousProjectionMatrix = new Matrix4();
  10446. cameraData.previousCameraViewMatrix = new Matrix4();
  10447. cameraData.currentProjectionMatrix = new Matrix4();
  10448. cameraData.currentCameraViewMatrix = new Matrix4();
  10449. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  10450. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  10451. } else {
  10452. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  10453. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  10454. }
  10455. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  10456. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  10457. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  10458. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  10459. }
  10460. }
  10461. updateAfter( { object } ) {
  10462. getPreviousMatrix( object ).copy( object.matrixWorld );
  10463. }
  10464. setup( /*builder*/ ) {
  10465. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  10466. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  10467. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  10468. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  10469. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  10470. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  10471. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  10472. return velocity;
  10473. }
  10474. }
  10475. function getData( object ) {
  10476. let objectData = _objectData.get( object );
  10477. if ( objectData === undefined ) {
  10478. objectData = {};
  10479. _objectData.set( object, objectData );
  10480. }
  10481. return objectData;
  10482. }
  10483. function getPreviousMatrix( object, index = 0 ) {
  10484. const objectData = getData( object );
  10485. let matrix = objectData[ index ];
  10486. if ( matrix === undefined ) {
  10487. objectData[ index ] = matrix = new Matrix4();
  10488. }
  10489. return matrix;
  10490. }
  10491. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  10492. const burn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  10493. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  10494. } ).setLayout( {
  10495. name: 'burnBlend',
  10496. type: 'vec3',
  10497. inputs: [
  10498. { name: 'base', type: 'vec3' },
  10499. { name: 'blend', type: 'vec3' }
  10500. ]
  10501. } );
  10502. const dodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  10503. return min$1( base.div( blend.oneMinus() ), 1.0 );
  10504. } ).setLayout( {
  10505. name: 'dodgeBlend',
  10506. type: 'vec3',
  10507. inputs: [
  10508. { name: 'base', type: 'vec3' },
  10509. { name: 'blend', type: 'vec3' }
  10510. ]
  10511. } );
  10512. const screen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  10513. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  10514. } ).setLayout( {
  10515. name: 'screenBlend',
  10516. type: 'vec3',
  10517. inputs: [
  10518. { name: 'base', type: 'vec3' },
  10519. { name: 'blend', type: 'vec3' }
  10520. ]
  10521. } );
  10522. const overlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  10523. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  10524. } ).setLayout( {
  10525. name: 'overlayBlend',
  10526. type: 'vec3',
  10527. inputs: [
  10528. { name: 'base', type: 'vec3' },
  10529. { name: 'blend', type: 'vec3' }
  10530. ]
  10531. } );
  10532. const blendNormal = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  10533. return vec4( base.rgb.mul( blend.a.oneMinus() ).add( blend.rgb.mul( blend.a ) ), base.a );
  10534. } ).setLayout( {
  10535. name: 'blendNormal',
  10536. type: 'vec4',
  10537. inputs: [
  10538. { name: 'base', type: 'vec4' },
  10539. { name: 'blend', type: 'vec4' }
  10540. ]
  10541. } );
  10542. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  10543. return luminance( color.rgb );
  10544. } );
  10545. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  10546. return adjustment.mix( luminance( color.rgb ), color.rgb );
  10547. } );
  10548. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  10549. const average = add( color.r, color.g, color.b ).div( 3.0 );
  10550. const mx = color.r.max( color.g.max( color.b ) );
  10551. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  10552. return mix( color.rgb, mx, amt );
  10553. } );
  10554. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  10555. const k = vec3( 0.57735, 0.57735, 0.57735 );
  10556. const cosAngle = adjustment.cos();
  10557. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  10558. } );
  10559. const luminance = (
  10560. color,
  10561. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  10562. ) => dot( color, luminanceCoefficients );
  10563. const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) );
  10564. /**
  10565. * Color Decision List (CDL) v1.2
  10566. *
  10567. * Compact representation of color grading information, defined by slope, offset, power, and
  10568. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  10569. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  10570. *
  10571. * @param {vec4} color Input (-Infinity < input < +Infinity)
  10572. * @param {number | vec3} slope Slope (0 ≤ slope < +Infinity)
  10573. * @param {number | vec3} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  10574. * @param {number | vec3} power Power (0 < power < +Infinity)
  10575. * @param {number} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  10576. * @param {vec3} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  10577. * @return Output, -Infinity < output < +Infinity
  10578. *
  10579. * References:
  10580. * - ASC CDL v1.2
  10581. * - https://blender.stackexchange.com/a/55239/43930
  10582. * - https://docs.acescentral.com/specifications/acescc/
  10583. */
  10584. const cdl = /*@__PURE__*/ Fn( ( [
  10585. color,
  10586. slope = vec3( 1 ),
  10587. offset = vec3( 0 ),
  10588. power = vec3( 1 ),
  10589. saturation = float( 1 ),
  10590. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  10591. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  10592. ] ) => {
  10593. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  10594. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  10595. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  10596. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  10597. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  10598. const pv = v.pow( power ).toVar();
  10599. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  10600. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  10601. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  10602. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  10603. return vec4( v.rgb, color.a );
  10604. } );
  10605. class PosterizeNode extends TempNode {
  10606. static get type() {
  10607. return 'PosterizeNode';
  10608. }
  10609. constructor( sourceNode, stepsNode ) {
  10610. super();
  10611. this.sourceNode = sourceNode;
  10612. this.stepsNode = stepsNode;
  10613. }
  10614. setup() {
  10615. const { sourceNode, stepsNode } = this;
  10616. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  10617. }
  10618. }
  10619. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  10620. let _sharedFramebuffer = null;
  10621. class ViewportSharedTextureNode extends ViewportTextureNode {
  10622. static get type() {
  10623. return 'ViewportSharedTextureNode';
  10624. }
  10625. constructor( uvNode = screenUV, levelNode = null ) {
  10626. if ( _sharedFramebuffer === null ) {
  10627. _sharedFramebuffer = new FramebufferTexture();
  10628. }
  10629. super( uvNode, levelNode, _sharedFramebuffer );
  10630. }
  10631. updateReference() {
  10632. return this;
  10633. }
  10634. }
  10635. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  10636. const _size = /*@__PURE__*/ new Vector2();
  10637. class PassTextureNode extends TextureNode {
  10638. static get type() {
  10639. return 'PassTextureNode';
  10640. }
  10641. constructor( passNode, texture ) {
  10642. super( texture );
  10643. this.passNode = passNode;
  10644. this.setUpdateMatrix( false );
  10645. }
  10646. setup( builder ) {
  10647. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  10648. return super.setup( builder );
  10649. }
  10650. clone() {
  10651. return new this.constructor( this.passNode, this.value );
  10652. }
  10653. }
  10654. class PassMultipleTextureNode extends PassTextureNode {
  10655. static get type() {
  10656. return 'PassMultipleTextureNode';
  10657. }
  10658. constructor( passNode, textureName, previousTexture = false ) {
  10659. super( passNode, null );
  10660. this.textureName = textureName;
  10661. this.previousTexture = previousTexture;
  10662. }
  10663. updateTexture() {
  10664. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  10665. }
  10666. setup( builder ) {
  10667. this.updateTexture();
  10668. return super.setup( builder );
  10669. }
  10670. clone() {
  10671. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  10672. }
  10673. }
  10674. class PassNode extends TempNode {
  10675. static get type() {
  10676. return 'PassNode';
  10677. }
  10678. constructor( scope, scene, camera, options = {} ) {
  10679. super( 'vec4' );
  10680. this.scope = scope;
  10681. this.scene = scene;
  10682. this.camera = camera;
  10683. this.options = options;
  10684. this._pixelRatio = 1;
  10685. this._width = 1;
  10686. this._height = 1;
  10687. const depthTexture = new DepthTexture();
  10688. depthTexture.isRenderTargetTexture = true;
  10689. //depthTexture.type = FloatType;
  10690. depthTexture.name = 'depth';
  10691. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  10692. renderTarget.texture.name = 'output';
  10693. renderTarget.depthTexture = depthTexture;
  10694. this.renderTarget = renderTarget;
  10695. this.updateBeforeType = NodeUpdateType.FRAME;
  10696. this._textures = {
  10697. output: renderTarget.texture,
  10698. depth: depthTexture
  10699. };
  10700. this._textureNodes = {};
  10701. this._linearDepthNodes = {};
  10702. this._viewZNodes = {};
  10703. this._previousTextures = {};
  10704. this._previousTextureNodes = {};
  10705. this._cameraNear = uniform( 0 );
  10706. this._cameraFar = uniform( 0 );
  10707. this._mrt = null;
  10708. this.isPassNode = true;
  10709. }
  10710. setMRT( mrt ) {
  10711. this._mrt = mrt;
  10712. return this;
  10713. }
  10714. getMRT() {
  10715. return this._mrt;
  10716. }
  10717. isGlobal() {
  10718. return true;
  10719. }
  10720. getTexture( name ) {
  10721. let texture = this._textures[ name ];
  10722. if ( texture === undefined ) {
  10723. const refTexture = this.renderTarget.texture;
  10724. texture = refTexture.clone();
  10725. texture.isRenderTargetTexture = true;
  10726. texture.name = name;
  10727. this._textures[ name ] = texture;
  10728. this.renderTarget.textures.push( texture );
  10729. }
  10730. return texture;
  10731. }
  10732. getPreviousTexture( name ) {
  10733. let texture = this._previousTextures[ name ];
  10734. if ( texture === undefined ) {
  10735. texture = this.getTexture( name ).clone();
  10736. texture.isRenderTargetTexture = true;
  10737. this._previousTextures[ name ] = texture;
  10738. }
  10739. return texture;
  10740. }
  10741. toggleTexture( name ) {
  10742. const prevTexture = this._previousTextures[ name ];
  10743. if ( prevTexture !== undefined ) {
  10744. const texture = this._textures[ name ];
  10745. const index = this.renderTarget.textures.indexOf( texture );
  10746. this.renderTarget.textures[ index ] = prevTexture;
  10747. this._textures[ name ] = prevTexture;
  10748. this._previousTextures[ name ] = texture;
  10749. this._textureNodes[ name ].updateTexture();
  10750. this._previousTextureNodes[ name ].updateTexture();
  10751. }
  10752. }
  10753. getTextureNode( name = 'output' ) {
  10754. let textureNode = this._textureNodes[ name ];
  10755. if ( textureNode === undefined ) {
  10756. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  10757. textureNode.updateTexture();
  10758. this._textureNodes[ name ] = textureNode;
  10759. }
  10760. return textureNode;
  10761. }
  10762. getPreviousTextureNode( name = 'output' ) {
  10763. let textureNode = this._previousTextureNodes[ name ];
  10764. if ( textureNode === undefined ) {
  10765. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  10766. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  10767. textureNode.updateTexture();
  10768. this._previousTextureNodes[ name ] = textureNode;
  10769. }
  10770. return textureNode;
  10771. }
  10772. getViewZNode( name = 'depth' ) {
  10773. let viewZNode = this._viewZNodes[ name ];
  10774. if ( viewZNode === undefined ) {
  10775. const cameraNear = this._cameraNear;
  10776. const cameraFar = this._cameraFar;
  10777. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  10778. }
  10779. return viewZNode;
  10780. }
  10781. getLinearDepthNode( name = 'depth' ) {
  10782. let linearDepthNode = this._linearDepthNodes[ name ];
  10783. if ( linearDepthNode === undefined ) {
  10784. const cameraNear = this._cameraNear;
  10785. const cameraFar = this._cameraFar;
  10786. const viewZNode = this.getViewZNode( name );
  10787. // TODO: just if ( builder.camera.isPerspectiveCamera )
  10788. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  10789. }
  10790. return linearDepthNode;
  10791. }
  10792. setup( { renderer } ) {
  10793. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  10794. // Disable MSAA for WebGL backend for now
  10795. if ( renderer.backend.isWebGLBackend === true ) {
  10796. this.renderTarget.samples = 0;
  10797. }
  10798. this.renderTarget.depthTexture.isMultisampleRenderTargetTexture = this.renderTarget.samples > 1;
  10799. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  10800. }
  10801. updateBefore( frame ) {
  10802. const { renderer } = frame;
  10803. const { scene, camera } = this;
  10804. this._pixelRatio = renderer.getPixelRatio();
  10805. const size = renderer.getSize( _size );
  10806. this.setSize( size.width, size.height );
  10807. const currentRenderTarget = renderer.getRenderTarget();
  10808. const currentMRT = renderer.getMRT();
  10809. this._cameraNear.value = camera.near;
  10810. this._cameraFar.value = camera.far;
  10811. for ( const name in this._previousTextures ) {
  10812. this.toggleTexture( name );
  10813. }
  10814. renderer.setRenderTarget( this.renderTarget );
  10815. renderer.setMRT( this._mrt );
  10816. renderer.render( scene, camera );
  10817. renderer.setRenderTarget( currentRenderTarget );
  10818. renderer.setMRT( currentMRT );
  10819. }
  10820. setSize( width, height ) {
  10821. this._width = width;
  10822. this._height = height;
  10823. const effectiveWidth = this._width * this._pixelRatio;
  10824. const effectiveHeight = this._height * this._pixelRatio;
  10825. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  10826. }
  10827. setPixelRatio( pixelRatio ) {
  10828. this._pixelRatio = pixelRatio;
  10829. this.setSize( this._width, this._height );
  10830. }
  10831. dispose() {
  10832. this.renderTarget.dispose();
  10833. }
  10834. }
  10835. PassNode.COLOR = 'color';
  10836. PassNode.DEPTH = 'depth';
  10837. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  10838. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  10839. const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) );
  10840. class ToonOutlinePassNode extends PassNode {
  10841. static get type() {
  10842. return 'ToonOutlinePassNode';
  10843. }
  10844. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  10845. super( PassNode.COLOR, scene, camera );
  10846. this.colorNode = colorNode;
  10847. this.thicknessNode = thicknessNode;
  10848. this.alphaNode = alphaNode;
  10849. this._materialCache = new WeakMap();
  10850. }
  10851. updateBefore( frame ) {
  10852. const { renderer } = frame;
  10853. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  10854. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  10855. // only render outline for supported materials
  10856. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  10857. if ( material.wireframe === false ) {
  10858. const outlineMaterial = this._getOutlineMaterial( material );
  10859. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  10860. }
  10861. }
  10862. // default
  10863. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  10864. } );
  10865. super.updateBefore( frame );
  10866. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  10867. }
  10868. _createMaterial() {
  10869. const material = new NodeMaterial();
  10870. material.isMeshToonOutlineMaterial = true;
  10871. material.name = 'Toon_Outline';
  10872. material.side = BackSide;
  10873. // vertex node
  10874. const outlineNormal = normalLocal.negate();
  10875. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  10876. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  10877. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  10878. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  10879. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  10880. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  10881. // color node
  10882. material.colorNode = vec4( this.colorNode, this.alphaNode );
  10883. return material;
  10884. }
  10885. _getOutlineMaterial( originalMaterial ) {
  10886. let outlineMaterial = this._materialCache.get( originalMaterial );
  10887. if ( outlineMaterial === undefined ) {
  10888. outlineMaterial = this._createMaterial();
  10889. this._materialCache.set( originalMaterial, outlineMaterial );
  10890. }
  10891. return outlineMaterial;
  10892. }
  10893. }
  10894. 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 ) ) );
  10895. // exposure only
  10896. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  10897. return color.mul( exposure ).clamp();
  10898. } ).setLayout( {
  10899. name: 'linearToneMapping',
  10900. type: 'vec3',
  10901. inputs: [
  10902. { name: 'color', type: 'vec3' },
  10903. { name: 'exposure', type: 'float' }
  10904. ]
  10905. } );
  10906. // source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf
  10907. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  10908. color = color.mul( exposure );
  10909. return color.div( color.add( 1.0 ) ).clamp();
  10910. } ).setLayout( {
  10911. name: 'reinhardToneMapping',
  10912. type: 'vec3',
  10913. inputs: [
  10914. { name: 'color', type: 'vec3' },
  10915. { name: 'exposure', type: 'float' }
  10916. ]
  10917. } );
  10918. // source: http://filmicworlds.com/blog/filmic-tonemapping-operators/
  10919. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  10920. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  10921. color = color.mul( exposure );
  10922. color = color.sub( 0.004 ).max( 0.0 );
  10923. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  10924. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  10925. return a.div( b ).pow( 2.2 );
  10926. } ).setLayout( {
  10927. name: 'cineonToneMapping',
  10928. type: 'vec3',
  10929. inputs: [
  10930. { name: 'color', type: 'vec3' },
  10931. { name: 'exposure', type: 'float' }
  10932. ]
  10933. } );
  10934. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  10935. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  10936. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  10937. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  10938. return a.div( b );
  10939. } );
  10940. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  10941. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  10942. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  10943. const ACESInputMat = mat3(
  10944. 0.59719, 0.35458, 0.04823,
  10945. 0.07600, 0.90834, 0.01566,
  10946. 0.02840, 0.13383, 0.83777
  10947. );
  10948. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  10949. const ACESOutputMat = mat3(
  10950. 1.60475, - 0.53108, - 0.07367,
  10951. - 0.10208, 1.10813, - 0.00605,
  10952. - 0.00327, - 0.07276, 1.07602
  10953. );
  10954. color = color.mul( exposure ).div( 0.6 );
  10955. color = ACESInputMat.mul( color );
  10956. // Apply RRT and ODT
  10957. color = RRTAndODTFit( color );
  10958. color = ACESOutputMat.mul( color );
  10959. // Clamp to [0, 1]
  10960. return color.clamp();
  10961. } ).setLayout( {
  10962. name: 'acesFilmicToneMapping',
  10963. type: 'vec3',
  10964. inputs: [
  10965. { name: 'color', type: 'vec3' },
  10966. { name: 'exposure', type: 'float' }
  10967. ]
  10968. } );
  10969. 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 ) );
  10970. 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 ) );
  10971. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  10972. const x = vec3( x_immutable ).toVar();
  10973. const x2 = vec3( x.mul( x ) ).toVar();
  10974. const x4 = vec3( x2.mul( x2 ) ).toVar();
  10975. 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 ) ) ) );
  10976. } );
  10977. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  10978. const colortone = vec3( color ).toVar();
  10979. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  10980. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  10981. const AgxMinEv = float( - 12.47393 );
  10982. const AgxMaxEv = float( 4.026069 );
  10983. colortone.mulAssign( exposure );
  10984. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  10985. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  10986. colortone.assign( max$1( colortone, 1e-10 ) );
  10987. colortone.assign( log2( colortone ) );
  10988. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  10989. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  10990. colortone.assign( agxDefaultContrastApprox( colortone ) );
  10991. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  10992. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  10993. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  10994. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  10995. return colortone;
  10996. } ).setLayout( {
  10997. name: 'agxToneMapping',
  10998. type: 'vec3',
  10999. inputs: [
  11000. { name: 'color', type: 'vec3' },
  11001. { name: 'exposure', type: 'float' }
  11002. ]
  11003. } );
  11004. // https://modelviewer.dev/examples/tone-mapping
  11005. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  11006. const StartCompression = float( 0.8 - 0.04 );
  11007. const Desaturation = float( 0.15 );
  11008. color = color.mul( exposure );
  11009. const x = min$1( color.r, min$1( color.g, color.b ) );
  11010. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  11011. color.subAssign( offset );
  11012. const peak = max$1( color.r, max$1( color.g, color.b ) );
  11013. If( peak.lessThan( StartCompression ), () => {
  11014. return color;
  11015. } );
  11016. const d = sub( 1, StartCompression );
  11017. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  11018. color.mulAssign( newPeak.div( peak ) );
  11019. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  11020. return mix( color, vec3( newPeak ), g );
  11021. } ).setLayout( {
  11022. name: 'neutralToneMapping',
  11023. type: 'vec3',
  11024. inputs: [
  11025. { name: 'color', type: 'vec3' },
  11026. { name: 'exposure', type: 'float' }
  11027. ]
  11028. } );
  11029. class CodeNode extends Node {
  11030. static get type() {
  11031. return 'CodeNode';
  11032. }
  11033. constructor( code = '', includes = [], language = '' ) {
  11034. super( 'code' );
  11035. this.isCodeNode = true;
  11036. this.code = code;
  11037. this.language = language;
  11038. this.includes = includes;
  11039. }
  11040. isGlobal() {
  11041. return true;
  11042. }
  11043. setIncludes( includes ) {
  11044. this.includes = includes;
  11045. return this;
  11046. }
  11047. getIncludes( /*builder*/ ) {
  11048. return this.includes;
  11049. }
  11050. generate( builder ) {
  11051. const includes = this.getIncludes( builder );
  11052. for ( const include of includes ) {
  11053. include.build( builder );
  11054. }
  11055. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  11056. nodeCode.code = this.code;
  11057. return nodeCode.code;
  11058. }
  11059. serialize( data ) {
  11060. super.serialize( data );
  11061. data.code = this.code;
  11062. data.language = this.language;
  11063. }
  11064. deserialize( data ) {
  11065. super.deserialize( data );
  11066. this.code = data.code;
  11067. this.language = data.language;
  11068. }
  11069. }
  11070. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  11071. const js = ( src, includes ) => code( src, includes, 'js' );
  11072. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  11073. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  11074. class FunctionNode extends CodeNode {
  11075. static get type() {
  11076. return 'FunctionNode';
  11077. }
  11078. constructor( code = '', includes = [], language = '' ) {
  11079. super( code, includes, language );
  11080. }
  11081. getNodeType( builder ) {
  11082. return this.getNodeFunction( builder ).type;
  11083. }
  11084. getInputs( builder ) {
  11085. return this.getNodeFunction( builder ).inputs;
  11086. }
  11087. getNodeFunction( builder ) {
  11088. const nodeData = builder.getDataFromNode( this );
  11089. let nodeFunction = nodeData.nodeFunction;
  11090. if ( nodeFunction === undefined ) {
  11091. nodeFunction = builder.parser.parseFunction( this.code );
  11092. nodeData.nodeFunction = nodeFunction;
  11093. }
  11094. return nodeFunction;
  11095. }
  11096. generate( builder, output ) {
  11097. super.generate( builder );
  11098. const nodeFunction = this.getNodeFunction( builder );
  11099. const name = nodeFunction.name;
  11100. const type = nodeFunction.type;
  11101. const nodeCode = builder.getCodeFromNode( this, type );
  11102. if ( name !== '' ) {
  11103. // use a custom property name
  11104. nodeCode.name = name;
  11105. }
  11106. const propertyName = builder.getPropertyName( nodeCode );
  11107. const code = this.getNodeFunction( builder ).getCode( propertyName );
  11108. nodeCode.code = code + '\n';
  11109. if ( output === 'property' ) {
  11110. return propertyName;
  11111. } else {
  11112. return builder.format( `${ propertyName }()`, type, output );
  11113. }
  11114. }
  11115. }
  11116. const nativeFn = ( code, includes = [], language = '' ) => {
  11117. for ( let i = 0; i < includes.length; i ++ ) {
  11118. const include = includes[ i ];
  11119. // TSL Function: glslFn, wgslFn
  11120. if ( typeof include === 'function' ) {
  11121. includes[ i ] = include.functionNode;
  11122. }
  11123. }
  11124. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  11125. const fn = ( ...params ) => functionNode.call( ...params );
  11126. fn.functionNode = functionNode;
  11127. return fn;
  11128. };
  11129. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  11130. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  11131. class ScriptableValueNode extends Node {
  11132. static get type() {
  11133. return 'ScriptableValueNode';
  11134. }
  11135. constructor( value = null ) {
  11136. super();
  11137. this._value = value;
  11138. this._cache = null;
  11139. this.inputType = null;
  11140. this.outpuType = null;
  11141. this.events = new EventDispatcher();
  11142. this.isScriptableValueNode = true;
  11143. }
  11144. get isScriptableOutputNode() {
  11145. return this.outputType !== null;
  11146. }
  11147. set value( val ) {
  11148. if ( this._value === val ) return;
  11149. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  11150. URL.revokeObjectURL( this._cache );
  11151. this._cache = null;
  11152. }
  11153. this._value = val;
  11154. this.events.dispatchEvent( { type: 'change' } );
  11155. this.refresh();
  11156. }
  11157. get value() {
  11158. return this._value;
  11159. }
  11160. refresh() {
  11161. this.events.dispatchEvent( { type: 'refresh' } );
  11162. }
  11163. getValue() {
  11164. const value = this.value;
  11165. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  11166. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  11167. } else if ( value && value.value !== null && value.value !== undefined && (
  11168. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  11169. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  11170. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  11171. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  11172. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  11173. ( this.inputType === 'Color' && value.value.isColor ) ||
  11174. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  11175. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  11176. ) ) {
  11177. return value.value;
  11178. }
  11179. return this._cache || value;
  11180. }
  11181. getNodeType( builder ) {
  11182. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  11183. }
  11184. setup() {
  11185. return this.value && this.value.isNode ? this.value : float();
  11186. }
  11187. serialize( data ) {
  11188. super.serialize( data );
  11189. if ( this.value !== null ) {
  11190. if ( this.inputType === 'ArrayBuffer' ) {
  11191. data.value = arrayBufferToBase64( this.value );
  11192. } else {
  11193. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  11194. }
  11195. } else {
  11196. data.value = null;
  11197. }
  11198. data.inputType = this.inputType;
  11199. data.outputType = this.outputType;
  11200. }
  11201. deserialize( data ) {
  11202. super.deserialize( data );
  11203. let value = null;
  11204. if ( data.value !== null ) {
  11205. if ( data.inputType === 'ArrayBuffer' ) {
  11206. value = base64ToArrayBuffer( data.value );
  11207. } else if ( data.inputType === 'Texture' ) {
  11208. value = data.meta.textures[ data.value ];
  11209. } else {
  11210. value = data.meta.nodes[ data.value ] || null;
  11211. }
  11212. }
  11213. this.value = value;
  11214. this.inputType = data.inputType;
  11215. this.outputType = data.outputType;
  11216. }
  11217. }
  11218. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  11219. class Resources extends Map {
  11220. get( key, callback = null, ...params ) {
  11221. if ( this.has( key ) ) return super.get( key );
  11222. if ( callback !== null ) {
  11223. const value = callback( ...params );
  11224. this.set( key, value );
  11225. return value;
  11226. }
  11227. }
  11228. }
  11229. class Parameters {
  11230. constructor( scriptableNode ) {
  11231. this.scriptableNode = scriptableNode;
  11232. }
  11233. get parameters() {
  11234. return this.scriptableNode.parameters;
  11235. }
  11236. get layout() {
  11237. return this.scriptableNode.getLayout();
  11238. }
  11239. getInputLayout( id ) {
  11240. return this.scriptableNode.getInputLayout( id );
  11241. }
  11242. get( name ) {
  11243. const param = this.parameters[ name ];
  11244. const value = param ? param.getValue() : null;
  11245. return value;
  11246. }
  11247. }
  11248. const ScriptableNodeResources = new Resources();
  11249. class ScriptableNode extends Node {
  11250. static get type() {
  11251. return 'ScriptableNode';
  11252. }
  11253. constructor( codeNode = null, parameters = {} ) {
  11254. super();
  11255. this.codeNode = codeNode;
  11256. this.parameters = parameters;
  11257. this._local = new Resources();
  11258. this._output = scriptableValue();
  11259. this._outputs = {};
  11260. this._source = this.source;
  11261. this._method = null;
  11262. this._object = null;
  11263. this._value = null;
  11264. this._needsOutputUpdate = true;
  11265. this.onRefresh = this.onRefresh.bind( this );
  11266. this.isScriptableNode = true;
  11267. }
  11268. get source() {
  11269. return this.codeNode ? this.codeNode.code : '';
  11270. }
  11271. setLocal( name, value ) {
  11272. return this._local.set( name, value );
  11273. }
  11274. getLocal( name ) {
  11275. return this._local.get( name );
  11276. }
  11277. onRefresh() {
  11278. this._refresh();
  11279. }
  11280. getInputLayout( id ) {
  11281. for ( const element of this.getLayout() ) {
  11282. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  11283. return element;
  11284. }
  11285. }
  11286. }
  11287. getOutputLayout( id ) {
  11288. for ( const element of this.getLayout() ) {
  11289. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  11290. return element;
  11291. }
  11292. }
  11293. }
  11294. setOutput( name, value ) {
  11295. const outputs = this._outputs;
  11296. if ( outputs[ name ] === undefined ) {
  11297. outputs[ name ] = scriptableValue( value );
  11298. } else {
  11299. outputs[ name ].value = value;
  11300. }
  11301. return this;
  11302. }
  11303. getOutput( name ) {
  11304. return this._outputs[ name ];
  11305. }
  11306. getParameter( name ) {
  11307. return this.parameters[ name ];
  11308. }
  11309. setParameter( name, value ) {
  11310. const parameters = this.parameters;
  11311. if ( value && value.isScriptableNode ) {
  11312. this.deleteParameter( name );
  11313. parameters[ name ] = value;
  11314. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  11315. } else if ( value && value.isScriptableValueNode ) {
  11316. this.deleteParameter( name );
  11317. parameters[ name ] = value;
  11318. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  11319. } else if ( parameters[ name ] === undefined ) {
  11320. parameters[ name ] = scriptableValue( value );
  11321. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  11322. } else {
  11323. parameters[ name ].value = value;
  11324. }
  11325. return this;
  11326. }
  11327. getValue() {
  11328. return this.getDefaultOutput().getValue();
  11329. }
  11330. deleteParameter( name ) {
  11331. let valueNode = this.parameters[ name ];
  11332. if ( valueNode ) {
  11333. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  11334. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  11335. }
  11336. return this;
  11337. }
  11338. clearParameters() {
  11339. for ( const name of Object.keys( this.parameters ) ) {
  11340. this.deleteParameter( name );
  11341. }
  11342. this.needsUpdate = true;
  11343. return this;
  11344. }
  11345. call( name, ...params ) {
  11346. const object = this.getObject();
  11347. const method = object[ name ];
  11348. if ( typeof method === 'function' ) {
  11349. return method( ...params );
  11350. }
  11351. }
  11352. async callAsync( name, ...params ) {
  11353. const object = this.getObject();
  11354. const method = object[ name ];
  11355. if ( typeof method === 'function' ) {
  11356. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  11357. }
  11358. }
  11359. getNodeType( builder ) {
  11360. return this.getDefaultOutputNode().getNodeType( builder );
  11361. }
  11362. refresh( output = null ) {
  11363. if ( output !== null ) {
  11364. this.getOutput( output ).refresh();
  11365. } else {
  11366. this._refresh();
  11367. }
  11368. }
  11369. getObject() {
  11370. if ( this.needsUpdate ) this.dispose();
  11371. if ( this._object !== null ) return this._object;
  11372. //
  11373. const refresh = () => this.refresh();
  11374. const setOutput = ( id, value ) => this.setOutput( id, value );
  11375. const parameters = new Parameters( this );
  11376. const THREE = ScriptableNodeResources.get( 'THREE' );
  11377. const TSL = ScriptableNodeResources.get( 'TSL' );
  11378. const method = this.getMethod( this.codeNode );
  11379. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  11380. this._object = method( ...params );
  11381. const layout = this._object.layout;
  11382. if ( layout ) {
  11383. if ( layout.cache === false ) {
  11384. this._local.clear();
  11385. }
  11386. // default output
  11387. this._output.outputType = layout.outputType || null;
  11388. if ( Array.isArray( layout.elements ) ) {
  11389. for ( const element of layout.elements ) {
  11390. const id = element.id || element.name;
  11391. if ( element.inputType ) {
  11392. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  11393. this.getParameter( id ).inputType = element.inputType;
  11394. }
  11395. if ( element.outputType ) {
  11396. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  11397. this.getOutput( id ).outputType = element.outputType;
  11398. }
  11399. }
  11400. }
  11401. }
  11402. return this._object;
  11403. }
  11404. deserialize( data ) {
  11405. super.deserialize( data );
  11406. for ( const name in this.parameters ) {
  11407. let valueNode = this.parameters[ name ];
  11408. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  11409. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  11410. }
  11411. }
  11412. getLayout() {
  11413. return this.getObject().layout;
  11414. }
  11415. getDefaultOutputNode() {
  11416. const output = this.getDefaultOutput().value;
  11417. if ( output && output.isNode ) {
  11418. return output;
  11419. }
  11420. return float();
  11421. }
  11422. getDefaultOutput() {
  11423. return this._exec()._output;
  11424. }
  11425. getMethod() {
  11426. if ( this.needsUpdate ) this.dispose();
  11427. if ( this._method !== null ) return this._method;
  11428. //
  11429. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  11430. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  11431. const properties = interfaceProps.join( ', ' );
  11432. const declarations = 'var ' + properties + '; var output = {};\n';
  11433. const returns = '\nreturn { ...output, ' + properties + ' };';
  11434. const code = declarations + this.codeNode.code + returns;
  11435. //
  11436. this._method = new Function( ...parametersProps, code );
  11437. return this._method;
  11438. }
  11439. dispose() {
  11440. if ( this._method === null ) return;
  11441. if ( this._object && typeof this._object.dispose === 'function' ) {
  11442. this._object.dispose();
  11443. }
  11444. this._method = null;
  11445. this._object = null;
  11446. this._source = null;
  11447. this._value = null;
  11448. this._needsOutputUpdate = true;
  11449. this._output.value = null;
  11450. this._outputs = {};
  11451. }
  11452. setup() {
  11453. return this.getDefaultOutputNode();
  11454. }
  11455. getCacheKey( force ) {
  11456. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  11457. for ( const param in this.parameters ) {
  11458. values.push( this.parameters[ param ].getCacheKey( force ) );
  11459. }
  11460. return hashArray( values );
  11461. }
  11462. set needsUpdate( value ) {
  11463. if ( value === true ) this.dispose();
  11464. }
  11465. get needsUpdate() {
  11466. return this.source !== this._source;
  11467. }
  11468. _exec() {
  11469. if ( this.codeNode === null ) return this;
  11470. if ( this._needsOutputUpdate === true ) {
  11471. this._value = this.call( 'main' );
  11472. this._needsOutputUpdate = false;
  11473. }
  11474. this._output.value = this._value;
  11475. return this;
  11476. }
  11477. _refresh() {
  11478. this.needsUpdate = true;
  11479. this._exec();
  11480. this._output.refresh();
  11481. }
  11482. }
  11483. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  11484. class FogNode extends Node {
  11485. static get type() {
  11486. return 'FogNode';
  11487. }
  11488. constructor( colorNode, factorNode ) {
  11489. super( 'float' );
  11490. this.isFogNode = true;
  11491. this.colorNode = colorNode;
  11492. this.factorNode = factorNode;
  11493. }
  11494. getViewZNode( builder ) {
  11495. let viewZ;
  11496. const getViewZ = builder.context.getViewZ;
  11497. if ( getViewZ !== undefined ) {
  11498. viewZ = getViewZ( this );
  11499. }
  11500. return ( viewZ || positionView.z ).negate();
  11501. }
  11502. setup() {
  11503. return this.factorNode;
  11504. }
  11505. }
  11506. const fog = /*@__PURE__*/ nodeProxy( FogNode );
  11507. class FogRangeNode extends FogNode {
  11508. static get type() {
  11509. return 'FogRangeNode';
  11510. }
  11511. constructor( colorNode, nearNode, farNode ) {
  11512. super( colorNode );
  11513. this.isFogRangeNode = true;
  11514. this.nearNode = nearNode;
  11515. this.farNode = farNode;
  11516. }
  11517. setup( builder ) {
  11518. const viewZ = this.getViewZNode( builder );
  11519. return smoothstep( this.nearNode, this.farNode, viewZ );
  11520. }
  11521. }
  11522. const rangeFog = /*@__PURE__*/ nodeProxy( FogRangeNode );
  11523. class FogExp2Node extends FogNode {
  11524. static get type() {
  11525. return 'FogExp2Node';
  11526. }
  11527. constructor( colorNode, densityNode ) {
  11528. super( colorNode );
  11529. this.isFogExp2Node = true;
  11530. this.densityNode = densityNode;
  11531. }
  11532. setup( builder ) {
  11533. const viewZ = this.getViewZNode( builder );
  11534. const density = this.densityNode;
  11535. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  11536. }
  11537. }
  11538. const densityFog = /*@__PURE__*/ nodeProxy( FogExp2Node );
  11539. let min = null;
  11540. let max = null;
  11541. class RangeNode extends Node {
  11542. static get type() {
  11543. return 'RangeNode';
  11544. }
  11545. constructor( minNode = float(), maxNode = float() ) {
  11546. super();
  11547. this.minNode = minNode;
  11548. this.maxNode = maxNode;
  11549. }
  11550. getVectorLength( builder ) {
  11551. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  11552. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  11553. return minLength > maxLength ? minLength : maxLength;
  11554. }
  11555. getNodeType( builder ) {
  11556. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  11557. }
  11558. setup( builder ) {
  11559. const object = builder.object;
  11560. let output = null;
  11561. if ( object.count > 1 ) {
  11562. const minValue = this.minNode.value;
  11563. const maxValue = this.maxNode.value;
  11564. const minLength = builder.getTypeLength( getValueType( minValue ) );
  11565. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  11566. min = min || new Vector4();
  11567. max = max || new Vector4();
  11568. min.setScalar( 0 );
  11569. max.setScalar( 0 );
  11570. if ( minLength === 1 ) min.setScalar( minValue );
  11571. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b );
  11572. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  11573. if ( maxLength === 1 ) max.setScalar( maxValue );
  11574. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b );
  11575. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  11576. const stride = 4;
  11577. const length = stride * object.count;
  11578. const array = new Float32Array( length );
  11579. for ( let i = 0; i < length; i ++ ) {
  11580. const index = i % stride;
  11581. const minElementValue = min.getComponent( index );
  11582. const maxElementValue = max.getComponent( index );
  11583. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  11584. }
  11585. const nodeType = this.getNodeType( builder );
  11586. if ( object.count <= 4096 ) {
  11587. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  11588. } else {
  11589. // TODO: Improve anonymous buffer attribute creation removing this part
  11590. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  11591. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  11592. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  11593. }
  11594. } else {
  11595. output = float( 0 );
  11596. }
  11597. return output;
  11598. }
  11599. }
  11600. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  11601. class ComputeBuiltinNode extends Node {
  11602. static get type() {
  11603. return 'ComputeBuiltinNode';
  11604. }
  11605. constructor( builtinName, nodeType ) {
  11606. super( nodeType );
  11607. this._builtinName = builtinName;
  11608. }
  11609. getHash( builder ) {
  11610. return this.getBuiltinName( builder );
  11611. }
  11612. getNodeType( /*builder*/ ) {
  11613. return this.nodeType;
  11614. }
  11615. setBuiltinName( builtinName ) {
  11616. this._builtinName = builtinName;
  11617. return this;
  11618. }
  11619. getBuiltinName( /*builder*/ ) {
  11620. return this._builtinName;
  11621. }
  11622. hasBuiltin( builder ) {
  11623. builder.hasBuiltin( this._builtinName );
  11624. }
  11625. generate( builder, output ) {
  11626. const builtinName = this.getBuiltinName( builder );
  11627. const nodeType = this.getNodeType( builder );
  11628. if ( builder.shaderStage === 'compute' ) {
  11629. return builder.format( builtinName, nodeType, output );
  11630. } else {
  11631. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  11632. return builder.generateConst( nodeType );
  11633. }
  11634. }
  11635. serialize( data ) {
  11636. super.serialize( data );
  11637. data.global = this.global;
  11638. data._builtinName = this._builtinName;
  11639. }
  11640. deserialize( data ) {
  11641. super.deserialize( data );
  11642. this.global = data.global;
  11643. this._builtinName = data._builtinName;
  11644. }
  11645. }
  11646. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  11647. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  11648. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  11649. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  11650. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  11651. class BarrierNode extends Node {
  11652. constructor( scope ) {
  11653. super();
  11654. this.scope = scope;
  11655. }
  11656. generate( builder ) {
  11657. const { scope } = this;
  11658. const { renderer } = builder;
  11659. if ( renderer.backend.isWebGLBackend === true ) {
  11660. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  11661. } else {
  11662. builder.addLineFlowCode( `${scope}Barrier()`, this );
  11663. }
  11664. }
  11665. }
  11666. const barrier = nodeProxy( BarrierNode );
  11667. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  11668. const storageBarrier = () => barrier( 'storage' ).append();
  11669. const textureBarrier = () => barrier( 'texture' ).append();
  11670. class WorkgroupInfoElementNode extends ArrayElementNode {
  11671. constructor( workgroupInfoNode, indexNode ) {
  11672. super( workgroupInfoNode, indexNode );
  11673. this.isWorkgroupInfoElementNode = true;
  11674. }
  11675. generate( builder, output ) {
  11676. let snippet;
  11677. const isAssignContext = builder.context.assign;
  11678. snippet = super.generate( builder );
  11679. if ( isAssignContext !== true ) {
  11680. const type = this.getNodeType( builder );
  11681. snippet = builder.format( snippet, type, output );
  11682. }
  11683. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  11684. return snippet;
  11685. }
  11686. }
  11687. class WorkgroupInfoNode extends Node {
  11688. constructor( scope, bufferType, bufferCount = 0 ) {
  11689. super( bufferType );
  11690. this.bufferType = bufferType;
  11691. this.bufferCount = bufferCount;
  11692. this.isWorkgroupInfoNode = true;
  11693. this.scope = scope;
  11694. }
  11695. label( name ) {
  11696. this.name = name;
  11697. return this;
  11698. }
  11699. getHash() {
  11700. return this.uuid;
  11701. }
  11702. setScope( scope ) {
  11703. this.scope = scope;
  11704. return this;
  11705. }
  11706. getInputType( /*builder*/ ) {
  11707. return `${this.scope}Array`;
  11708. }
  11709. element( indexNode ) {
  11710. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  11711. }
  11712. generate( builder ) {
  11713. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  11714. }
  11715. }
  11716. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  11717. class AtomicFunctionNode extends TempNode {
  11718. static get type() {
  11719. return 'AtomicFunctionNode';
  11720. }
  11721. constructor( method, pointerNode, valueNode, storeNode = null ) {
  11722. super( 'uint' );
  11723. this.method = method;
  11724. this.pointerNode = pointerNode;
  11725. this.valueNode = valueNode;
  11726. this.storeNode = storeNode;
  11727. }
  11728. getInputType( builder ) {
  11729. return this.pointerNode.getNodeType( builder );
  11730. }
  11731. getNodeType( builder ) {
  11732. return this.getInputType( builder );
  11733. }
  11734. generate( builder ) {
  11735. const method = this.method;
  11736. const type = this.getNodeType( builder );
  11737. const inputType = this.getInputType( builder );
  11738. const a = this.pointerNode;
  11739. const b = this.valueNode;
  11740. const params = [];
  11741. params.push( `&${ a.build( builder, inputType ) }` );
  11742. params.push( b.build( builder, inputType ) );
  11743. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  11744. if ( this.storeNode !== null ) {
  11745. const varSnippet = this.storeNode.build( builder, inputType );
  11746. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this );
  11747. } else {
  11748. builder.addLineFlowCode( methodSnippet, this );
  11749. }
  11750. }
  11751. }
  11752. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  11753. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  11754. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  11755. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  11756. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  11757. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  11758. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  11759. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  11760. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  11761. const atomicNode = nodeProxy( AtomicFunctionNode );
  11762. const atomicFunc = ( method, pointerNode, valueNode, storeNode ) => {
  11763. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  11764. node.append();
  11765. return node;
  11766. };
  11767. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  11768. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  11769. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  11770. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  11771. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  11772. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  11773. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  11774. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  11775. let uniformsLib;
  11776. function getLightData( light ) {
  11777. uniformsLib = uniformsLib || new WeakMap();
  11778. let uniforms = uniformsLib.get( light );
  11779. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  11780. return uniforms;
  11781. }
  11782. function lightPosition( light ) {
  11783. const data = getLightData( light );
  11784. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  11785. }
  11786. function lightTargetPosition( light ) {
  11787. const data = getLightData( light );
  11788. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  11789. }
  11790. function lightViewPosition( light ) {
  11791. const data = getLightData( light );
  11792. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  11793. self.value = self.value || new Vector3();
  11794. self.value.setFromMatrixPosition( light.matrixWorld );
  11795. self.value.applyMatrix4( camera.matrixWorldInverse );
  11796. } ) );
  11797. }
  11798. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  11799. const sortLights = ( lights ) => {
  11800. return lights.sort( ( a, b ) => a.id - b.id );
  11801. };
  11802. const getLightNodeById = ( id, lightNodes ) => {
  11803. for ( const lightNode of lightNodes ) {
  11804. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  11805. return lightNode;
  11806. }
  11807. }
  11808. return null;
  11809. };
  11810. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  11811. class LightsNode extends Node {
  11812. static get type() {
  11813. return 'LightsNode';
  11814. }
  11815. constructor() {
  11816. super( 'vec3' );
  11817. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  11818. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  11819. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  11820. this._lights = [];
  11821. this._lightNodes = null;
  11822. this._lightNodesHash = null;
  11823. this.global = true;
  11824. }
  11825. getHash( builder ) {
  11826. if ( this._lightNodesHash === null ) {
  11827. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  11828. const hash = [];
  11829. for ( const lightNode of this._lightNodes ) {
  11830. hash.push( lightNode.getSelf().getHash() );
  11831. }
  11832. this._lightNodesHash = 'lights-' + hash.join( ',' );
  11833. }
  11834. return this._lightNodesHash;
  11835. }
  11836. analyze( builder ) {
  11837. const properties = builder.getDataFromNode( this );
  11838. for ( const node of properties.nodes ) {
  11839. node.build( builder );
  11840. }
  11841. }
  11842. setupLightsNode( builder ) {
  11843. const lightNodes = [];
  11844. const previousLightNodes = this._lightNodes;
  11845. const lights = sortLights( this._lights );
  11846. const nodeLibrary = builder.renderer.library;
  11847. for ( const light of lights ) {
  11848. if ( light.isNode ) {
  11849. lightNodes.push( nodeObject( light ) );
  11850. } else {
  11851. let lightNode = null;
  11852. if ( previousLightNodes !== null ) {
  11853. lightNode = getLightNodeById( light.id, previousLightNodes ); // resuse existing light node
  11854. }
  11855. if ( lightNode === null ) {
  11856. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  11857. if ( lightNodeClass === null ) {
  11858. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  11859. continue;
  11860. }
  11861. let lightNode = null;
  11862. if ( ! _lightsNodeRef.has( light ) ) {
  11863. lightNode = nodeObject( new lightNodeClass( light ) );
  11864. _lightsNodeRef.set( light, lightNode );
  11865. } else {
  11866. lightNode = _lightsNodeRef.get( light );
  11867. }
  11868. lightNodes.push( lightNode );
  11869. }
  11870. }
  11871. }
  11872. this._lightNodes = lightNodes;
  11873. }
  11874. setupLights( builder, lightNodes ) {
  11875. for ( const lightNode of lightNodes ) {
  11876. lightNode.build( builder );
  11877. }
  11878. }
  11879. setup( builder ) {
  11880. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  11881. const context = builder.context;
  11882. const lightingModel = context.lightingModel;
  11883. let outgoingLightNode = this.outgoingLightNode;
  11884. if ( lightingModel ) {
  11885. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  11886. context.outgoingLight = outgoingLightNode;
  11887. const stack = builder.addStack();
  11888. //
  11889. const properties = builder.getDataFromNode( this );
  11890. properties.nodes = stack.nodes;
  11891. //
  11892. lightingModel.start( context, stack, builder );
  11893. // lights
  11894. this.setupLights( builder, _lightNodes );
  11895. //
  11896. lightingModel.indirect( context, stack, builder );
  11897. //
  11898. const { backdrop, backdropAlpha } = context;
  11899. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  11900. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  11901. if ( backdrop !== null ) {
  11902. if ( backdropAlpha !== null ) {
  11903. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  11904. } else {
  11905. totalDiffuse = vec3( backdrop );
  11906. }
  11907. context.material.transparent = true;
  11908. }
  11909. totalDiffuseNode.assign( totalDiffuse );
  11910. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  11911. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  11912. //
  11913. lightingModel.finish( context, stack, builder );
  11914. //
  11915. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  11916. }
  11917. return outgoingLightNode;
  11918. }
  11919. setLights( lights ) {
  11920. this._lights = lights;
  11921. this._lightNodes = null;
  11922. this._lightNodesHash = null;
  11923. return this;
  11924. }
  11925. getLights() {
  11926. return this._lights;
  11927. }
  11928. get hasLights() {
  11929. return this._lights.length > 0;
  11930. }
  11931. }
  11932. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  11933. const BasicShadowMap = Fn( ( { depthTexture, shadowCoord } ) => {
  11934. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  11935. } );
  11936. const PCFShadowMap = Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  11937. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  11938. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  11939. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  11940. const texelSize = vec2( 1 ).div( mapSize );
  11941. const dx0 = texelSize.x.negate().mul( radius );
  11942. const dy0 = texelSize.y.negate().mul( radius );
  11943. const dx1 = texelSize.x.mul( radius );
  11944. const dy1 = texelSize.y.mul( radius );
  11945. const dx2 = dx0.div( 2 );
  11946. const dy2 = dy0.div( 2 );
  11947. const dx3 = dx1.div( 2 );
  11948. const dy3 = dy1.div( 2 );
  11949. return add(
  11950. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  11951. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  11952. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  11953. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  11954. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  11955. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  11956. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  11957. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  11958. depthCompare( shadowCoord.xy, shadowCoord.z ),
  11959. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  11960. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  11961. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  11962. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  11963. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  11964. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  11965. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  11966. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  11967. ).mul( 1 / 17 );
  11968. } );
  11969. const PCFSoftShadowMap = Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  11970. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  11971. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  11972. const texelSize = vec2( 1 ).div( mapSize );
  11973. const dx = texelSize.x;
  11974. const dy = texelSize.y;
  11975. const uv = shadowCoord.xy;
  11976. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  11977. uv.subAssign( f.mul( texelSize ) );
  11978. return add(
  11979. depthCompare( uv, shadowCoord.z ),
  11980. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  11981. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  11982. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  11983. mix(
  11984. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  11985. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  11986. f.x
  11987. ),
  11988. mix(
  11989. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  11990. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  11991. f.x
  11992. ),
  11993. mix(
  11994. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  11995. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  11996. f.y
  11997. ),
  11998. mix(
  11999. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  12000. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  12001. f.y
  12002. ),
  12003. mix(
  12004. mix(
  12005. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  12006. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  12007. f.x
  12008. ),
  12009. mix(
  12010. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  12011. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  12012. f.x
  12013. ),
  12014. f.y
  12015. )
  12016. ).mul( 1 / 9 );
  12017. } );
  12018. // VSM
  12019. const VSMShadowMapNode = Fn( ( { depthTexture, shadowCoord } ) => {
  12020. const occlusion = float( 1 ).toVar();
  12021. const distribution = texture( depthTexture ).uv( shadowCoord.xy ).rg;
  12022. const hardShadow = step( shadowCoord.z, distribution.x );
  12023. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  12024. const distance = shadowCoord.z.sub( distribution.x );
  12025. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  12026. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  12027. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  12028. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  12029. } );
  12030. return occlusion;
  12031. } );
  12032. const VSMPassVertical = Fn( ( { samples, radius, size, shadowPass } ) => {
  12033. const mean = float( 0 ).toVar();
  12034. const squaredMean = float( 0 ).toVar();
  12035. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  12036. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  12037. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  12038. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  12039. const depth = shadowPass.uv( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  12040. mean.addAssign( depth );
  12041. squaredMean.addAssign( depth.mul( depth ) );
  12042. } );
  12043. mean.divAssign( samples );
  12044. squaredMean.divAssign( samples );
  12045. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  12046. return vec2( mean, std_dev );
  12047. } );
  12048. const VSMPassHorizontal = Fn( ( { samples, radius, size, shadowPass } ) => {
  12049. const mean = float( 0 ).toVar();
  12050. const squaredMean = float( 0 ).toVar();
  12051. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  12052. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  12053. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  12054. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  12055. const distribution = shadowPass.uv( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  12056. mean.addAssign( distribution.x );
  12057. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  12058. } );
  12059. mean.divAssign( samples );
  12060. squaredMean.divAssign( samples );
  12061. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  12062. return vec2( mean, std_dev );
  12063. } );
  12064. const _shadowFilterLib = [ BasicShadowMap, PCFShadowMap, PCFSoftShadowMap, VSMShadowMapNode ];
  12065. //
  12066. let _overrideMaterial = null;
  12067. const _quadMesh$1 = /*@__PURE__*/ new QuadMesh();
  12068. class ShadowNode extends Node {
  12069. static get type() {
  12070. return 'ShadowNode';
  12071. }
  12072. constructor( light, shadow = null ) {
  12073. super();
  12074. this.light = light;
  12075. this.shadow = shadow || light.shadow;
  12076. this.shadowMap = null;
  12077. this.vsmShadowMapVertical = null;
  12078. this.vsmShadowMapHorizontal = null;
  12079. this.vsmMaterialVertical = null;
  12080. this.vsmMaterialHorizontal = null;
  12081. this.updateBeforeType = NodeUpdateType.RENDER;
  12082. this._node = null;
  12083. this.isShadowNode = true;
  12084. }
  12085. setupShadow( builder ) {
  12086. const { object, renderer } = builder;
  12087. if ( _overrideMaterial === null ) {
  12088. _overrideMaterial = new NodeMaterial();
  12089. _overrideMaterial.fragmentNode = vec4( 0, 0, 0, 1 );
  12090. _overrideMaterial.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.fragmentNode unintentionally when using material.shadowNode
  12091. _overrideMaterial.name = 'ShadowMaterial';
  12092. }
  12093. const shadow = this.shadow;
  12094. const shadowMapType = renderer.shadowMap.type;
  12095. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  12096. depthTexture.compareFunction = LessCompare;
  12097. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  12098. shadowMap.depthTexture = depthTexture;
  12099. shadow.camera.updateProjectionMatrix();
  12100. // VSM
  12101. if ( shadowMapType === VSMShadowMap ) {
  12102. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  12103. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  12104. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  12105. const shadowPassVertical = texture( depthTexture );
  12106. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  12107. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  12108. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  12109. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  12110. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  12111. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  12112. material.name = 'VSMVertical';
  12113. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  12114. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  12115. material.name = 'VSMHorizontal';
  12116. }
  12117. //
  12118. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  12119. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  12120. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  12121. const position = object.material.shadowPositionNode || positionWorld;
  12122. let shadowCoord = uniform( shadow.matrix ).setGroup( renderGroup ).mul( position.add( transformedNormalWorld.mul( normalBias ) ) );
  12123. let coordZ;
  12124. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  12125. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  12126. coordZ = shadowCoord.z;
  12127. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  12128. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  12129. }
  12130. } else {
  12131. const w = shadowCoord.w;
  12132. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  12133. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  12134. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  12135. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  12136. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  12137. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  12138. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  12139. }
  12140. shadowCoord = vec3(
  12141. shadowCoord.x,
  12142. shadowCoord.y.oneMinus(), // follow webgpu standards
  12143. coordZ.add( bias )
  12144. );
  12145. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  12146. .and( shadowCoord.x.lessThanEqual( 1 ) )
  12147. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  12148. .and( shadowCoord.y.lessThanEqual( 1 ) )
  12149. .and( shadowCoord.z.lessThanEqual( 1 ) );
  12150. //
  12151. const filterFn = shadow.filterNode || _shadowFilterLib[ renderer.shadowMap.type ] || null;
  12152. if ( filterFn === null ) {
  12153. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  12154. }
  12155. const shadowColor = texture( shadowMap.texture, shadowCoord );
  12156. const shadowNode = frustumTest.select( filterFn( { depthTexture: ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture, shadowCoord, shadow } ), float( 1 ) );
  12157. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  12158. this.shadowMap = shadowMap;
  12159. this.shadow.map = shadowMap;
  12160. return shadowOutput;
  12161. }
  12162. setup( builder ) {
  12163. if ( builder.renderer.shadowMap.enabled === false ) return;
  12164. let node = this._node;
  12165. if ( node === null ) {
  12166. this._node = node = this.setupShadow( builder );
  12167. }
  12168. if ( builder.material.shadowNode ) { // @deprecated, r171
  12169. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  12170. }
  12171. if ( builder.material.receivedShadowNode ) {
  12172. node = builder.material.receivedShadowNode( node );
  12173. }
  12174. return node;
  12175. }
  12176. updateShadow( frame ) {
  12177. const { shadowMap, light, shadow } = this;
  12178. const { renderer, scene, camera } = frame;
  12179. const shadowType = renderer.shadowMap.type;
  12180. const depthVersion = shadowMap.depthTexture.version;
  12181. this._depthVersionCached = depthVersion;
  12182. const currentOverrideMaterial = scene.overrideMaterial;
  12183. scene.overrideMaterial = _overrideMaterial;
  12184. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  12185. shadow.updateMatrices( light );
  12186. shadow.camera.layers.mask = camera.layers.mask;
  12187. const currentRenderTarget = renderer.getRenderTarget();
  12188. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  12189. renderer.setRenderObjectFunction( ( object, ...params ) => {
  12190. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  12191. renderer.renderObject( object, ...params );
  12192. }
  12193. } );
  12194. renderer.setRenderTarget( shadowMap );
  12195. renderer.render( scene, shadow.camera );
  12196. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  12197. // vsm blur pass
  12198. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  12199. this.vsmPass( renderer );
  12200. }
  12201. renderer.setRenderTarget( currentRenderTarget );
  12202. scene.overrideMaterial = currentOverrideMaterial;
  12203. }
  12204. vsmPass( renderer ) {
  12205. const { shadow } = this;
  12206. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  12207. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  12208. renderer.setRenderTarget( this.vsmShadowMapVertical );
  12209. _quadMesh$1.material = this.vsmMaterialVertical;
  12210. _quadMesh$1.render( renderer );
  12211. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  12212. _quadMesh$1.material = this.vsmMaterialHorizontal;
  12213. _quadMesh$1.render( renderer );
  12214. }
  12215. dispose() {
  12216. this.shadowMap.dispose();
  12217. this.shadowMap = null;
  12218. if ( this.vsmShadowMapVertical !== null ) {
  12219. this.vsmShadowMapVertical.dispose();
  12220. this.vsmShadowMapVertical = null;
  12221. this.vsmMaterialVertical.dispose();
  12222. this.vsmMaterialVertical = null;
  12223. }
  12224. if ( this.vsmShadowMapHorizontal !== null ) {
  12225. this.vsmShadowMapHorizontal.dispose();
  12226. this.vsmShadowMapHorizontal = null;
  12227. this.vsmMaterialHorizontal.dispose();
  12228. this.vsmMaterialHorizontal = null;
  12229. }
  12230. this.updateBeforeType = NodeUpdateType.NONE;
  12231. }
  12232. updateBefore( frame ) {
  12233. const { shadow } = this;
  12234. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  12235. if ( needsUpdate ) {
  12236. this.updateShadow( frame );
  12237. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  12238. shadow.needsUpdate = false;
  12239. }
  12240. }
  12241. }
  12242. }
  12243. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  12244. class AnalyticLightNode extends LightingNode {
  12245. static get type() {
  12246. return 'AnalyticLightNode';
  12247. }
  12248. constructor( light = null ) {
  12249. super();
  12250. this.updateType = NodeUpdateType.FRAME;
  12251. this.light = light;
  12252. this.color = new Color();
  12253. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  12254. this.baseColorNode = null;
  12255. this.shadowNode = null;
  12256. this.shadowColorNode = null;
  12257. this.isAnalyticLightNode = true;
  12258. }
  12259. getCacheKey() {
  12260. return hash$1( super.getCacheKey(), this.light.id, this.light.castShadow ? 1 : 0 );
  12261. }
  12262. getHash() {
  12263. return this.light.uuid;
  12264. }
  12265. setupShadow( builder ) {
  12266. const { renderer } = builder;
  12267. if ( renderer.shadowMap.enabled === false ) return;
  12268. let shadowColorNode = this.shadowColorNode;
  12269. if ( shadowColorNode === null ) {
  12270. const customShadowNode = this.light.shadow.shadowNode;
  12271. let shadowNode;
  12272. if ( customShadowNode !== undefined ) {
  12273. shadowNode = nodeObject( customShadowNode );
  12274. } else {
  12275. shadowNode = shadow( this.light );
  12276. }
  12277. this.shadowNode = shadowNode;
  12278. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  12279. this.baseColorNode = this.colorNode;
  12280. }
  12281. //
  12282. this.colorNode = shadowColorNode;
  12283. }
  12284. setup( builder ) {
  12285. this.colorNode = this.baseColorNode || this.colorNode;
  12286. if ( this.light.castShadow ) {
  12287. if ( builder.object.receiveShadow ) {
  12288. this.setupShadow( builder );
  12289. }
  12290. } else if ( this.shadowNode !== null ) {
  12291. this.shadowNode.dispose();
  12292. }
  12293. }
  12294. update( /*frame*/ ) {
  12295. const { light } = this;
  12296. this.color.copy( light.color ).multiplyScalar( light.intensity );
  12297. }
  12298. }
  12299. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  12300. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  12301. // based upon Frostbite 3 Moving to Physically-based Rendering
  12302. // page 32, equation 26: E[window1]
  12303. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  12304. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  12305. return cutoffDistance.greaterThan( 0 ).select(
  12306. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  12307. distanceFalloff
  12308. );
  12309. } ); // validated
  12310. const directPointLight = Fn( ( { color, lightViewPosition, cutoffDistance, decayExponent }, builder ) => {
  12311. const lightingModel = builder.context.lightingModel;
  12312. const lVector = lightViewPosition.sub( positionView ); // @TODO: Add it into LightNode
  12313. const lightDirection = lVector.normalize();
  12314. const lightDistance = lVector.length();
  12315. const lightAttenuation = getDistanceAttenuation( {
  12316. lightDistance,
  12317. cutoffDistance,
  12318. decayExponent
  12319. } );
  12320. const lightColor = color.mul( lightAttenuation );
  12321. const reflectedLight = builder.context.reflectedLight;
  12322. lightingModel.direct( {
  12323. lightDirection,
  12324. lightColor,
  12325. reflectedLight
  12326. }, builder.stack, builder );
  12327. } );
  12328. class PointLightNode extends AnalyticLightNode {
  12329. static get type() {
  12330. return 'PointLightNode';
  12331. }
  12332. constructor( light = null ) {
  12333. super( light );
  12334. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  12335. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  12336. }
  12337. update( frame ) {
  12338. const { light } = this;
  12339. super.update( frame );
  12340. this.cutoffDistanceNode.value = light.distance;
  12341. this.decayExponentNode.value = light.decay;
  12342. }
  12343. setup() {
  12344. directPointLight( {
  12345. color: this.colorNode,
  12346. lightViewPosition: lightViewPosition( this.light ),
  12347. cutoffDistance: this.cutoffDistanceNode,
  12348. decayExponent: this.decayExponentNode
  12349. } ).append();
  12350. }
  12351. }
  12352. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  12353. const uv = coord.mul( 2.0 );
  12354. const cx = uv.x.floor();
  12355. const cy = uv.y.floor();
  12356. const result = cx.add( cy ).mod( 2.0 );
  12357. return result.sign();
  12358. } );
  12359. // Three.js Transpiler
  12360. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  12361. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  12362. const f = float( f_immutable ).toVar();
  12363. const t = float( t_immutable ).toVar();
  12364. const b = bool( b_immutable ).toVar();
  12365. return select( b, t, f );
  12366. } ).setLayout( {
  12367. name: 'mx_select',
  12368. type: 'float',
  12369. inputs: [
  12370. { name: 'b', type: 'bool' },
  12371. { name: 't', type: 'float' },
  12372. { name: 'f', type: 'float' }
  12373. ]
  12374. } );
  12375. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  12376. const b = bool( b_immutable ).toVar();
  12377. const val = float( val_immutable ).toVar();
  12378. return select( b, val.negate(), val );
  12379. } ).setLayout( {
  12380. name: 'mx_negate_if',
  12381. type: 'float',
  12382. inputs: [
  12383. { name: 'val', type: 'float' },
  12384. { name: 'b', type: 'bool' }
  12385. ]
  12386. } );
  12387. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  12388. const x = float( x_immutable ).toVar();
  12389. return int( floor( x ) );
  12390. } ).setLayout( {
  12391. name: 'mx_floor',
  12392. type: 'int',
  12393. inputs: [
  12394. { name: 'x', type: 'float' }
  12395. ]
  12396. } );
  12397. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  12398. const x = float( x_immutable ).toVar();
  12399. i.assign( mx_floor( x ) );
  12400. return x.sub( float( i ) );
  12401. } );
  12402. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  12403. const t = float( t_immutable ).toVar();
  12404. const s = float( s_immutable ).toVar();
  12405. const v3 = float( v3_immutable ).toVar();
  12406. const v2 = float( v2_immutable ).toVar();
  12407. const v1 = float( v1_immutable ).toVar();
  12408. const v0 = float( v0_immutable ).toVar();
  12409. const s1 = float( sub( 1.0, s ) ).toVar();
  12410. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  12411. } ).setLayout( {
  12412. name: 'mx_bilerp_0',
  12413. type: 'float',
  12414. inputs: [
  12415. { name: 'v0', type: 'float' },
  12416. { name: 'v1', type: 'float' },
  12417. { name: 'v2', type: 'float' },
  12418. { name: 'v3', type: 'float' },
  12419. { name: 's', type: 'float' },
  12420. { name: 't', type: 'float' }
  12421. ]
  12422. } );
  12423. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  12424. const t = float( t_immutable ).toVar();
  12425. const s = float( s_immutable ).toVar();
  12426. const v3 = vec3( v3_immutable ).toVar();
  12427. const v2 = vec3( v2_immutable ).toVar();
  12428. const v1 = vec3( v1_immutable ).toVar();
  12429. const v0 = vec3( v0_immutable ).toVar();
  12430. const s1 = float( sub( 1.0, s ) ).toVar();
  12431. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  12432. } ).setLayout( {
  12433. name: 'mx_bilerp_1',
  12434. type: 'vec3',
  12435. inputs: [
  12436. { name: 'v0', type: 'vec3' },
  12437. { name: 'v1', type: 'vec3' },
  12438. { name: 'v2', type: 'vec3' },
  12439. { name: 'v3', type: 'vec3' },
  12440. { name: 's', type: 'float' },
  12441. { name: 't', type: 'float' }
  12442. ]
  12443. } );
  12444. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  12445. 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 ] ) => {
  12446. const r = float( r_immutable ).toVar();
  12447. const t = float( t_immutable ).toVar();
  12448. const s = float( s_immutable ).toVar();
  12449. const v7 = float( v7_immutable ).toVar();
  12450. const v6 = float( v6_immutable ).toVar();
  12451. const v5 = float( v5_immutable ).toVar();
  12452. const v4 = float( v4_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. const t1 = float( sub( 1.0, t ) ).toVar();
  12459. const r1 = float( sub( 1.0, r ) ).toVar();
  12460. 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 ) ) ) ) ) );
  12461. } ).setLayout( {
  12462. name: 'mx_trilerp_0',
  12463. type: 'float',
  12464. inputs: [
  12465. { name: 'v0', type: 'float' },
  12466. { name: 'v1', type: 'float' },
  12467. { name: 'v2', type: 'float' },
  12468. { name: 'v3', type: 'float' },
  12469. { name: 'v4', type: 'float' },
  12470. { name: 'v5', type: 'float' },
  12471. { name: 'v6', type: 'float' },
  12472. { name: 'v7', type: 'float' },
  12473. { name: 's', type: 'float' },
  12474. { name: 't', type: 'float' },
  12475. { name: 'r', type: 'float' }
  12476. ]
  12477. } );
  12478. 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 ] ) => {
  12479. const r = float( r_immutable ).toVar();
  12480. const t = float( t_immutable ).toVar();
  12481. const s = float( s_immutable ).toVar();
  12482. const v7 = vec3( v7_immutable ).toVar();
  12483. const v6 = vec3( v6_immutable ).toVar();
  12484. const v5 = vec3( v5_immutable ).toVar();
  12485. const v4 = vec3( v4_immutable ).toVar();
  12486. const v3 = vec3( v3_immutable ).toVar();
  12487. const v2 = vec3( v2_immutable ).toVar();
  12488. const v1 = vec3( v1_immutable ).toVar();
  12489. const v0 = vec3( v0_immutable ).toVar();
  12490. const s1 = float( sub( 1.0, s ) ).toVar();
  12491. const t1 = float( sub( 1.0, t ) ).toVar();
  12492. const r1 = float( sub( 1.0, r ) ).toVar();
  12493. 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 ) ) ) ) ) );
  12494. } ).setLayout( {
  12495. name: 'mx_trilerp_1',
  12496. type: 'vec3',
  12497. inputs: [
  12498. { name: 'v0', type: 'vec3' },
  12499. { name: 'v1', type: 'vec3' },
  12500. { name: 'v2', type: 'vec3' },
  12501. { name: 'v3', type: 'vec3' },
  12502. { name: 'v4', type: 'vec3' },
  12503. { name: 'v5', type: 'vec3' },
  12504. { name: 'v6', type: 'vec3' },
  12505. { name: 'v7', type: 'vec3' },
  12506. { name: 's', type: 'float' },
  12507. { name: 't', type: 'float' },
  12508. { name: 'r', type: 'float' }
  12509. ]
  12510. } );
  12511. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  12512. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  12513. const y = float( y_immutable ).toVar();
  12514. const x = float( x_immutable ).toVar();
  12515. const hash = uint( hash_immutable ).toVar();
  12516. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  12517. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  12518. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  12519. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  12520. } ).setLayout( {
  12521. name: 'mx_gradient_float_0',
  12522. type: 'float',
  12523. inputs: [
  12524. { name: 'hash', type: 'uint' },
  12525. { name: 'x', type: 'float' },
  12526. { name: 'y', type: 'float' }
  12527. ]
  12528. } );
  12529. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  12530. const z = float( z_immutable ).toVar();
  12531. const y = float( y_immutable ).toVar();
  12532. const x = float( x_immutable ).toVar();
  12533. const hash = uint( hash_immutable ).toVar();
  12534. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  12535. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  12536. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  12537. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  12538. } ).setLayout( {
  12539. name: 'mx_gradient_float_1',
  12540. type: 'float',
  12541. inputs: [
  12542. { name: 'hash', type: 'uint' },
  12543. { name: 'x', type: 'float' },
  12544. { name: 'y', type: 'float' },
  12545. { name: 'z', type: 'float' }
  12546. ]
  12547. } );
  12548. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  12549. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  12550. const y = float( y_immutable ).toVar();
  12551. const x = float( x_immutable ).toVar();
  12552. const hash = uvec3( hash_immutable ).toVar();
  12553. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  12554. } ).setLayout( {
  12555. name: 'mx_gradient_vec3_0',
  12556. type: 'vec3',
  12557. inputs: [
  12558. { name: 'hash', type: 'uvec3' },
  12559. { name: 'x', type: 'float' },
  12560. { name: 'y', type: 'float' }
  12561. ]
  12562. } );
  12563. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  12564. const z = float( z_immutable ).toVar();
  12565. const y = float( y_immutable ).toVar();
  12566. const x = float( x_immutable ).toVar();
  12567. const hash = uvec3( hash_immutable ).toVar();
  12568. 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 ) );
  12569. } ).setLayout( {
  12570. name: 'mx_gradient_vec3_1',
  12571. type: 'vec3',
  12572. inputs: [
  12573. { name: 'hash', type: 'uvec3' },
  12574. { name: 'x', type: 'float' },
  12575. { name: 'y', type: 'float' },
  12576. { name: 'z', type: 'float' }
  12577. ]
  12578. } );
  12579. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  12580. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  12581. const v = float( v_immutable ).toVar();
  12582. return mul( 0.6616, v );
  12583. } ).setLayout( {
  12584. name: 'mx_gradient_scale2d_0',
  12585. type: 'float',
  12586. inputs: [
  12587. { name: 'v', type: 'float' }
  12588. ]
  12589. } );
  12590. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  12591. const v = float( v_immutable ).toVar();
  12592. return mul( 0.9820, v );
  12593. } ).setLayout( {
  12594. name: 'mx_gradient_scale3d_0',
  12595. type: 'float',
  12596. inputs: [
  12597. { name: 'v', type: 'float' }
  12598. ]
  12599. } );
  12600. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  12601. const v = vec3( v_immutable ).toVar();
  12602. return mul( 0.6616, v );
  12603. } ).setLayout( {
  12604. name: 'mx_gradient_scale2d_1',
  12605. type: 'vec3',
  12606. inputs: [
  12607. { name: 'v', type: 'vec3' }
  12608. ]
  12609. } );
  12610. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  12611. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  12612. const v = vec3( v_immutable ).toVar();
  12613. return mul( 0.9820, v );
  12614. } ).setLayout( {
  12615. name: 'mx_gradient_scale3d_1',
  12616. type: 'vec3',
  12617. inputs: [
  12618. { name: 'v', type: 'vec3' }
  12619. ]
  12620. } );
  12621. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  12622. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  12623. const k = int( k_immutable ).toVar();
  12624. const x = uint( x_immutable ).toVar();
  12625. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  12626. } ).setLayout( {
  12627. name: 'mx_rotl32',
  12628. type: 'uint',
  12629. inputs: [
  12630. { name: 'x', type: 'uint' },
  12631. { name: 'k', type: 'int' }
  12632. ]
  12633. } );
  12634. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  12635. a.subAssign( c );
  12636. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  12637. c.addAssign( b );
  12638. b.subAssign( a );
  12639. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  12640. a.addAssign( c );
  12641. c.subAssign( b );
  12642. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  12643. b.addAssign( a );
  12644. a.subAssign( c );
  12645. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  12646. c.addAssign( b );
  12647. b.subAssign( a );
  12648. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  12649. a.addAssign( c );
  12650. c.subAssign( b );
  12651. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  12652. b.addAssign( a );
  12653. } );
  12654. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  12655. const c = uint( c_immutable ).toVar();
  12656. const b = uint( b_immutable ).toVar();
  12657. const a = uint( a_immutable ).toVar();
  12658. c.bitXorAssign( b );
  12659. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  12660. a.bitXorAssign( c );
  12661. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  12662. b.bitXorAssign( a );
  12663. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  12664. c.bitXorAssign( b );
  12665. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  12666. a.bitXorAssign( c );
  12667. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  12668. b.bitXorAssign( a );
  12669. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  12670. c.bitXorAssign( b );
  12671. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  12672. return c;
  12673. } ).setLayout( {
  12674. name: 'mx_bjfinal',
  12675. type: 'uint',
  12676. inputs: [
  12677. { name: 'a', type: 'uint' },
  12678. { name: 'b', type: 'uint' },
  12679. { name: 'c', type: 'uint' }
  12680. ]
  12681. } );
  12682. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  12683. const bits = uint( bits_immutable ).toVar();
  12684. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  12685. } ).setLayout( {
  12686. name: 'mx_bits_to_01',
  12687. type: 'float',
  12688. inputs: [
  12689. { name: 'bits', type: 'uint' }
  12690. ]
  12691. } );
  12692. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  12693. const t = float( t_immutable ).toVar();
  12694. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  12695. } ).setLayout( {
  12696. name: 'mx_fade',
  12697. type: 'float',
  12698. inputs: [
  12699. { name: 't', type: 'float' }
  12700. ]
  12701. } );
  12702. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  12703. const x = int( x_immutable ).toVar();
  12704. const len = uint( uint( 1 ) ).toVar();
  12705. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  12706. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  12707. } ).setLayout( {
  12708. name: 'mx_hash_int_0',
  12709. type: 'uint',
  12710. inputs: [
  12711. { name: 'x', type: 'int' }
  12712. ]
  12713. } );
  12714. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  12715. const y = int( y_immutable ).toVar();
  12716. const x = int( x_immutable ).toVar();
  12717. const len = uint( uint( 2 ) ).toVar();
  12718. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  12719. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  12720. a.addAssign( uint( x ) );
  12721. b.addAssign( uint( y ) );
  12722. return mx_bjfinal( a, b, c );
  12723. } ).setLayout( {
  12724. name: 'mx_hash_int_1',
  12725. type: 'uint',
  12726. inputs: [
  12727. { name: 'x', type: 'int' },
  12728. { name: 'y', type: 'int' }
  12729. ]
  12730. } );
  12731. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  12732. const z = int( z_immutable ).toVar();
  12733. const y = int( y_immutable ).toVar();
  12734. const x = int( x_immutable ).toVar();
  12735. const len = uint( uint( 3 ) ).toVar();
  12736. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  12737. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  12738. a.addAssign( uint( x ) );
  12739. b.addAssign( uint( y ) );
  12740. c.addAssign( uint( z ) );
  12741. return mx_bjfinal( a, b, c );
  12742. } ).setLayout( {
  12743. name: 'mx_hash_int_2',
  12744. type: 'uint',
  12745. inputs: [
  12746. { name: 'x', type: 'int' },
  12747. { name: 'y', type: 'int' },
  12748. { name: 'z', type: 'int' }
  12749. ]
  12750. } );
  12751. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  12752. const xx = int( xx_immutable ).toVar();
  12753. const z = int( z_immutable ).toVar();
  12754. const y = int( y_immutable ).toVar();
  12755. const x = int( x_immutable ).toVar();
  12756. const len = uint( uint( 4 ) ).toVar();
  12757. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  12758. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  12759. a.addAssign( uint( x ) );
  12760. b.addAssign( uint( y ) );
  12761. c.addAssign( uint( z ) );
  12762. mx_bjmix( a, b, c );
  12763. a.addAssign( uint( xx ) );
  12764. return mx_bjfinal( a, b, c );
  12765. } ).setLayout( {
  12766. name: 'mx_hash_int_3',
  12767. type: 'uint',
  12768. inputs: [
  12769. { name: 'x', type: 'int' },
  12770. { name: 'y', type: 'int' },
  12771. { name: 'z', type: 'int' },
  12772. { name: 'xx', type: 'int' }
  12773. ]
  12774. } );
  12775. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  12776. const yy = int( yy_immutable ).toVar();
  12777. const xx = int( xx_immutable ).toVar();
  12778. const z = int( z_immutable ).toVar();
  12779. const y = int( y_immutable ).toVar();
  12780. const x = int( x_immutable ).toVar();
  12781. const len = uint( uint( 5 ) ).toVar();
  12782. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  12783. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  12784. a.addAssign( uint( x ) );
  12785. b.addAssign( uint( y ) );
  12786. c.addAssign( uint( z ) );
  12787. mx_bjmix( a, b, c );
  12788. a.addAssign( uint( xx ) );
  12789. b.addAssign( uint( yy ) );
  12790. return mx_bjfinal( a, b, c );
  12791. } ).setLayout( {
  12792. name: 'mx_hash_int_4',
  12793. type: 'uint',
  12794. inputs: [
  12795. { name: 'x', type: 'int' },
  12796. { name: 'y', type: 'int' },
  12797. { name: 'z', type: 'int' },
  12798. { name: 'xx', type: 'int' },
  12799. { name: 'yy', type: 'int' }
  12800. ]
  12801. } );
  12802. 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 ] );
  12803. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  12804. const y = int( y_immutable ).toVar();
  12805. const x = int( x_immutable ).toVar();
  12806. const h = uint( mx_hash_int( x, y ) ).toVar();
  12807. const result = uvec3().toVar();
  12808. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  12809. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  12810. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  12811. return result;
  12812. } ).setLayout( {
  12813. name: 'mx_hash_vec3_0',
  12814. type: 'uvec3',
  12815. inputs: [
  12816. { name: 'x', type: 'int' },
  12817. { name: 'y', type: 'int' }
  12818. ]
  12819. } );
  12820. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  12821. const z = int( z_immutable ).toVar();
  12822. const y = int( y_immutable ).toVar();
  12823. const x = int( x_immutable ).toVar();
  12824. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  12825. const result = uvec3().toVar();
  12826. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  12827. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  12828. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  12829. return result;
  12830. } ).setLayout( {
  12831. name: 'mx_hash_vec3_1',
  12832. type: 'uvec3',
  12833. inputs: [
  12834. { name: 'x', type: 'int' },
  12835. { name: 'y', type: 'int' },
  12836. { name: 'z', type: 'int' }
  12837. ]
  12838. } );
  12839. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  12840. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12841. const p = vec2( p_immutable ).toVar();
  12842. const X = int().toVar(), Y = int().toVar();
  12843. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  12844. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  12845. const u = float( mx_fade( fx ) ).toVar();
  12846. const v = float( mx_fade( fy ) ).toVar();
  12847. 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();
  12848. return mx_gradient_scale2d( result );
  12849. } ).setLayout( {
  12850. name: 'mx_perlin_noise_float_0',
  12851. type: 'float',
  12852. inputs: [
  12853. { name: 'p', type: 'vec2' }
  12854. ]
  12855. } );
  12856. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12857. const p = vec3( p_immutable ).toVar();
  12858. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  12859. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  12860. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  12861. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  12862. const u = float( mx_fade( fx ) ).toVar();
  12863. const v = float( mx_fade( fy ) ).toVar();
  12864. const w = float( mx_fade( fz ) ).toVar();
  12865. 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();
  12866. return mx_gradient_scale3d( result );
  12867. } ).setLayout( {
  12868. name: 'mx_perlin_noise_float_1',
  12869. type: 'float',
  12870. inputs: [
  12871. { name: 'p', type: 'vec3' }
  12872. ]
  12873. } );
  12874. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  12875. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12876. const p = vec2( p_immutable ).toVar();
  12877. const X = int().toVar(), Y = int().toVar();
  12878. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  12879. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  12880. const u = float( mx_fade( fx ) ).toVar();
  12881. const v = float( mx_fade( fy ) ).toVar();
  12882. 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();
  12883. return mx_gradient_scale2d( result );
  12884. } ).setLayout( {
  12885. name: 'mx_perlin_noise_vec3_0',
  12886. type: 'vec3',
  12887. inputs: [
  12888. { name: 'p', type: 'vec2' }
  12889. ]
  12890. } );
  12891. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12892. const p = vec3( p_immutable ).toVar();
  12893. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  12894. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  12895. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  12896. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  12897. const u = float( mx_fade( fx ) ).toVar();
  12898. const v = float( mx_fade( fy ) ).toVar();
  12899. const w = float( mx_fade( fz ) ).toVar();
  12900. 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();
  12901. return mx_gradient_scale3d( result );
  12902. } ).setLayout( {
  12903. name: 'mx_perlin_noise_vec3_1',
  12904. type: 'vec3',
  12905. inputs: [
  12906. { name: 'p', type: 'vec3' }
  12907. ]
  12908. } );
  12909. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  12910. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12911. const p = float( p_immutable ).toVar();
  12912. const ix = int( mx_floor( p ) ).toVar();
  12913. return mx_bits_to_01( mx_hash_int( ix ) );
  12914. } ).setLayout( {
  12915. name: 'mx_cell_noise_float_0',
  12916. type: 'float',
  12917. inputs: [
  12918. { name: 'p', type: 'float' }
  12919. ]
  12920. } );
  12921. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12922. const p = vec2( p_immutable ).toVar();
  12923. const ix = int( mx_floor( p.x ) ).toVar();
  12924. const iy = int( mx_floor( p.y ) ).toVar();
  12925. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  12926. } ).setLayout( {
  12927. name: 'mx_cell_noise_float_1',
  12928. type: 'float',
  12929. inputs: [
  12930. { name: 'p', type: 'vec2' }
  12931. ]
  12932. } );
  12933. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12934. const p = vec3( p_immutable ).toVar();
  12935. const ix = int( mx_floor( p.x ) ).toVar();
  12936. const iy = int( mx_floor( p.y ) ).toVar();
  12937. const iz = int( mx_floor( p.z ) ).toVar();
  12938. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  12939. } ).setLayout( {
  12940. name: 'mx_cell_noise_float_2',
  12941. type: 'float',
  12942. inputs: [
  12943. { name: 'p', type: 'vec3' }
  12944. ]
  12945. } );
  12946. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12947. const p = vec4( p_immutable ).toVar();
  12948. const ix = int( mx_floor( p.x ) ).toVar();
  12949. const iy = int( mx_floor( p.y ) ).toVar();
  12950. const iz = int( mx_floor( p.z ) ).toVar();
  12951. const iw = int( mx_floor( p.w ) ).toVar();
  12952. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  12953. } ).setLayout( {
  12954. name: 'mx_cell_noise_float_3',
  12955. type: 'float',
  12956. inputs: [
  12957. { name: 'p', type: 'vec4' }
  12958. ]
  12959. } );
  12960. 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 ] );
  12961. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12962. const p = float( p_immutable ).toVar();
  12963. const ix = int( mx_floor( p ) ).toVar();
  12964. 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 ) ) ) );
  12965. } ).setLayout( {
  12966. name: 'mx_cell_noise_vec3_0',
  12967. type: 'vec3',
  12968. inputs: [
  12969. { name: 'p', type: 'float' }
  12970. ]
  12971. } );
  12972. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12973. const p = vec2( p_immutable ).toVar();
  12974. const ix = int( mx_floor( p.x ) ).toVar();
  12975. const iy = int( mx_floor( p.y ) ).toVar();
  12976. 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 ) ) ) );
  12977. } ).setLayout( {
  12978. name: 'mx_cell_noise_vec3_1',
  12979. type: 'vec3',
  12980. inputs: [
  12981. { name: 'p', type: 'vec2' }
  12982. ]
  12983. } );
  12984. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12985. const p = vec3( p_immutable ).toVar();
  12986. const ix = int( mx_floor( p.x ) ).toVar();
  12987. const iy = int( mx_floor( p.y ) ).toVar();
  12988. const iz = int( mx_floor( p.z ) ).toVar();
  12989. 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 ) ) ) );
  12990. } ).setLayout( {
  12991. name: 'mx_cell_noise_vec3_2',
  12992. type: 'vec3',
  12993. inputs: [
  12994. { name: 'p', type: 'vec3' }
  12995. ]
  12996. } );
  12997. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  12998. const p = vec4( p_immutable ).toVar();
  12999. const ix = int( mx_floor( p.x ) ).toVar();
  13000. const iy = int( mx_floor( p.y ) ).toVar();
  13001. const iz = int( mx_floor( p.z ) ).toVar();
  13002. const iw = int( mx_floor( p.w ) ).toVar();
  13003. 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 ) ) ) );
  13004. } ).setLayout( {
  13005. name: 'mx_cell_noise_vec3_3',
  13006. type: 'vec3',
  13007. inputs: [
  13008. { name: 'p', type: 'vec4' }
  13009. ]
  13010. } );
  13011. 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 ] );
  13012. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  13013. const diminish = float( diminish_immutable ).toVar();
  13014. const lacunarity = float( lacunarity_immutable ).toVar();
  13015. const octaves = int( octaves_immutable ).toVar();
  13016. const p = vec3( p_immutable ).toVar();
  13017. const result = float( 0.0 ).toVar();
  13018. const amplitude = float( 1.0 ).toVar();
  13019. Loop( octaves, () => {
  13020. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  13021. amplitude.mulAssign( diminish );
  13022. p.mulAssign( lacunarity );
  13023. } );
  13024. return result;
  13025. } ).setLayout( {
  13026. name: 'mx_fractal_noise_float',
  13027. type: 'float',
  13028. inputs: [
  13029. { name: 'p', type: 'vec3' },
  13030. { name: 'octaves', type: 'int' },
  13031. { name: 'lacunarity', type: 'float' },
  13032. { name: 'diminish', type: 'float' }
  13033. ]
  13034. } );
  13035. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  13036. const diminish = float( diminish_immutable ).toVar();
  13037. const lacunarity = float( lacunarity_immutable ).toVar();
  13038. const octaves = int( octaves_immutable ).toVar();
  13039. const p = vec3( p_immutable ).toVar();
  13040. const result = vec3( 0.0 ).toVar();
  13041. const amplitude = float( 1.0 ).toVar();
  13042. Loop( octaves, () => {
  13043. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  13044. amplitude.mulAssign( diminish );
  13045. p.mulAssign( lacunarity );
  13046. } );
  13047. return result;
  13048. } ).setLayout( {
  13049. name: 'mx_fractal_noise_vec3',
  13050. type: 'vec3',
  13051. inputs: [
  13052. { name: 'p', type: 'vec3' },
  13053. { name: 'octaves', type: 'int' },
  13054. { name: 'lacunarity', type: 'float' },
  13055. { name: 'diminish', type: 'float' }
  13056. ]
  13057. } );
  13058. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  13059. const diminish = float( diminish_immutable ).toVar();
  13060. const lacunarity = float( lacunarity_immutable ).toVar();
  13061. const octaves = int( octaves_immutable ).toVar();
  13062. const p = vec3( p_immutable ).toVar();
  13063. 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 ) );
  13064. } ).setLayout( {
  13065. name: 'mx_fractal_noise_vec2',
  13066. type: 'vec2',
  13067. inputs: [
  13068. { name: 'p', type: 'vec3' },
  13069. { name: 'octaves', type: 'int' },
  13070. { name: 'lacunarity', type: 'float' },
  13071. { name: 'diminish', type: 'float' }
  13072. ]
  13073. } );
  13074. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  13075. const diminish = float( diminish_immutable ).toVar();
  13076. const lacunarity = float( lacunarity_immutable ).toVar();
  13077. const octaves = int( octaves_immutable ).toVar();
  13078. const p = vec3( p_immutable ).toVar();
  13079. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  13080. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  13081. return vec4( c, f );
  13082. } ).setLayout( {
  13083. name: 'mx_fractal_noise_vec4',
  13084. type: 'vec4',
  13085. inputs: [
  13086. { name: 'p', type: 'vec3' },
  13087. { name: 'octaves', type: 'int' },
  13088. { name: 'lacunarity', type: 'float' },
  13089. { name: 'diminish', type: 'float' }
  13090. ]
  13091. } );
  13092. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  13093. const metric = int( metric_immutable ).toVar();
  13094. const jitter = float( jitter_immutable ).toVar();
  13095. const yoff = int( yoff_immutable ).toVar();
  13096. const xoff = int( xoff_immutable ).toVar();
  13097. const y = int( y_immutable ).toVar();
  13098. const x = int( x_immutable ).toVar();
  13099. const p = vec2( p_immutable ).toVar();
  13100. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  13101. const off = vec2( tmp.x, tmp.y ).toVar();
  13102. off.subAssign( 0.5 );
  13103. off.mulAssign( jitter );
  13104. off.addAssign( 0.5 );
  13105. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  13106. const diff = vec2( cellpos.sub( p ) ).toVar();
  13107. If( metric.equal( int( 2 ) ), () => {
  13108. return abs( diff.x ).add( abs( diff.y ) );
  13109. } );
  13110. If( metric.equal( int( 3 ) ), () => {
  13111. return max$1( abs( diff.x ), abs( diff.y ) );
  13112. } );
  13113. return dot( diff, diff );
  13114. } ).setLayout( {
  13115. name: 'mx_worley_distance_0',
  13116. type: 'float',
  13117. inputs: [
  13118. { name: 'p', type: 'vec2' },
  13119. { name: 'x', type: 'int' },
  13120. { name: 'y', type: 'int' },
  13121. { name: 'xoff', type: 'int' },
  13122. { name: 'yoff', type: 'int' },
  13123. { name: 'jitter', type: 'float' },
  13124. { name: 'metric', type: 'int' }
  13125. ]
  13126. } );
  13127. 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 ] ) => {
  13128. const metric = int( metric_immutable ).toVar();
  13129. const jitter = float( jitter_immutable ).toVar();
  13130. const zoff = int( zoff_immutable ).toVar();
  13131. const yoff = int( yoff_immutable ).toVar();
  13132. const xoff = int( xoff_immutable ).toVar();
  13133. const z = int( z_immutable ).toVar();
  13134. const y = int( y_immutable ).toVar();
  13135. const x = int( x_immutable ).toVar();
  13136. const p = vec3( p_immutable ).toVar();
  13137. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  13138. off.subAssign( 0.5 );
  13139. off.mulAssign( jitter );
  13140. off.addAssign( 0.5 );
  13141. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  13142. const diff = vec3( cellpos.sub( p ) ).toVar();
  13143. If( metric.equal( int( 2 ) ), () => {
  13144. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  13145. } );
  13146. If( metric.equal( int( 3 ) ), () => {
  13147. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  13148. } );
  13149. return dot( diff, diff );
  13150. } ).setLayout( {
  13151. name: 'mx_worley_distance_1',
  13152. type: 'float',
  13153. inputs: [
  13154. { name: 'p', type: 'vec3' },
  13155. { name: 'x', type: 'int' },
  13156. { name: 'y', type: 'int' },
  13157. { name: 'z', type: 'int' },
  13158. { name: 'xoff', type: 'int' },
  13159. { name: 'yoff', type: 'int' },
  13160. { name: 'zoff', type: 'int' },
  13161. { name: 'jitter', type: 'float' },
  13162. { name: 'metric', type: 'int' }
  13163. ]
  13164. } );
  13165. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  13166. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13167. const metric = int( metric_immutable ).toVar();
  13168. const jitter = float( jitter_immutable ).toVar();
  13169. const p = vec2( p_immutable ).toVar();
  13170. const X = int().toVar(), Y = int().toVar();
  13171. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  13172. const sqdist = float( 1e6 ).toVar();
  13173. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13174. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13175. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  13176. sqdist.assign( min$1( sqdist, dist ) );
  13177. } );
  13178. } );
  13179. If( metric.equal( int( 0 ) ), () => {
  13180. sqdist.assign( sqrt( sqdist ) );
  13181. } );
  13182. return sqdist;
  13183. } ).setLayout( {
  13184. name: 'mx_worley_noise_float_0',
  13185. type: 'float',
  13186. inputs: [
  13187. { name: 'p', type: 'vec2' },
  13188. { name: 'jitter', type: 'float' },
  13189. { name: 'metric', type: 'int' }
  13190. ]
  13191. } );
  13192. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13193. const metric = int( metric_immutable ).toVar();
  13194. const jitter = float( jitter_immutable ).toVar();
  13195. const p = vec2( p_immutable ).toVar();
  13196. const X = int().toVar(), Y = int().toVar();
  13197. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  13198. const sqdist = vec2( 1e6, 1e6 ).toVar();
  13199. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13200. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13201. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  13202. If( dist.lessThan( sqdist.x ), () => {
  13203. sqdist.y.assign( sqdist.x );
  13204. sqdist.x.assign( dist );
  13205. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  13206. sqdist.y.assign( dist );
  13207. } );
  13208. } );
  13209. } );
  13210. If( metric.equal( int( 0 ) ), () => {
  13211. sqdist.assign( sqrt( sqdist ) );
  13212. } );
  13213. return sqdist;
  13214. } ).setLayout( {
  13215. name: 'mx_worley_noise_vec2_0',
  13216. type: 'vec2',
  13217. inputs: [
  13218. { name: 'p', type: 'vec2' },
  13219. { name: 'jitter', type: 'float' },
  13220. { name: 'metric', type: 'int' }
  13221. ]
  13222. } );
  13223. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13224. const metric = int( metric_immutable ).toVar();
  13225. const jitter = float( jitter_immutable ).toVar();
  13226. const p = vec2( p_immutable ).toVar();
  13227. const X = int().toVar(), Y = int().toVar();
  13228. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  13229. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  13230. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13231. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13232. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  13233. If( dist.lessThan( sqdist.x ), () => {
  13234. sqdist.z.assign( sqdist.y );
  13235. sqdist.y.assign( sqdist.x );
  13236. sqdist.x.assign( dist );
  13237. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  13238. sqdist.z.assign( sqdist.y );
  13239. sqdist.y.assign( dist );
  13240. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  13241. sqdist.z.assign( dist );
  13242. } );
  13243. } );
  13244. } );
  13245. If( metric.equal( int( 0 ) ), () => {
  13246. sqdist.assign( sqrt( sqdist ) );
  13247. } );
  13248. return sqdist;
  13249. } ).setLayout( {
  13250. name: 'mx_worley_noise_vec3_0',
  13251. type: 'vec3',
  13252. inputs: [
  13253. { name: 'p', type: 'vec2' },
  13254. { name: 'jitter', type: 'float' },
  13255. { name: 'metric', type: 'int' }
  13256. ]
  13257. } );
  13258. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13259. const metric = int( metric_immutable ).toVar();
  13260. const jitter = float( jitter_immutable ).toVar();
  13261. const p = vec3( p_immutable ).toVar();
  13262. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  13263. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  13264. const sqdist = float( 1e6 ).toVar();
  13265. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13266. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13267. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  13268. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  13269. sqdist.assign( min$1( sqdist, dist ) );
  13270. } );
  13271. } );
  13272. } );
  13273. If( metric.equal( int( 0 ) ), () => {
  13274. sqdist.assign( sqrt( sqdist ) );
  13275. } );
  13276. return sqdist;
  13277. } ).setLayout( {
  13278. name: 'mx_worley_noise_float_1',
  13279. type: 'float',
  13280. inputs: [
  13281. { name: 'p', type: 'vec3' },
  13282. { name: 'jitter', type: 'float' },
  13283. { name: 'metric', type: 'int' }
  13284. ]
  13285. } );
  13286. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  13287. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13288. const metric = int( metric_immutable ).toVar();
  13289. const jitter = float( jitter_immutable ).toVar();
  13290. const p = vec3( p_immutable ).toVar();
  13291. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  13292. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  13293. const sqdist = vec2( 1e6, 1e6 ).toVar();
  13294. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13295. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13296. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  13297. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  13298. If( dist.lessThan( sqdist.x ), () => {
  13299. sqdist.y.assign( sqdist.x );
  13300. sqdist.x.assign( dist );
  13301. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  13302. sqdist.y.assign( dist );
  13303. } );
  13304. } );
  13305. } );
  13306. } );
  13307. If( metric.equal( int( 0 ) ), () => {
  13308. sqdist.assign( sqrt( sqdist ) );
  13309. } );
  13310. return sqdist;
  13311. } ).setLayout( {
  13312. name: 'mx_worley_noise_vec2_1',
  13313. type: 'vec2',
  13314. inputs: [
  13315. { name: 'p', type: 'vec3' },
  13316. { name: 'jitter', type: 'float' },
  13317. { name: 'metric', type: 'int' }
  13318. ]
  13319. } );
  13320. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  13321. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  13322. const metric = int( metric_immutable ).toVar();
  13323. const jitter = float( jitter_immutable ).toVar();
  13324. const p = vec3( p_immutable ).toVar();
  13325. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  13326. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  13327. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  13328. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  13329. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  13330. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  13331. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  13332. If( dist.lessThan( sqdist.x ), () => {
  13333. sqdist.z.assign( sqdist.y );
  13334. sqdist.y.assign( sqdist.x );
  13335. sqdist.x.assign( dist );
  13336. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  13337. sqdist.z.assign( sqdist.y );
  13338. sqdist.y.assign( dist );
  13339. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  13340. sqdist.z.assign( dist );
  13341. } );
  13342. } );
  13343. } );
  13344. } );
  13345. If( metric.equal( int( 0 ) ), () => {
  13346. sqdist.assign( sqrt( sqdist ) );
  13347. } );
  13348. return sqdist;
  13349. } ).setLayout( {
  13350. name: 'mx_worley_noise_vec3_1',
  13351. type: 'vec3',
  13352. inputs: [
  13353. { name: 'p', type: 'vec3' },
  13354. { name: 'jitter', type: 'float' },
  13355. { name: 'metric', type: 'int' }
  13356. ]
  13357. } );
  13358. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  13359. // Three.js Transpiler
  13360. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  13361. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  13362. const s = hsv.y;
  13363. const v = hsv.z;
  13364. const result = vec3().toVar();
  13365. If( s.lessThan( 0.0001 ), () => {
  13366. result.assign( vec3( v, v, v ) );
  13367. } ).Else( () => {
  13368. let h = hsv.x;
  13369. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  13370. const hi = int( trunc( h ) );
  13371. const f = h.sub( float( hi ) );
  13372. const p = v.mul( s.oneMinus() );
  13373. const q = v.mul( s.mul( f ).oneMinus() );
  13374. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  13375. If( hi.equal( int( 0 ) ), () => {
  13376. result.assign( vec3( v, t, p ) );
  13377. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  13378. result.assign( vec3( q, v, p ) );
  13379. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  13380. result.assign( vec3( p, v, t ) );
  13381. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  13382. result.assign( vec3( p, q, v ) );
  13383. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  13384. result.assign( vec3( t, p, v ) );
  13385. } ).Else( () => {
  13386. result.assign( vec3( v, p, q ) );
  13387. } );
  13388. } );
  13389. return result;
  13390. } ).setLayout( {
  13391. name: 'mx_hsvtorgb',
  13392. type: 'vec3',
  13393. inputs: [
  13394. { name: 'hsv', type: 'vec3' }
  13395. ]
  13396. } );
  13397. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  13398. const c = vec3( c_immutable ).toVar();
  13399. const r = float( c.x ).toVar();
  13400. const g = float( c.y ).toVar();
  13401. const b = float( c.z ).toVar();
  13402. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  13403. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  13404. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  13405. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  13406. v.assign( maxcomp );
  13407. If( maxcomp.greaterThan( 0.0 ), () => {
  13408. s.assign( delta.div( maxcomp ) );
  13409. } ).Else( () => {
  13410. s.assign( 0.0 );
  13411. } );
  13412. If( s.lessThanEqual( 0.0 ), () => {
  13413. h.assign( 0.0 );
  13414. } ).Else( () => {
  13415. If( r.greaterThanEqual( maxcomp ), () => {
  13416. h.assign( g.sub( b ).div( delta ) );
  13417. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  13418. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  13419. } ).Else( () => {
  13420. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  13421. } );
  13422. h.mulAssign( 1.0 / 6.0 );
  13423. If( h.lessThan( 0.0 ), () => {
  13424. h.addAssign( 1.0 );
  13425. } );
  13426. } );
  13427. return vec3( h, s, v );
  13428. } ).setLayout( {
  13429. name: 'mx_rgbtohsv',
  13430. type: 'vec3',
  13431. inputs: [
  13432. { name: 'c', type: 'vec3' }
  13433. ]
  13434. } );
  13435. // Three.js Transpiler
  13436. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  13437. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  13438. const color = vec3( color_immutable ).toVar();
  13439. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  13440. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  13441. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  13442. return mix( linSeg, powSeg, isAbove );
  13443. } ).setLayout( {
  13444. name: 'mx_srgb_texture_to_lin_rec709',
  13445. type: 'vec3',
  13446. inputs: [
  13447. { name: 'color', type: 'vec3' }
  13448. ]
  13449. } );
  13450. const mx_aastep = ( threshold, value ) => {
  13451. threshold = float( threshold );
  13452. value = float( value );
  13453. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  13454. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  13455. };
  13456. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  13457. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  13458. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  13459. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  13460. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  13461. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  13462. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  13463. const mx_safepower = ( in1, in2 = 1 ) => {
  13464. in1 = float( in1 );
  13465. return in1.abs().pow( in2 ).mul( in1.sign() );
  13466. };
  13467. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  13468. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  13469. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  13470. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  13471. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  13472. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  13473. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  13474. return noise_vec4.mul( amplitude ).add( pivot );
  13475. };
  13476. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  13477. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  13478. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  13479. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  13480. 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 );
  13481. 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 );
  13482. 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 );
  13483. 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 );
  13484. // https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html
  13485. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  13486. const nDir = normalize( normal ).toVar( 'nDir' );
  13487. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmax' );
  13488. const rbmin = sub( float( - 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmin' );
  13489. const rbminmax = vec3().toVar( 'rbminmax' );
  13490. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  13491. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  13492. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  13493. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar( 'correction' );
  13494. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar( 'boxIntersection' );
  13495. return boxIntersection.sub( cubePos );
  13496. } );
  13497. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  13498. // normal is assumed to have unit length
  13499. const x = normal.x, y = normal.y, z = normal.z;
  13500. // band 0
  13501. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  13502. // band 1
  13503. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  13504. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  13505. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  13506. // band 2
  13507. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  13508. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  13509. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  13510. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  13511. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  13512. return result;
  13513. } );
  13514. const _clearColor$1 = /*@__PURE__*/ new Color4();
  13515. class Background extends DataMap {
  13516. constructor( renderer, nodes ) {
  13517. super();
  13518. this.renderer = renderer;
  13519. this.nodes = nodes;
  13520. }
  13521. update( scene, renderList, renderContext ) {
  13522. const renderer = this.renderer;
  13523. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  13524. let forceClear = false;
  13525. if ( background === null ) {
  13526. // no background settings, use clear color configuration from the renderer
  13527. renderer._clearColor.getRGB( _clearColor$1, LinearSRGBColorSpace );
  13528. _clearColor$1.a = renderer._clearColor.a;
  13529. } else if ( background.isColor === true ) {
  13530. // background is an opaque color
  13531. background.getRGB( _clearColor$1, LinearSRGBColorSpace );
  13532. _clearColor$1.a = 1;
  13533. forceClear = true;
  13534. } else if ( background.isNode === true ) {
  13535. const sceneData = this.get( scene );
  13536. const backgroundNode = background;
  13537. _clearColor$1.copy( renderer._clearColor );
  13538. let backgroundMesh = sceneData.backgroundMesh;
  13539. if ( backgroundMesh === undefined ) {
  13540. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  13541. // @TODO: Add Texture2D support using node context
  13542. getUV: () => backgroundRotation.mul( normalWorld ),
  13543. getTextureLevel: () => backgroundBlurriness
  13544. } );
  13545. let viewProj = modelViewProjection();
  13546. viewProj = viewProj.setZ( viewProj.w );
  13547. const nodeMaterial = new NodeMaterial();
  13548. nodeMaterial.name = 'Background.material';
  13549. nodeMaterial.side = BackSide;
  13550. nodeMaterial.depthTest = false;
  13551. nodeMaterial.depthWrite = false;
  13552. nodeMaterial.fog = false;
  13553. nodeMaterial.lights = false;
  13554. nodeMaterial.vertexNode = viewProj;
  13555. nodeMaterial.colorNode = backgroundMeshNode;
  13556. sceneData.backgroundMeshNode = backgroundMeshNode;
  13557. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  13558. backgroundMesh.frustumCulled = false;
  13559. backgroundMesh.name = 'Background.mesh';
  13560. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  13561. this.matrixWorld.copyPosition( camera.matrixWorld );
  13562. };
  13563. }
  13564. const backgroundCacheKey = backgroundNode.getCacheKey();
  13565. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  13566. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  13567. sceneData.backgroundMeshNode.needsUpdate = true;
  13568. backgroundMesh.material.needsUpdate = true;
  13569. sceneData.backgroundCacheKey = backgroundCacheKey;
  13570. }
  13571. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  13572. } else {
  13573. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  13574. }
  13575. //
  13576. if ( renderer.autoClear === true || forceClear === true ) {
  13577. const clearColorValue = renderContext.clearColorValue;
  13578. clearColorValue.r = _clearColor$1.r;
  13579. clearColorValue.g = _clearColor$1.g;
  13580. clearColorValue.b = _clearColor$1.b;
  13581. clearColorValue.a = _clearColor$1.a;
  13582. // premultiply alpha
  13583. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  13584. clearColorValue.r *= clearColorValue.a;
  13585. clearColorValue.g *= clearColorValue.a;
  13586. clearColorValue.b *= clearColorValue.a;
  13587. }
  13588. //
  13589. renderContext.depthClearValue = renderer._clearDepth;
  13590. renderContext.stencilClearValue = renderer._clearStencil;
  13591. renderContext.clearColor = renderer.autoClearColor === true;
  13592. renderContext.clearDepth = renderer.autoClearDepth === true;
  13593. renderContext.clearStencil = renderer.autoClearStencil === true;
  13594. } else {
  13595. renderContext.clearColor = false;
  13596. renderContext.clearDepth = false;
  13597. renderContext.clearStencil = false;
  13598. }
  13599. }
  13600. }
  13601. let _id$5 = 0;
  13602. class BindGroup {
  13603. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  13604. this.name = name;
  13605. this.bindings = bindings;
  13606. this.index = index;
  13607. this.bindingsReference = bindingsReference;
  13608. this.id = _id$5 ++;
  13609. }
  13610. }
  13611. class NodeBuilderState {
  13612. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, monitor, transforms = [] ) {
  13613. this.vertexShader = vertexShader;
  13614. this.fragmentShader = fragmentShader;
  13615. this.computeShader = computeShader;
  13616. this.transforms = transforms;
  13617. this.nodeAttributes = nodeAttributes;
  13618. this.bindings = bindings;
  13619. this.updateNodes = updateNodes;
  13620. this.updateBeforeNodes = updateBeforeNodes;
  13621. this.updateAfterNodes = updateAfterNodes;
  13622. this.monitor = monitor;
  13623. this.usedTimes = 0;
  13624. }
  13625. createBindings() {
  13626. const bindings = [];
  13627. for ( const instanceGroup of this.bindings ) {
  13628. const shared = instanceGroup.bindings[ 0 ].groupNode.shared;
  13629. if ( shared !== true ) {
  13630. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  13631. bindings.push( bindingsGroup );
  13632. for ( const instanceBinding of instanceGroup.bindings ) {
  13633. bindingsGroup.bindings.push( instanceBinding.clone() );
  13634. }
  13635. } else {
  13636. bindings.push( instanceGroup );
  13637. }
  13638. }
  13639. return bindings;
  13640. }
  13641. }
  13642. class NodeAttribute {
  13643. constructor( name, type, node = null ) {
  13644. this.isNodeAttribute = true;
  13645. this.name = name;
  13646. this.type = type;
  13647. this.node = node;
  13648. }
  13649. }
  13650. class NodeUniform {
  13651. constructor( name, type, node ) {
  13652. this.isNodeUniform = true;
  13653. this.name = name;
  13654. this.type = type;
  13655. this.node = node.getSelf();
  13656. }
  13657. get value() {
  13658. return this.node.value;
  13659. }
  13660. set value( val ) {
  13661. this.node.value = val;
  13662. }
  13663. get id() {
  13664. return this.node.id;
  13665. }
  13666. get groupNode() {
  13667. return this.node.groupNode;
  13668. }
  13669. }
  13670. class NodeVar {
  13671. constructor( name, type ) {
  13672. this.isNodeVar = true;
  13673. this.name = name;
  13674. this.type = type;
  13675. }
  13676. }
  13677. class NodeVarying extends NodeVar {
  13678. constructor( name, type ) {
  13679. super( name, type );
  13680. this.needsInterpolation = false;
  13681. this.isNodeVarying = true;
  13682. }
  13683. }
  13684. class NodeCode {
  13685. constructor( name, type, code = '' ) {
  13686. this.name = name;
  13687. this.type = type;
  13688. this.code = code;
  13689. Object.defineProperty( this, 'isNodeCode', { value: true } );
  13690. }
  13691. }
  13692. let id = 0;
  13693. class NodeCache {
  13694. constructor( parent = null ) {
  13695. this.id = id ++;
  13696. this.nodesData = new WeakMap();
  13697. this.parent = parent;
  13698. }
  13699. getData( node ) {
  13700. let data = this.nodesData.get( node );
  13701. if ( data === undefined && this.parent !== null ) {
  13702. data = this.parent.getData( node );
  13703. }
  13704. return data;
  13705. }
  13706. setData( node, data ) {
  13707. this.nodesData.set( node, data );
  13708. }
  13709. }
  13710. class Uniform {
  13711. constructor( name, value ) {
  13712. this.name = name;
  13713. this.value = value;
  13714. this.boundary = 0; // used to build the uniform buffer according to the STD140 layout
  13715. this.itemSize = 0;
  13716. this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer
  13717. }
  13718. setValue( value ) {
  13719. this.value = value;
  13720. }
  13721. getValue() {
  13722. return this.value;
  13723. }
  13724. }
  13725. class NumberUniform extends Uniform {
  13726. constructor( name, value = 0 ) {
  13727. super( name, value );
  13728. this.isNumberUniform = true;
  13729. this.boundary = 4;
  13730. this.itemSize = 1;
  13731. }
  13732. }
  13733. class Vector2Uniform extends Uniform {
  13734. constructor( name, value = new Vector2() ) {
  13735. super( name, value );
  13736. this.isVector2Uniform = true;
  13737. this.boundary = 8;
  13738. this.itemSize = 2;
  13739. }
  13740. }
  13741. class Vector3Uniform extends Uniform {
  13742. constructor( name, value = new Vector3() ) {
  13743. super( name, value );
  13744. this.isVector3Uniform = true;
  13745. this.boundary = 16;
  13746. this.itemSize = 3;
  13747. }
  13748. }
  13749. class Vector4Uniform extends Uniform {
  13750. constructor( name, value = new Vector4() ) {
  13751. super( name, value );
  13752. this.isVector4Uniform = true;
  13753. this.boundary = 16;
  13754. this.itemSize = 4;
  13755. }
  13756. }
  13757. class ColorUniform extends Uniform {
  13758. constructor( name, value = new Color() ) {
  13759. super( name, value );
  13760. this.isColorUniform = true;
  13761. this.boundary = 16;
  13762. this.itemSize = 3;
  13763. }
  13764. }
  13765. class Matrix3Uniform extends Uniform {
  13766. constructor( name, value = new Matrix3() ) {
  13767. super( name, value );
  13768. this.isMatrix3Uniform = true;
  13769. this.boundary = 48;
  13770. this.itemSize = 12;
  13771. }
  13772. }
  13773. class Matrix4Uniform extends Uniform {
  13774. constructor( name, value = new Matrix4() ) {
  13775. super( name, value );
  13776. this.isMatrix4Uniform = true;
  13777. this.boundary = 64;
  13778. this.itemSize = 16;
  13779. }
  13780. }
  13781. class NumberNodeUniform extends NumberUniform {
  13782. constructor( nodeUniform ) {
  13783. super( nodeUniform.name, nodeUniform.value );
  13784. this.nodeUniform = nodeUniform;
  13785. }
  13786. getValue() {
  13787. return this.nodeUniform.value;
  13788. }
  13789. }
  13790. class Vector2NodeUniform extends Vector2Uniform {
  13791. constructor( nodeUniform ) {
  13792. super( nodeUniform.name, nodeUniform.value );
  13793. this.nodeUniform = nodeUniform;
  13794. }
  13795. getValue() {
  13796. return this.nodeUniform.value;
  13797. }
  13798. }
  13799. class Vector3NodeUniform extends Vector3Uniform {
  13800. constructor( nodeUniform ) {
  13801. super( nodeUniform.name, nodeUniform.value );
  13802. this.nodeUniform = nodeUniform;
  13803. }
  13804. getValue() {
  13805. return this.nodeUniform.value;
  13806. }
  13807. }
  13808. class Vector4NodeUniform extends Vector4Uniform {
  13809. constructor( nodeUniform ) {
  13810. super( nodeUniform.name, nodeUniform.value );
  13811. this.nodeUniform = nodeUniform;
  13812. }
  13813. getValue() {
  13814. return this.nodeUniform.value;
  13815. }
  13816. }
  13817. class ColorNodeUniform extends ColorUniform {
  13818. constructor( nodeUniform ) {
  13819. super( nodeUniform.name, nodeUniform.value );
  13820. this.nodeUniform = nodeUniform;
  13821. }
  13822. getValue() {
  13823. return this.nodeUniform.value;
  13824. }
  13825. }
  13826. class Matrix3NodeUniform extends Matrix3Uniform {
  13827. constructor( nodeUniform ) {
  13828. super( nodeUniform.name, nodeUniform.value );
  13829. this.nodeUniform = nodeUniform;
  13830. }
  13831. getValue() {
  13832. return this.nodeUniform.value;
  13833. }
  13834. }
  13835. class Matrix4NodeUniform extends Matrix4Uniform {
  13836. constructor( nodeUniform ) {
  13837. super( nodeUniform.name, nodeUniform.value );
  13838. this.nodeUniform = nodeUniform;
  13839. }
  13840. getValue() {
  13841. return this.nodeUniform.value;
  13842. }
  13843. }
  13844. const LOD_MIN = 4;
  13845. // The standard deviations (radians) associated with the extra mips. These are
  13846. // chosen to approximate a Trowbridge-Reitz distribution function times the
  13847. // geometric shadowing function. These sigma values squared must match the
  13848. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  13849. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  13850. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  13851. // samples and exit early, but not recompile the shader.
  13852. const MAX_SAMPLES = 20;
  13853. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  13854. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  13855. const _clearColor = /*@__PURE__*/ new Color();
  13856. let _oldTarget = null;
  13857. let _oldActiveCubeFace = 0;
  13858. let _oldActiveMipmapLevel = 0;
  13859. // Golden Ratio
  13860. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  13861. const INV_PHI = 1 / PHI;
  13862. // Vertices of a dodecahedron (except the opposites, which represent the
  13863. // same axis), used as axis directions evenly spread on a sphere.
  13864. const _axisDirections = [
  13865. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  13866. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  13867. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  13868. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  13869. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  13870. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  13871. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  13872. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  13873. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  13874. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  13875. ];
  13876. //
  13877. // WebGPU Face indices
  13878. const _faceLib = [
  13879. 3, 1, 5,
  13880. 0, 4, 2
  13881. ];
  13882. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  13883. const outputDirection = vec3( direction.x, direction.y.negate(), direction.z );
  13884. /**
  13885. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  13886. * (PMREM) from a cubeMap environment texture. This allows different levels of
  13887. * blur to be quickly accessed based on material roughness. It is packed into a
  13888. * special CubeUV format that allows us to perform custom interpolation so that
  13889. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  13890. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  13891. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  13892. * higher roughness levels. In this way we maintain resolution to smoothly
  13893. * interpolate diffuse lighting while limiting sampling computation.
  13894. *
  13895. * Paper: Fast, Accurate Image-Based Lighting
  13896. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  13897. */
  13898. class PMREMGenerator {
  13899. constructor( renderer ) {
  13900. this._renderer = renderer;
  13901. this._pingPongRenderTarget = null;
  13902. this._lodMax = 0;
  13903. this._cubeSize = 0;
  13904. this._lodPlanes = [];
  13905. this._sizeLods = [];
  13906. this._sigmas = [];
  13907. this._lodMeshes = [];
  13908. this._blurMaterial = null;
  13909. this._cubemapMaterial = null;
  13910. this._equirectMaterial = null;
  13911. this._backgroundBox = null;
  13912. }
  13913. /**
  13914. * Generates a PMREM from a supplied Scene, which can be faster than using an
  13915. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  13916. * in radians to be applied to the scene before PMREM generation. Optional near
  13917. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  13918. * is placed at the origin).
  13919. */
  13920. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  13921. _oldTarget = this._renderer.getRenderTarget();
  13922. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  13923. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  13924. this._setSize( 256 );
  13925. const cubeUVRenderTarget = this._allocateTargets();
  13926. cubeUVRenderTarget.depthBuffer = true;
  13927. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  13928. if ( sigma > 0 ) {
  13929. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  13930. }
  13931. this._applyPMREM( cubeUVRenderTarget );
  13932. this._cleanup( cubeUVRenderTarget );
  13933. return cubeUVRenderTarget;
  13934. }
  13935. /**
  13936. * Generates a PMREM from an equirectangular texture, which can be either LDR
  13937. * or HDR. The ideal input image size is 1k (1024 x 512),
  13938. * as this matches best with the 256 x 256 cubemap output.
  13939. */
  13940. fromEquirectangular( equirectangular, renderTarget = null ) {
  13941. return this._fromTexture( equirectangular, renderTarget );
  13942. }
  13943. /**
  13944. * Generates a PMREM from an cubemap texture, which can be either LDR
  13945. * or HDR. The ideal input cube size is 256 x 256,
  13946. * as this matches best with the 256 x 256 cubemap output.
  13947. */
  13948. fromCubemap( cubemap, renderTarget = null ) {
  13949. return this._fromTexture( cubemap, renderTarget );
  13950. }
  13951. /**
  13952. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  13953. * your texture's network fetch for increased concurrency.
  13954. */
  13955. async compileCubemapShader() {
  13956. if ( this._cubemapMaterial === null ) {
  13957. this._cubemapMaterial = _getCubemapMaterial();
  13958. await this._compileMaterial( this._cubemapMaterial );
  13959. }
  13960. }
  13961. /**
  13962. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  13963. * your texture's network fetch for increased concurrency.
  13964. */
  13965. async compileEquirectangularShader() {
  13966. if ( this._equirectMaterial === null ) {
  13967. this._equirectMaterial = _getEquirectMaterial();
  13968. await this._compileMaterial( this._equirectMaterial );
  13969. }
  13970. }
  13971. /**
  13972. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  13973. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  13974. * one of them will cause any others to also become unusable.
  13975. */
  13976. dispose() {
  13977. this._dispose();
  13978. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  13979. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  13980. if ( this._backgroundBox !== null ) {
  13981. this._backgroundBox.geometry.dispose();
  13982. this._backgroundBox.material.dispose();
  13983. }
  13984. }
  13985. // private interface
  13986. _setSize( cubeSize ) {
  13987. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  13988. this._cubeSize = Math.pow( 2, this._lodMax );
  13989. }
  13990. _dispose() {
  13991. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  13992. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  13993. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  13994. this._lodPlanes[ i ].dispose();
  13995. }
  13996. }
  13997. _cleanup( outputTarget ) {
  13998. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  13999. outputTarget.scissorTest = false;
  14000. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  14001. }
  14002. _fromTexture( texture, renderTarget ) {
  14003. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  14004. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  14005. } else { // Equirectangular
  14006. this._setSize( texture.image.width / 4 );
  14007. }
  14008. _oldTarget = this._renderer.getRenderTarget();
  14009. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  14010. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  14011. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  14012. this._textureToCubeUV( texture, cubeUVRenderTarget );
  14013. this._applyPMREM( cubeUVRenderTarget );
  14014. this._cleanup( cubeUVRenderTarget );
  14015. return cubeUVRenderTarget;
  14016. }
  14017. _allocateTargets() {
  14018. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  14019. const height = 4 * this._cubeSize;
  14020. const params = {
  14021. magFilter: LinearFilter,
  14022. minFilter: LinearFilter,
  14023. generateMipmaps: false,
  14024. type: HalfFloatType,
  14025. format: RGBAFormat,
  14026. colorSpace: LinearSRGBColorSpace,
  14027. //depthBuffer: false
  14028. };
  14029. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  14030. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  14031. if ( this._pingPongRenderTarget !== null ) {
  14032. this._dispose();
  14033. }
  14034. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  14035. const { _lodMax } = this;
  14036. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  14037. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  14038. }
  14039. return cubeUVRenderTarget;
  14040. }
  14041. async _compileMaterial( material ) {
  14042. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  14043. await this._renderer.compile( tmpMesh, _flatCamera );
  14044. }
  14045. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  14046. const cubeCamera = _cubeCamera;
  14047. cubeCamera.near = near;
  14048. cubeCamera.far = far;
  14049. // px, py, pz, nx, ny, nz
  14050. const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ];
  14051. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  14052. const renderer = this._renderer;
  14053. const originalAutoClear = renderer.autoClear;
  14054. renderer.getClearColor( _clearColor );
  14055. renderer.autoClear = false;
  14056. let backgroundBox = this._backgroundBox;
  14057. if ( backgroundBox === null ) {
  14058. const backgroundMaterial = new MeshBasicMaterial( {
  14059. name: 'PMREM.Background',
  14060. side: BackSide,
  14061. depthWrite: false,
  14062. depthTest: false
  14063. } );
  14064. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  14065. }
  14066. let useSolidColor = false;
  14067. const background = scene.background;
  14068. if ( background ) {
  14069. if ( background.isColor ) {
  14070. backgroundBox.material.color.copy( background );
  14071. scene.background = null;
  14072. useSolidColor = true;
  14073. }
  14074. } else {
  14075. backgroundBox.material.color.copy( _clearColor );
  14076. useSolidColor = true;
  14077. }
  14078. renderer.setRenderTarget( cubeUVRenderTarget );
  14079. renderer.clear();
  14080. if ( useSolidColor ) {
  14081. renderer.render( backgroundBox, cubeCamera );
  14082. }
  14083. for ( let i = 0; i < 6; i ++ ) {
  14084. const col = i % 3;
  14085. if ( col === 0 ) {
  14086. cubeCamera.up.set( 0, upSign[ i ], 0 );
  14087. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  14088. } else if ( col === 1 ) {
  14089. cubeCamera.up.set( 0, 0, upSign[ i ] );
  14090. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  14091. } else {
  14092. cubeCamera.up.set( 0, upSign[ i ], 0 );
  14093. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  14094. }
  14095. const size = this._cubeSize;
  14096. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  14097. renderer.render( scene, cubeCamera );
  14098. }
  14099. renderer.autoClear = originalAutoClear;
  14100. scene.background = background;
  14101. }
  14102. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  14103. const renderer = this._renderer;
  14104. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  14105. if ( isCubeTexture ) {
  14106. if ( this._cubemapMaterial === null ) {
  14107. this._cubemapMaterial = _getCubemapMaterial( texture );
  14108. }
  14109. } else {
  14110. if ( this._equirectMaterial === null ) {
  14111. this._equirectMaterial = _getEquirectMaterial( texture );
  14112. }
  14113. }
  14114. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  14115. material.fragmentNode.value = texture;
  14116. const mesh = this._lodMeshes[ 0 ];
  14117. mesh.material = material;
  14118. const size = this._cubeSize;
  14119. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  14120. renderer.setRenderTarget( cubeUVRenderTarget );
  14121. renderer.render( mesh, _flatCamera );
  14122. }
  14123. _applyPMREM( cubeUVRenderTarget ) {
  14124. const renderer = this._renderer;
  14125. const autoClear = renderer.autoClear;
  14126. renderer.autoClear = false;
  14127. const n = this._lodPlanes.length;
  14128. for ( let i = 1; i < n; i ++ ) {
  14129. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  14130. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  14131. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  14132. }
  14133. renderer.autoClear = autoClear;
  14134. }
  14135. /**
  14136. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  14137. * vertically and horizontally, but this breaks down on a cube. Here we apply
  14138. * the blur latitudinally (around the poles), and then longitudinally (towards
  14139. * the poles) to approximate the orthogonally-separable blur. It is least
  14140. * accurate at the poles, but still does a decent job.
  14141. */
  14142. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  14143. const pingPongRenderTarget = this._pingPongRenderTarget;
  14144. this._halfBlur(
  14145. cubeUVRenderTarget,
  14146. pingPongRenderTarget,
  14147. lodIn,
  14148. lodOut,
  14149. sigma,
  14150. 'latitudinal',
  14151. poleAxis );
  14152. this._halfBlur(
  14153. pingPongRenderTarget,
  14154. cubeUVRenderTarget,
  14155. lodOut,
  14156. lodOut,
  14157. sigma,
  14158. 'longitudinal',
  14159. poleAxis );
  14160. }
  14161. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  14162. const renderer = this._renderer;
  14163. const blurMaterial = this._blurMaterial;
  14164. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  14165. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  14166. }
  14167. // Number of standard deviations at which to cut off the discrete approximation.
  14168. const STANDARD_DEVIATIONS = 3;
  14169. const blurMesh = this._lodMeshes[ lodOut ];
  14170. blurMesh.material = blurMaterial;
  14171. const blurUniforms = blurMaterial.uniforms;
  14172. const pixels = this._sizeLods[ lodIn ] - 1;
  14173. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  14174. const sigmaPixels = sigmaRadians / radiansPerPixel;
  14175. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  14176. if ( samples > MAX_SAMPLES ) {
  14177. console.warn( `sigmaRadians, ${
  14178. sigmaRadians}, is too large and will clip, as it requested ${
  14179. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  14180. }
  14181. const weights = [];
  14182. let sum = 0;
  14183. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  14184. const x = i / sigmaPixels;
  14185. const weight = Math.exp( - x * x / 2 );
  14186. weights.push( weight );
  14187. if ( i === 0 ) {
  14188. sum += weight;
  14189. } else if ( i < samples ) {
  14190. sum += 2 * weight;
  14191. }
  14192. }
  14193. for ( let i = 0; i < weights.length; i ++ ) {
  14194. weights[ i ] = weights[ i ] / sum;
  14195. }
  14196. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  14197. blurUniforms.envMap.value = targetIn.texture;
  14198. blurUniforms.samples.value = samples;
  14199. blurUniforms.weights.array = weights;
  14200. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  14201. if ( poleAxis ) {
  14202. blurUniforms.poleAxis.value = poleAxis;
  14203. }
  14204. const { _lodMax } = this;
  14205. blurUniforms.dTheta.value = radiansPerPixel;
  14206. blurUniforms.mipInt.value = _lodMax - lodIn;
  14207. const outputSize = this._sizeLods[ lodOut ];
  14208. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  14209. const y = 4 * ( this._cubeSize - outputSize );
  14210. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  14211. renderer.setRenderTarget( targetOut );
  14212. renderer.render( blurMesh, _flatCamera );
  14213. }
  14214. }
  14215. function _createPlanes( lodMax ) {
  14216. const lodPlanes = [];
  14217. const sizeLods = [];
  14218. const sigmas = [];
  14219. const lodMeshes = [];
  14220. let lod = lodMax;
  14221. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  14222. for ( let i = 0; i < totalLods; i ++ ) {
  14223. const sizeLod = Math.pow( 2, lod );
  14224. sizeLods.push( sizeLod );
  14225. let sigma = 1.0 / sizeLod;
  14226. if ( i > lodMax - LOD_MIN ) {
  14227. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  14228. } else if ( i === 0 ) {
  14229. sigma = 0;
  14230. }
  14231. sigmas.push( sigma );
  14232. const texelSize = 1.0 / ( sizeLod - 2 );
  14233. const min = - texelSize;
  14234. const max = 1 + texelSize;
  14235. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  14236. const cubeFaces = 6;
  14237. const vertices = 6;
  14238. const positionSize = 3;
  14239. const uvSize = 2;
  14240. const faceIndexSize = 1;
  14241. const position = new Float32Array( positionSize * vertices * cubeFaces );
  14242. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  14243. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  14244. for ( let face = 0; face < cubeFaces; face ++ ) {
  14245. const x = ( face % 3 ) * 2 / 3 - 1;
  14246. const y = face > 2 ? 0 : - 1;
  14247. const coordinates = [
  14248. x, y, 0,
  14249. x + 2 / 3, y, 0,
  14250. x + 2 / 3, y + 1, 0,
  14251. x, y, 0,
  14252. x + 2 / 3, y + 1, 0,
  14253. x, y + 1, 0
  14254. ];
  14255. const faceIdx = _faceLib[ face ];
  14256. position.set( coordinates, positionSize * vertices * faceIdx );
  14257. uv.set( uv1, uvSize * vertices * faceIdx );
  14258. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  14259. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  14260. }
  14261. const planes = new BufferGeometry();
  14262. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  14263. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  14264. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  14265. lodPlanes.push( planes );
  14266. lodMeshes.push( new Mesh( planes, null ) );
  14267. if ( lod > LOD_MIN ) {
  14268. lod --;
  14269. }
  14270. }
  14271. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  14272. }
  14273. function _createRenderTarget( width, height, params ) {
  14274. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  14275. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  14276. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  14277. cubeUVRenderTarget.texture.isPMREMTexture = true;
  14278. cubeUVRenderTarget.scissorTest = true;
  14279. return cubeUVRenderTarget;
  14280. }
  14281. function _setViewport( target, x, y, width, height ) {
  14282. target.viewport.set( x, y, width, height );
  14283. target.scissor.set( x, y, width, height );
  14284. }
  14285. function _getMaterial( type ) {
  14286. const material = new NodeMaterial();
  14287. material.depthTest = false;
  14288. material.depthWrite = false;
  14289. material.blending = NoBlending;
  14290. material.name = `PMREM_${ type }`;
  14291. return material;
  14292. }
  14293. function _getBlurShader( lodMax, width, height ) {
  14294. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  14295. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  14296. const dTheta = uniform( 0 );
  14297. const n = float( MAX_SAMPLES );
  14298. const latitudinal = uniform( 0 ); // false, bool
  14299. const samples = uniform( 1 ); // int
  14300. const envMap = texture( null );
  14301. const mipInt = uniform( 0 ); // int
  14302. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  14303. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  14304. const CUBEUV_MAX_MIP = float( lodMax );
  14305. const materialUniforms = {
  14306. n,
  14307. latitudinal,
  14308. weights,
  14309. poleAxis,
  14310. outputDirection,
  14311. dTheta,
  14312. samples,
  14313. envMap,
  14314. mipInt,
  14315. CUBEUV_TEXEL_WIDTH,
  14316. CUBEUV_TEXEL_HEIGHT,
  14317. CUBEUV_MAX_MIP
  14318. };
  14319. const material = _getMaterial( 'blur' );
  14320. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  14321. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  14322. return material;
  14323. }
  14324. function _getCubemapMaterial( envTexture ) {
  14325. const material = _getMaterial( 'cubemap' );
  14326. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  14327. return material;
  14328. }
  14329. function _getEquirectMaterial( envTexture ) {
  14330. const material = _getMaterial( 'equirect' );
  14331. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  14332. return material;
  14333. }
  14334. const rendererCache = new WeakMap();
  14335. const typeFromLength = new Map( [
  14336. [ 2, 'vec2' ],
  14337. [ 3, 'vec3' ],
  14338. [ 4, 'vec4' ],
  14339. [ 9, 'mat3' ],
  14340. [ 16, 'mat4' ]
  14341. ] );
  14342. const typeFromArray = new Map( [
  14343. [ Int8Array, 'int' ],
  14344. [ Int16Array, 'int' ],
  14345. [ Int32Array, 'int' ],
  14346. [ Uint8Array, 'uint' ],
  14347. [ Uint16Array, 'uint' ],
  14348. [ Uint32Array, 'uint' ],
  14349. [ Float32Array, 'float' ]
  14350. ] );
  14351. const toFloat = ( value ) => {
  14352. if ( /e/g.test( value ) ) {
  14353. return String( value ).replace( /\+/g, '' );
  14354. } else {
  14355. value = Number( value );
  14356. return value + ( value % 1 ? '' : '.0' );
  14357. }
  14358. };
  14359. class NodeBuilder {
  14360. constructor( object, renderer, parser ) {
  14361. this.object = object;
  14362. this.material = ( object && object.material ) || null;
  14363. this.geometry = ( object && object.geometry ) || null;
  14364. this.renderer = renderer;
  14365. this.parser = parser;
  14366. this.scene = null;
  14367. this.camera = null;
  14368. this.nodes = [];
  14369. this.sequentialNodes = [];
  14370. this.updateNodes = [];
  14371. this.updateBeforeNodes = [];
  14372. this.updateAfterNodes = [];
  14373. this.hashNodes = {};
  14374. this.monitor = null;
  14375. this.lightsNode = null;
  14376. this.environmentNode = null;
  14377. this.fogNode = null;
  14378. this.clippingContext = null;
  14379. this.vertexShader = null;
  14380. this.fragmentShader = null;
  14381. this.computeShader = null;
  14382. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  14383. this.flowCode = { vertex: '', fragment: '', compute: '' };
  14384. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  14385. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  14386. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  14387. this.bindingsIndexes = {};
  14388. this.bindGroups = null;
  14389. this.attributes = [];
  14390. this.bufferAttributes = [];
  14391. this.varyings = [];
  14392. this.codes = {};
  14393. this.vars = {};
  14394. this.flow = { code: '' };
  14395. this.chaining = [];
  14396. this.stack = stack();
  14397. this.stacks = [];
  14398. this.tab = '\t';
  14399. this.currentFunctionNode = null;
  14400. this.context = {
  14401. material: this.material
  14402. };
  14403. this.cache = new NodeCache();
  14404. this.globalCache = this.cache;
  14405. this.flowsData = new WeakMap();
  14406. this.shaderStage = null;
  14407. this.buildStage = null;
  14408. this.useComparisonMethod = false;
  14409. }
  14410. getBindGroupsCache() {
  14411. let bindGroupsCache = rendererCache.get( this.renderer );
  14412. if ( bindGroupsCache === undefined ) {
  14413. bindGroupsCache = new ChainMap();
  14414. rendererCache.set( this.renderer, bindGroupsCache );
  14415. }
  14416. return bindGroupsCache;
  14417. }
  14418. createRenderTarget( width, height, options ) {
  14419. return new RenderTarget( width, height, options );
  14420. }
  14421. createCubeRenderTarget( size, options ) {
  14422. return new CubeRenderTarget( size, options );
  14423. }
  14424. createPMREMGenerator() {
  14425. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  14426. return new PMREMGenerator( this.renderer );
  14427. }
  14428. includes( node ) {
  14429. return this.nodes.includes( node );
  14430. }
  14431. _getBindGroup( groupName, bindings ) {
  14432. const bindGroupsCache = this.getBindGroupsCache();
  14433. //
  14434. const bindingsArray = [];
  14435. let sharedGroup = true;
  14436. for ( const binding of bindings ) {
  14437. bindingsArray.push( binding );
  14438. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  14439. }
  14440. //
  14441. let bindGroup;
  14442. if ( sharedGroup ) {
  14443. bindGroup = bindGroupsCache.get( bindingsArray );
  14444. if ( bindGroup === undefined ) {
  14445. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  14446. bindGroupsCache.set( bindingsArray, bindGroup );
  14447. }
  14448. } else {
  14449. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  14450. }
  14451. return bindGroup;
  14452. }
  14453. getBindGroupArray( groupName, shaderStage ) {
  14454. const bindings = this.bindings[ shaderStage ];
  14455. let bindGroup = bindings[ groupName ];
  14456. if ( bindGroup === undefined ) {
  14457. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  14458. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  14459. }
  14460. bindings[ groupName ] = bindGroup = [];
  14461. }
  14462. return bindGroup;
  14463. }
  14464. getBindings() {
  14465. let bindingsGroups = this.bindGroups;
  14466. if ( bindingsGroups === null ) {
  14467. const groups = {};
  14468. const bindings = this.bindings;
  14469. for ( const shaderStage of shaderStages ) {
  14470. for ( const groupName in bindings[ shaderStage ] ) {
  14471. const uniforms = bindings[ shaderStage ][ groupName ];
  14472. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  14473. groupUniforms.push( ...uniforms );
  14474. }
  14475. }
  14476. bindingsGroups = [];
  14477. for ( const groupName in groups ) {
  14478. const group = groups[ groupName ];
  14479. const bindingsGroup = this._getBindGroup( groupName, group );
  14480. bindingsGroups.push( bindingsGroup );
  14481. }
  14482. this.bindGroups = bindingsGroups;
  14483. }
  14484. return bindingsGroups;
  14485. }
  14486. sortBindingGroups() {
  14487. const bindingsGroups = this.getBindings();
  14488. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  14489. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  14490. const bindingGroup = bindingsGroups[ i ];
  14491. this.bindingsIndexes[ bindingGroup.name ].group = i;
  14492. bindingGroup.index = i;
  14493. }
  14494. }
  14495. setHashNode( node, hash ) {
  14496. this.hashNodes[ hash ] = node;
  14497. }
  14498. addNode( node ) {
  14499. if ( this.nodes.includes( node ) === false ) {
  14500. this.nodes.push( node );
  14501. this.setHashNode( node, node.getHash( this ) );
  14502. }
  14503. }
  14504. addSequentialNode( node ) {
  14505. if ( this.sequentialNodes.includes( node ) === false ) {
  14506. this.sequentialNodes.push( node );
  14507. }
  14508. }
  14509. buildUpdateNodes() {
  14510. for ( const node of this.nodes ) {
  14511. const updateType = node.getUpdateType();
  14512. if ( updateType !== NodeUpdateType.NONE ) {
  14513. this.updateNodes.push( node.getSelf() );
  14514. }
  14515. }
  14516. for ( const node of this.sequentialNodes ) {
  14517. const updateBeforeType = node.getUpdateBeforeType();
  14518. const updateAfterType = node.getUpdateAfterType();
  14519. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  14520. this.updateBeforeNodes.push( node.getSelf() );
  14521. }
  14522. if ( updateAfterType !== NodeUpdateType.NONE ) {
  14523. this.updateAfterNodes.push( node.getSelf() );
  14524. }
  14525. }
  14526. }
  14527. get currentNode() {
  14528. return this.chaining[ this.chaining.length - 1 ];
  14529. }
  14530. isFilteredTexture( texture ) {
  14531. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  14532. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  14533. }
  14534. addChain( node ) {
  14535. /*
  14536. if ( this.chaining.indexOf( node ) !== - 1 ) {
  14537. console.warn( 'Recursive node: ', node );
  14538. }
  14539. */
  14540. this.chaining.push( node );
  14541. }
  14542. removeChain( node ) {
  14543. const lastChain = this.chaining.pop();
  14544. if ( lastChain !== node ) {
  14545. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  14546. }
  14547. }
  14548. getMethod( method ) {
  14549. return method;
  14550. }
  14551. getNodeFromHash( hash ) {
  14552. return this.hashNodes[ hash ];
  14553. }
  14554. addFlow( shaderStage, node ) {
  14555. this.flowNodes[ shaderStage ].push( node );
  14556. return node;
  14557. }
  14558. setContext( context ) {
  14559. this.context = context;
  14560. }
  14561. getContext() {
  14562. return this.context;
  14563. }
  14564. getSharedContext() {
  14565. ({ ...this.context });
  14566. return this.context;
  14567. }
  14568. setCache( cache ) {
  14569. this.cache = cache;
  14570. }
  14571. getCache() {
  14572. return this.cache;
  14573. }
  14574. getCacheFromNode( node, parent = true ) {
  14575. const data = this.getDataFromNode( node );
  14576. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  14577. return data.cache;
  14578. }
  14579. isAvailable( /*name*/ ) {
  14580. return false;
  14581. }
  14582. getVertexIndex() {
  14583. console.warn( 'Abstract function.' );
  14584. }
  14585. getInstanceIndex() {
  14586. console.warn( 'Abstract function.' );
  14587. }
  14588. getDrawIndex() {
  14589. console.warn( 'Abstract function.' );
  14590. }
  14591. getFrontFacing() {
  14592. console.warn( 'Abstract function.' );
  14593. }
  14594. getFragCoord() {
  14595. console.warn( 'Abstract function.' );
  14596. }
  14597. isFlipY() {
  14598. return false;
  14599. }
  14600. increaseUsage( node ) {
  14601. const nodeData = this.getDataFromNode( node );
  14602. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  14603. return nodeData.usageCount;
  14604. }
  14605. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  14606. console.warn( 'Abstract function.' );
  14607. }
  14608. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  14609. console.warn( 'Abstract function.' );
  14610. }
  14611. generateConst( type, value = null ) {
  14612. if ( value === null ) {
  14613. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  14614. else if ( type === 'bool' ) value = false;
  14615. else if ( type === 'color' ) value = new Color();
  14616. else if ( type === 'vec2' ) value = new Vector2();
  14617. else if ( type === 'vec3' ) value = new Vector3();
  14618. else if ( type === 'vec4' ) value = new Vector4();
  14619. }
  14620. if ( type === 'float' ) return toFloat( value );
  14621. if ( type === 'int' ) return `${ Math.round( value ) }`;
  14622. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  14623. if ( type === 'bool' ) return value ? 'true' : 'false';
  14624. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  14625. const typeLength = this.getTypeLength( type );
  14626. const componentType = this.getComponentType( type );
  14627. const generateConst = value => this.generateConst( componentType, value );
  14628. if ( typeLength === 2 ) {
  14629. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  14630. } else if ( typeLength === 3 ) {
  14631. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  14632. } else if ( typeLength === 4 ) {
  14633. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  14634. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  14635. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  14636. } else if ( typeLength > 4 ) {
  14637. return `${ this.getType( type ) }()`;
  14638. }
  14639. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  14640. }
  14641. getType( type ) {
  14642. if ( type === 'color' ) return 'vec3';
  14643. return type;
  14644. }
  14645. hasGeometryAttribute( name ) {
  14646. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  14647. }
  14648. getAttribute( name, type ) {
  14649. const attributes = this.attributes;
  14650. // find attribute
  14651. for ( const attribute of attributes ) {
  14652. if ( attribute.name === name ) {
  14653. return attribute;
  14654. }
  14655. }
  14656. // create a new if no exist
  14657. const attribute = new NodeAttribute( name, type );
  14658. attributes.push( attribute );
  14659. return attribute;
  14660. }
  14661. getPropertyName( node/*, shaderStage*/ ) {
  14662. return node.name;
  14663. }
  14664. isVector( type ) {
  14665. return /vec\d/.test( type );
  14666. }
  14667. isMatrix( type ) {
  14668. return /mat\d/.test( type );
  14669. }
  14670. isReference( type ) {
  14671. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  14672. }
  14673. needsToWorkingColorSpace( /*texture*/ ) {
  14674. return false;
  14675. }
  14676. getComponentTypeFromTexture( texture ) {
  14677. const type = texture.type;
  14678. if ( texture.isDataTexture ) {
  14679. if ( type === IntType ) return 'int';
  14680. if ( type === UnsignedIntType ) return 'uint';
  14681. }
  14682. return 'float';
  14683. }
  14684. getElementType( type ) {
  14685. if ( type === 'mat2' ) return 'vec2';
  14686. if ( type === 'mat3' ) return 'vec3';
  14687. if ( type === 'mat4' ) return 'vec4';
  14688. return this.getComponentType( type );
  14689. }
  14690. getComponentType( type ) {
  14691. type = this.getVectorType( type );
  14692. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  14693. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  14694. if ( componentType === null ) return null;
  14695. if ( componentType[ 1 ] === 'b' ) return 'bool';
  14696. if ( componentType[ 1 ] === 'i' ) return 'int';
  14697. if ( componentType[ 1 ] === 'u' ) return 'uint';
  14698. return 'float';
  14699. }
  14700. getVectorType( type ) {
  14701. if ( type === 'color' ) return 'vec3';
  14702. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  14703. return type;
  14704. }
  14705. getTypeFromLength( length, componentType = 'float' ) {
  14706. if ( length === 1 ) return componentType;
  14707. const baseType = typeFromLength.get( length );
  14708. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  14709. return prefix + baseType;
  14710. }
  14711. getTypeFromArray( array ) {
  14712. return typeFromArray.get( array.constructor );
  14713. }
  14714. getTypeFromAttribute( attribute ) {
  14715. let dataAttribute = attribute;
  14716. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  14717. const array = dataAttribute.array;
  14718. const itemSize = attribute.itemSize;
  14719. const normalized = attribute.normalized;
  14720. let arrayType;
  14721. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  14722. arrayType = this.getTypeFromArray( array );
  14723. }
  14724. return this.getTypeFromLength( itemSize, arrayType );
  14725. }
  14726. getTypeLength( type ) {
  14727. const vecType = this.getVectorType( type );
  14728. const vecNum = /vec([2-4])/.exec( vecType );
  14729. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  14730. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  14731. if ( /mat2/.test( type ) === true ) return 4;
  14732. if ( /mat3/.test( type ) === true ) return 9;
  14733. if ( /mat4/.test( type ) === true ) return 16;
  14734. return 0;
  14735. }
  14736. getVectorFromMatrix( type ) {
  14737. return type.replace( 'mat', 'vec' );
  14738. }
  14739. changeComponentType( type, newComponentType ) {
  14740. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  14741. }
  14742. getIntegerType( type ) {
  14743. const componentType = this.getComponentType( type );
  14744. if ( componentType === 'int' || componentType === 'uint' ) return type;
  14745. return this.changeComponentType( type, 'int' );
  14746. }
  14747. addStack() {
  14748. this.stack = stack( this.stack );
  14749. this.stacks.push( getCurrentStack() || this.stack );
  14750. setCurrentStack( this.stack );
  14751. return this.stack;
  14752. }
  14753. removeStack() {
  14754. const lastStack = this.stack;
  14755. this.stack = lastStack.parent;
  14756. setCurrentStack( this.stacks.pop() );
  14757. return lastStack;
  14758. }
  14759. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  14760. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  14761. let nodeData = cache.getData( node );
  14762. if ( nodeData === undefined ) {
  14763. nodeData = {};
  14764. cache.setData( node, nodeData );
  14765. }
  14766. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  14767. return nodeData[ shaderStage ];
  14768. }
  14769. getNodeProperties( node, shaderStage = 'any' ) {
  14770. const nodeData = this.getDataFromNode( node, shaderStage );
  14771. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  14772. }
  14773. getBufferAttributeFromNode( node, type ) {
  14774. const nodeData = this.getDataFromNode( node );
  14775. let bufferAttribute = nodeData.bufferAttribute;
  14776. if ( bufferAttribute === undefined ) {
  14777. const index = this.uniforms.index ++;
  14778. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  14779. this.bufferAttributes.push( bufferAttribute );
  14780. nodeData.bufferAttribute = bufferAttribute;
  14781. }
  14782. return bufferAttribute;
  14783. }
  14784. getStructTypeFromNode( node, shaderStage = this.shaderStage ) {
  14785. const nodeData = this.getDataFromNode( node, shaderStage );
  14786. if ( nodeData.structType === undefined ) {
  14787. const index = this.structs.index ++;
  14788. node.name = `StructType${ index }`;
  14789. this.structs[ shaderStage ].push( node );
  14790. nodeData.structType = node;
  14791. }
  14792. return node;
  14793. }
  14794. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  14795. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  14796. let nodeUniform = nodeData.uniform;
  14797. if ( nodeUniform === undefined ) {
  14798. const index = this.uniforms.index ++;
  14799. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  14800. this.uniforms[ shaderStage ].push( nodeUniform );
  14801. nodeData.uniform = nodeUniform;
  14802. }
  14803. return nodeUniform;
  14804. }
  14805. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  14806. const nodeData = this.getDataFromNode( node, shaderStage );
  14807. let nodeVar = nodeData.variable;
  14808. if ( nodeVar === undefined ) {
  14809. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  14810. if ( name === null ) name = 'nodeVar' + vars.length;
  14811. nodeVar = new NodeVar( name, type );
  14812. vars.push( nodeVar );
  14813. nodeData.variable = nodeVar;
  14814. }
  14815. return nodeVar;
  14816. }
  14817. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  14818. const nodeData = this.getDataFromNode( node, 'any' );
  14819. let nodeVarying = nodeData.varying;
  14820. if ( nodeVarying === undefined ) {
  14821. const varyings = this.varyings;
  14822. const index = varyings.length;
  14823. if ( name === null ) name = 'nodeVarying' + index;
  14824. nodeVarying = new NodeVarying( name, type );
  14825. varyings.push( nodeVarying );
  14826. nodeData.varying = nodeVarying;
  14827. }
  14828. return nodeVarying;
  14829. }
  14830. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  14831. const nodeData = this.getDataFromNode( node );
  14832. let nodeCode = nodeData.code;
  14833. if ( nodeCode === undefined ) {
  14834. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  14835. const index = codes.length;
  14836. nodeCode = new NodeCode( 'nodeCode' + index, type );
  14837. codes.push( nodeCode );
  14838. nodeData.code = nodeCode;
  14839. }
  14840. return nodeCode;
  14841. }
  14842. addFlowCodeHierarchy( node, nodeBlock ) {
  14843. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  14844. let needsFlowCode = true;
  14845. let nodeBlockHierarchy = nodeBlock;
  14846. while ( nodeBlockHierarchy ) {
  14847. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  14848. needsFlowCode = false;
  14849. break;
  14850. }
  14851. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  14852. }
  14853. if ( needsFlowCode ) {
  14854. for ( const flowCode of flowCodes ) {
  14855. this.addLineFlowCode( flowCode );
  14856. }
  14857. }
  14858. }
  14859. addLineFlowCodeBlock( node, code, nodeBlock ) {
  14860. const nodeData = this.getDataFromNode( node );
  14861. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  14862. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  14863. flowCodes.push( code );
  14864. codeBlock.set( nodeBlock, true );
  14865. }
  14866. addLineFlowCode( code, node = null ) {
  14867. if ( code === '' ) return this;
  14868. if ( node !== null && this.context.nodeBlock ) {
  14869. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  14870. }
  14871. code = this.tab + code;
  14872. if ( ! /;\s*$/.test( code ) ) {
  14873. code = code + ';\n';
  14874. }
  14875. this.flow.code += code;
  14876. return this;
  14877. }
  14878. addFlowCode( code ) {
  14879. this.flow.code += code;
  14880. return this;
  14881. }
  14882. addFlowTab() {
  14883. this.tab += '\t';
  14884. return this;
  14885. }
  14886. removeFlowTab() {
  14887. this.tab = this.tab.slice( 0, - 1 );
  14888. return this;
  14889. }
  14890. getFlowData( node/*, shaderStage*/ ) {
  14891. return this.flowsData.get( node );
  14892. }
  14893. flowNode( node ) {
  14894. const output = node.getNodeType( this );
  14895. const flowData = this.flowChildNode( node, output );
  14896. this.flowsData.set( node, flowData );
  14897. return flowData;
  14898. }
  14899. buildFunctionNode( shaderNode ) {
  14900. const fn = new FunctionNode();
  14901. const previous = this.currentFunctionNode;
  14902. this.currentFunctionNode = fn;
  14903. fn.code = this.buildFunctionCode( shaderNode );
  14904. this.currentFunctionNode = previous;
  14905. return fn;
  14906. }
  14907. flowShaderNode( shaderNode ) {
  14908. const layout = shaderNode.layout;
  14909. const inputs = {
  14910. [ Symbol.iterator ]() {
  14911. let index = 0;
  14912. const values = Object.values( this );
  14913. return {
  14914. next: () => ( {
  14915. value: values[ index ],
  14916. done: index ++ >= values.length
  14917. } )
  14918. };
  14919. }
  14920. };
  14921. for ( const input of layout.inputs ) {
  14922. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  14923. }
  14924. //
  14925. shaderNode.layout = null;
  14926. const callNode = shaderNode.call( inputs );
  14927. const flowData = this.flowStagesNode( callNode, layout.type );
  14928. shaderNode.layout = layout;
  14929. return flowData;
  14930. }
  14931. flowStagesNode( node, output = null ) {
  14932. const previousFlow = this.flow;
  14933. const previousVars = this.vars;
  14934. const previousCache = this.cache;
  14935. const previousBuildStage = this.buildStage;
  14936. const previousStack = this.stack;
  14937. const flow = {
  14938. code: ''
  14939. };
  14940. this.flow = flow;
  14941. this.vars = {};
  14942. this.cache = new NodeCache();
  14943. this.stack = stack();
  14944. for ( const buildStage of defaultBuildStages ) {
  14945. this.setBuildStage( buildStage );
  14946. flow.result = node.build( this, output );
  14947. }
  14948. flow.vars = this.getVars( this.shaderStage );
  14949. this.flow = previousFlow;
  14950. this.vars = previousVars;
  14951. this.cache = previousCache;
  14952. this.stack = previousStack;
  14953. this.setBuildStage( previousBuildStage );
  14954. return flow;
  14955. }
  14956. getFunctionOperator() {
  14957. return null;
  14958. }
  14959. flowChildNode( node, output = null ) {
  14960. const previousFlow = this.flow;
  14961. const flow = {
  14962. code: ''
  14963. };
  14964. this.flow = flow;
  14965. flow.result = node.build( this, output );
  14966. this.flow = previousFlow;
  14967. return flow;
  14968. }
  14969. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  14970. const previousShaderStage = this.shaderStage;
  14971. this.setShaderStage( shaderStage );
  14972. const flowData = this.flowChildNode( node, output );
  14973. if ( propertyName !== null ) {
  14974. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  14975. }
  14976. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  14977. this.setShaderStage( previousShaderStage );
  14978. return flowData;
  14979. }
  14980. getAttributesArray() {
  14981. return this.attributes.concat( this.bufferAttributes );
  14982. }
  14983. getAttributes( /*shaderStage*/ ) {
  14984. console.warn( 'Abstract function.' );
  14985. }
  14986. getVaryings( /*shaderStage*/ ) {
  14987. console.warn( 'Abstract function.' );
  14988. }
  14989. getVar( type, name ) {
  14990. return `${ this.getType( type ) } ${ name }`;
  14991. }
  14992. getVars( shaderStage ) {
  14993. let snippet = '';
  14994. const vars = this.vars[ shaderStage ];
  14995. if ( vars !== undefined ) {
  14996. for ( const variable of vars ) {
  14997. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  14998. }
  14999. }
  15000. return snippet;
  15001. }
  15002. getUniforms( /*shaderStage*/ ) {
  15003. console.warn( 'Abstract function.' );
  15004. }
  15005. getCodes( shaderStage ) {
  15006. const codes = this.codes[ shaderStage ];
  15007. let code = '';
  15008. if ( codes !== undefined ) {
  15009. for ( const nodeCode of codes ) {
  15010. code += nodeCode.code + '\n';
  15011. }
  15012. }
  15013. return code;
  15014. }
  15015. getHash() {
  15016. return this.vertexShader + this.fragmentShader + this.computeShader;
  15017. }
  15018. setShaderStage( shaderStage ) {
  15019. this.shaderStage = shaderStage;
  15020. }
  15021. getShaderStage() {
  15022. return this.shaderStage;
  15023. }
  15024. setBuildStage( buildStage ) {
  15025. this.buildStage = buildStage;
  15026. }
  15027. getBuildStage() {
  15028. return this.buildStage;
  15029. }
  15030. buildCode() {
  15031. console.warn( 'Abstract function.' );
  15032. }
  15033. build() {
  15034. const { object, material, renderer } = this;
  15035. if ( material !== null ) {
  15036. let nodeMaterial = renderer.library.fromMaterial( material );
  15037. if ( nodeMaterial === null ) {
  15038. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  15039. nodeMaterial = new NodeMaterial();
  15040. }
  15041. nodeMaterial.build( this );
  15042. } else {
  15043. this.addFlow( 'compute', object );
  15044. }
  15045. // setup() -> stage 1: create possible new nodes and returns an output reference node
  15046. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  15047. // generate() -> stage 3: generate shader
  15048. for ( const buildStage of defaultBuildStages ) {
  15049. this.setBuildStage( buildStage );
  15050. if ( this.context.vertex && this.context.vertex.isNode ) {
  15051. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  15052. }
  15053. for ( const shaderStage of shaderStages ) {
  15054. this.setShaderStage( shaderStage );
  15055. const flowNodes = this.flowNodes[ shaderStage ];
  15056. for ( const node of flowNodes ) {
  15057. if ( buildStage === 'generate' ) {
  15058. this.flowNode( node );
  15059. } else {
  15060. node.build( this );
  15061. }
  15062. }
  15063. }
  15064. }
  15065. this.setBuildStage( null );
  15066. this.setShaderStage( null );
  15067. // stage 4: build code for a specific output
  15068. this.buildCode();
  15069. this.buildUpdateNodes();
  15070. return this;
  15071. }
  15072. getNodeUniform( uniformNode, type ) {
  15073. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  15074. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  15075. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  15076. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  15077. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  15078. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  15079. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  15080. throw new Error( `Uniform "${type}" not declared.` );
  15081. }
  15082. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  15083. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  15084. }
  15085. format( snippet, fromType, toType ) {
  15086. fromType = this.getVectorType( fromType );
  15087. toType = this.getVectorType( toType );
  15088. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  15089. return snippet;
  15090. }
  15091. const fromTypeLength = this.getTypeLength( fromType );
  15092. const toTypeLength = this.getTypeLength( toType );
  15093. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  15094. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  15095. }
  15096. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  15097. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  15098. }
  15099. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  15100. // @TODO: ignore for now
  15101. return snippet;
  15102. }
  15103. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  15104. // @TODO: ignore for now
  15105. return snippet;
  15106. }
  15107. if ( fromTypeLength === toTypeLength ) {
  15108. return `${ this.getType( toType ) }( ${ snippet } )`;
  15109. }
  15110. if ( fromTypeLength > toTypeLength ) {
  15111. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  15112. }
  15113. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  15114. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  15115. }
  15116. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  15117. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  15118. }
  15119. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  15120. // convert a number value to vector type, e.g:
  15121. // vec3( 1u ) -> vec3( float( 1u ) )
  15122. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  15123. }
  15124. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  15125. }
  15126. getSignature() {
  15127. return `// Three.js r${ REVISION } - Node System\n`;
  15128. }
  15129. }
  15130. class NodeFrame {
  15131. constructor() {
  15132. this.time = 0;
  15133. this.deltaTime = 0;
  15134. this.frameId = 0;
  15135. this.renderId = 0;
  15136. this.startTime = null;
  15137. this.updateMap = new WeakMap();
  15138. this.updateBeforeMap = new WeakMap();
  15139. this.updateAfterMap = new WeakMap();
  15140. this.renderer = null;
  15141. this.material = null;
  15142. this.camera = null;
  15143. this.object = null;
  15144. this.scene = null;
  15145. }
  15146. _getMaps( referenceMap, nodeRef ) {
  15147. let maps = referenceMap.get( nodeRef );
  15148. if ( maps === undefined ) {
  15149. maps = {
  15150. renderMap: new WeakMap(),
  15151. frameMap: new WeakMap()
  15152. };
  15153. referenceMap.set( nodeRef, maps );
  15154. }
  15155. return maps;
  15156. }
  15157. updateBeforeNode( node ) {
  15158. const updateType = node.getUpdateBeforeType();
  15159. const reference = node.updateReference( this );
  15160. if ( updateType === NodeUpdateType.FRAME ) {
  15161. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  15162. if ( frameMap.get( reference ) !== this.frameId ) {
  15163. if ( node.updateBefore( this ) !== false ) {
  15164. frameMap.set( reference, this.frameId );
  15165. }
  15166. }
  15167. } else if ( updateType === NodeUpdateType.RENDER ) {
  15168. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  15169. if ( renderMap.get( reference ) !== this.renderId ) {
  15170. if ( node.updateBefore( this ) !== false ) {
  15171. renderMap.set( reference, this.renderId );
  15172. }
  15173. }
  15174. } else if ( updateType === NodeUpdateType.OBJECT ) {
  15175. node.updateBefore( this );
  15176. }
  15177. }
  15178. updateAfterNode( node ) {
  15179. const updateType = node.getUpdateAfterType();
  15180. const reference = node.updateReference( this );
  15181. if ( updateType === NodeUpdateType.FRAME ) {
  15182. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  15183. if ( frameMap.get( reference ) !== this.frameId ) {
  15184. if ( node.updateAfter( this ) !== false ) {
  15185. frameMap.set( reference, this.frameId );
  15186. }
  15187. }
  15188. } else if ( updateType === NodeUpdateType.RENDER ) {
  15189. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  15190. if ( renderMap.get( reference ) !== this.renderId ) {
  15191. if ( node.updateAfter( this ) !== false ) {
  15192. renderMap.set( reference, this.renderId );
  15193. }
  15194. }
  15195. } else if ( updateType === NodeUpdateType.OBJECT ) {
  15196. node.updateAfter( this );
  15197. }
  15198. }
  15199. updateNode( node ) {
  15200. const updateType = node.getUpdateType();
  15201. const reference = node.updateReference( this );
  15202. if ( updateType === NodeUpdateType.FRAME ) {
  15203. const { frameMap } = this._getMaps( this.updateMap, reference );
  15204. if ( frameMap.get( reference ) !== this.frameId ) {
  15205. if ( node.update( this ) !== false ) {
  15206. frameMap.set( reference, this.frameId );
  15207. }
  15208. }
  15209. } else if ( updateType === NodeUpdateType.RENDER ) {
  15210. const { renderMap } = this._getMaps( this.updateMap, reference );
  15211. if ( renderMap.get( reference ) !== this.renderId ) {
  15212. if ( node.update( this ) !== false ) {
  15213. renderMap.set( reference, this.renderId );
  15214. }
  15215. }
  15216. } else if ( updateType === NodeUpdateType.OBJECT ) {
  15217. node.update( this );
  15218. }
  15219. }
  15220. update() {
  15221. this.frameId ++;
  15222. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  15223. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  15224. this.lastTime = performance.now();
  15225. this.time += this.deltaTime;
  15226. }
  15227. }
  15228. class NodeFunctionInput {
  15229. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  15230. this.type = type;
  15231. this.name = name;
  15232. this.count = count;
  15233. this.qualifier = qualifier;
  15234. this.isConst = isConst;
  15235. }
  15236. }
  15237. NodeFunctionInput.isNodeFunctionInput = true;
  15238. class DirectionalLightNode extends AnalyticLightNode {
  15239. static get type() {
  15240. return 'DirectionalLightNode';
  15241. }
  15242. constructor( light = null ) {
  15243. super( light );
  15244. }
  15245. setup( builder ) {
  15246. super.setup( builder );
  15247. const lightingModel = builder.context.lightingModel;
  15248. const lightColor = this.colorNode;
  15249. const lightDirection = lightTargetDirection( this.light );
  15250. const reflectedLight = builder.context.reflectedLight;
  15251. lightingModel.direct( {
  15252. lightDirection,
  15253. lightColor,
  15254. reflectedLight
  15255. }, builder.stack, builder );
  15256. }
  15257. }
  15258. const _matrix41 = /*@__PURE__*/ new Matrix4();
  15259. const _matrix42 = /*@__PURE__*/ new Matrix4();
  15260. let ltcLib = null;
  15261. class RectAreaLightNode extends AnalyticLightNode {
  15262. static get type() {
  15263. return 'RectAreaLightNode';
  15264. }
  15265. constructor( light = null ) {
  15266. super( light );
  15267. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  15268. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  15269. this.updateType = NodeUpdateType.RENDER;
  15270. }
  15271. update( frame ) {
  15272. super.update( frame );
  15273. const { light } = this;
  15274. const viewMatrix = frame.camera.matrixWorldInverse;
  15275. _matrix42.identity();
  15276. _matrix41.copy( light.matrixWorld );
  15277. _matrix41.premultiply( viewMatrix );
  15278. _matrix42.extractRotation( _matrix41 );
  15279. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  15280. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  15281. this.halfWidth.value.applyMatrix4( _matrix42 );
  15282. this.halfHeight.value.applyMatrix4( _matrix42 );
  15283. }
  15284. setup( builder ) {
  15285. super.setup( builder );
  15286. let ltc_1, ltc_2;
  15287. if ( builder.isAvailable( 'float32Filterable' ) ) {
  15288. ltc_1 = texture( ltcLib.LTC_FLOAT_1 );
  15289. ltc_2 = texture( ltcLib.LTC_FLOAT_2 );
  15290. } else {
  15291. ltc_1 = texture( ltcLib.LTC_HALF_1 );
  15292. ltc_2 = texture( ltcLib.LTC_HALF_2 );
  15293. }
  15294. const { colorNode, light } = this;
  15295. const lightingModel = builder.context.lightingModel;
  15296. const lightPosition = lightViewPosition( light );
  15297. const reflectedLight = builder.context.reflectedLight;
  15298. lightingModel.directRectArea( {
  15299. lightColor: colorNode,
  15300. lightPosition,
  15301. halfWidth: this.halfWidth,
  15302. halfHeight: this.halfHeight,
  15303. reflectedLight,
  15304. ltc_1,
  15305. ltc_2
  15306. }, builder.stack, builder );
  15307. }
  15308. static setLTC( ltc ) {
  15309. ltcLib = ltc;
  15310. }
  15311. }
  15312. class SpotLightNode extends AnalyticLightNode {
  15313. static get type() {
  15314. return 'SpotLightNode';
  15315. }
  15316. constructor( light = null ) {
  15317. super( light );
  15318. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  15319. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  15320. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  15321. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  15322. }
  15323. update( frame ) {
  15324. super.update( frame );
  15325. const { light } = this;
  15326. this.coneCosNode.value = Math.cos( light.angle );
  15327. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  15328. this.cutoffDistanceNode.value = light.distance;
  15329. this.decayExponentNode.value = light.decay;
  15330. }
  15331. getSpotAttenuation( angleCosine ) {
  15332. const { coneCosNode, penumbraCosNode } = this;
  15333. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  15334. }
  15335. setup( builder ) {
  15336. super.setup( builder );
  15337. const lightingModel = builder.context.lightingModel;
  15338. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  15339. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  15340. const lightDirection = lVector.normalize();
  15341. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  15342. const spotAttenuation = this.getSpotAttenuation( angleCos );
  15343. const lightDistance = lVector.length();
  15344. const lightAttenuation = getDistanceAttenuation( {
  15345. lightDistance,
  15346. cutoffDistance: cutoffDistanceNode,
  15347. decayExponent: decayExponentNode
  15348. } );
  15349. const lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  15350. const reflectedLight = builder.context.reflectedLight;
  15351. lightingModel.direct( {
  15352. lightDirection,
  15353. lightColor,
  15354. reflectedLight
  15355. }, builder.stack, builder );
  15356. }
  15357. }
  15358. class IESSpotLightNode extends SpotLightNode {
  15359. static get type() {
  15360. return 'IESSpotLightNode';
  15361. }
  15362. getSpotAttenuation( angleCosine ) {
  15363. const iesMap = this.light.iesMap;
  15364. let spotAttenuation = null;
  15365. if ( iesMap && iesMap.isTexture === true ) {
  15366. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  15367. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  15368. } else {
  15369. spotAttenuation = super.getSpotAttenuation( angleCosine );
  15370. }
  15371. return spotAttenuation;
  15372. }
  15373. }
  15374. class AmbientLightNode extends AnalyticLightNode {
  15375. static get type() {
  15376. return 'AmbientLightNode';
  15377. }
  15378. constructor( light = null ) {
  15379. super( light );
  15380. }
  15381. setup( { context } ) {
  15382. context.irradiance.addAssign( this.colorNode );
  15383. }
  15384. }
  15385. class HemisphereLightNode extends AnalyticLightNode {
  15386. static get type() {
  15387. return 'HemisphereLightNode';
  15388. }
  15389. constructor( light = null ) {
  15390. super( light );
  15391. this.lightPositionNode = lightPosition( light );
  15392. this.lightDirectionNode = this.lightPositionNode.normalize();
  15393. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  15394. }
  15395. update( frame ) {
  15396. const { light } = this;
  15397. super.update( frame );
  15398. this.lightPositionNode.object3d = light;
  15399. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  15400. }
  15401. setup( builder ) {
  15402. const { colorNode, groundColorNode, lightDirectionNode } = this;
  15403. const dotNL = normalView.dot( lightDirectionNode );
  15404. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  15405. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  15406. builder.context.irradiance.addAssign( irradiance );
  15407. }
  15408. }
  15409. class LightProbeNode extends AnalyticLightNode {
  15410. static get type() {
  15411. return 'LightProbeNode';
  15412. }
  15413. constructor( light = null ) {
  15414. super( light );
  15415. const array = [];
  15416. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  15417. this.lightProbe = uniformArray( array );
  15418. }
  15419. update( frame ) {
  15420. const { light } = this;
  15421. super.update( frame );
  15422. //
  15423. for ( let i = 0; i < 9; i ++ ) {
  15424. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  15425. }
  15426. }
  15427. setup( builder ) {
  15428. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  15429. builder.context.irradiance.addAssign( irradiance );
  15430. }
  15431. }
  15432. class NodeParser {
  15433. parseFunction( /*source*/ ) {
  15434. console.warn( 'Abstract function.' );
  15435. }
  15436. }
  15437. class NodeFunction {
  15438. constructor( type, inputs, name = '', precision = '' ) {
  15439. this.type = type;
  15440. this.inputs = inputs;
  15441. this.name = name;
  15442. this.precision = precision;
  15443. }
  15444. getCode( /*name = this.name*/ ) {
  15445. console.warn( 'Abstract function.' );
  15446. }
  15447. }
  15448. NodeFunction.isNodeFunction = true;
  15449. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  15450. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  15451. const pragmaMain = '#pragma main';
  15452. const parse$1 = ( source ) => {
  15453. source = source.trim();
  15454. const pragmaMainIndex = source.indexOf( pragmaMain );
  15455. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  15456. const declaration = mainCode.match( declarationRegexp$1 );
  15457. if ( declaration !== null && declaration.length === 5 ) {
  15458. // tokenizer
  15459. const inputsCode = declaration[ 4 ];
  15460. const propsMatches = [];
  15461. let nameMatch = null;
  15462. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  15463. propsMatches.push( nameMatch );
  15464. }
  15465. // parser
  15466. const inputs = [];
  15467. let i = 0;
  15468. while ( i < propsMatches.length ) {
  15469. const isConst = propsMatches[ i ][ 0 ] === 'const';
  15470. if ( isConst === true ) {
  15471. i ++;
  15472. }
  15473. let qualifier = propsMatches[ i ][ 0 ];
  15474. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  15475. i ++;
  15476. } else {
  15477. qualifier = '';
  15478. }
  15479. const type = propsMatches[ i ++ ][ 0 ];
  15480. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  15481. if ( Number.isNaN( count ) === false ) i ++;
  15482. else count = null;
  15483. const name = propsMatches[ i ++ ][ 0 ];
  15484. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  15485. }
  15486. //
  15487. const blockCode = mainCode.substring( declaration[ 0 ].length );
  15488. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  15489. const type = declaration[ 2 ];
  15490. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  15491. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  15492. return {
  15493. type,
  15494. inputs,
  15495. name,
  15496. precision,
  15497. inputsCode,
  15498. blockCode,
  15499. headerCode
  15500. };
  15501. } else {
  15502. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  15503. }
  15504. };
  15505. class GLSLNodeFunction extends NodeFunction {
  15506. constructor( source ) {
  15507. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  15508. super( type, inputs, name, precision );
  15509. this.inputsCode = inputsCode;
  15510. this.blockCode = blockCode;
  15511. this.headerCode = headerCode;
  15512. }
  15513. getCode( name = this.name ) {
  15514. let code;
  15515. const blockCode = this.blockCode;
  15516. if ( blockCode !== '' ) {
  15517. const { type, inputsCode, headerCode, precision } = this;
  15518. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  15519. if ( precision !== '' ) {
  15520. declarationCode = `${ precision } ${ declarationCode }`;
  15521. }
  15522. code = headerCode + declarationCode + blockCode;
  15523. } else {
  15524. // interface function
  15525. code = '';
  15526. }
  15527. return code;
  15528. }
  15529. }
  15530. class GLSLNodeParser extends NodeParser {
  15531. parseFunction( source ) {
  15532. return new GLSLNodeFunction( source );
  15533. }
  15534. }
  15535. const outputNodeMap = new WeakMap();
  15536. class Nodes extends DataMap {
  15537. constructor( renderer, backend ) {
  15538. super();
  15539. this.renderer = renderer;
  15540. this.backend = backend;
  15541. this.nodeFrame = new NodeFrame();
  15542. this.nodeBuilderCache = new Map();
  15543. this.callHashCache = new ChainMap();
  15544. this.groupsData = new ChainMap();
  15545. }
  15546. updateGroup( nodeUniformsGroup ) {
  15547. const groupNode = nodeUniformsGroup.groupNode;
  15548. const name = groupNode.name;
  15549. // objectGroup is every updated
  15550. if ( name === objectGroup.name ) return true;
  15551. // renderGroup is updated once per render/compute call
  15552. if ( name === renderGroup.name ) {
  15553. const uniformsGroupData = this.get( nodeUniformsGroup );
  15554. const renderId = this.nodeFrame.renderId;
  15555. if ( uniformsGroupData.renderId !== renderId ) {
  15556. uniformsGroupData.renderId = renderId;
  15557. return true;
  15558. }
  15559. return false;
  15560. }
  15561. // frameGroup is updated once per frame
  15562. if ( name === frameGroup.name ) {
  15563. const uniformsGroupData = this.get( nodeUniformsGroup );
  15564. const frameId = this.nodeFrame.frameId;
  15565. if ( uniformsGroupData.frameId !== frameId ) {
  15566. uniformsGroupData.frameId = frameId;
  15567. return true;
  15568. }
  15569. return false;
  15570. }
  15571. // other groups are updated just when groupNode.needsUpdate is true
  15572. const groupChain = [ groupNode, nodeUniformsGroup ];
  15573. let groupData = this.groupsData.get( groupChain );
  15574. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  15575. if ( groupData.version !== groupNode.version ) {
  15576. groupData.version = groupNode.version;
  15577. return true;
  15578. }
  15579. return false;
  15580. }
  15581. getForRenderCacheKey( renderObject ) {
  15582. return renderObject.initialCacheKey;
  15583. }
  15584. getForRender( renderObject ) {
  15585. const renderObjectData = this.get( renderObject );
  15586. let nodeBuilderState = renderObjectData.nodeBuilderState;
  15587. if ( nodeBuilderState === undefined ) {
  15588. const { nodeBuilderCache } = this;
  15589. const cacheKey = this.getForRenderCacheKey( renderObject );
  15590. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  15591. if ( nodeBuilderState === undefined ) {
  15592. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  15593. nodeBuilder.scene = renderObject.scene;
  15594. nodeBuilder.material = renderObject.material;
  15595. nodeBuilder.camera = renderObject.camera;
  15596. nodeBuilder.context.material = renderObject.material;
  15597. nodeBuilder.lightsNode = renderObject.lightsNode;
  15598. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  15599. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  15600. nodeBuilder.clippingContext = renderObject.clippingContext;
  15601. nodeBuilder.build();
  15602. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  15603. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  15604. }
  15605. nodeBuilderState.usedTimes ++;
  15606. renderObjectData.nodeBuilderState = nodeBuilderState;
  15607. }
  15608. return nodeBuilderState;
  15609. }
  15610. delete( object ) {
  15611. if ( object.isRenderObject ) {
  15612. const nodeBuilderState = this.get( object ).nodeBuilderState;
  15613. nodeBuilderState.usedTimes --;
  15614. if ( nodeBuilderState.usedTimes === 0 ) {
  15615. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  15616. }
  15617. }
  15618. return super.delete( object );
  15619. }
  15620. getForCompute( computeNode ) {
  15621. const computeData = this.get( computeNode );
  15622. let nodeBuilderState = computeData.nodeBuilderState;
  15623. if ( nodeBuilderState === undefined ) {
  15624. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  15625. nodeBuilder.build();
  15626. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  15627. computeData.nodeBuilderState = nodeBuilderState;
  15628. }
  15629. return nodeBuilderState;
  15630. }
  15631. _createNodeBuilderState( nodeBuilder ) {
  15632. return new NodeBuilderState(
  15633. nodeBuilder.vertexShader,
  15634. nodeBuilder.fragmentShader,
  15635. nodeBuilder.computeShader,
  15636. nodeBuilder.getAttributesArray(),
  15637. nodeBuilder.getBindings(),
  15638. nodeBuilder.updateNodes,
  15639. nodeBuilder.updateBeforeNodes,
  15640. nodeBuilder.updateAfterNodes,
  15641. nodeBuilder.monitor,
  15642. nodeBuilder.transforms
  15643. );
  15644. }
  15645. getEnvironmentNode( scene ) {
  15646. return scene.environmentNode || this.get( scene ).environmentNode || null;
  15647. }
  15648. getBackgroundNode( scene ) {
  15649. return scene.backgroundNode || this.get( scene ).backgroundNode || null;
  15650. }
  15651. getFogNode( scene ) {
  15652. return scene.fogNode || this.get( scene ).fogNode || null;
  15653. }
  15654. getCacheKey( scene, lightsNode ) {
  15655. const chain = [ scene, lightsNode ];
  15656. const callId = this.renderer.info.calls;
  15657. let cacheKeyData = this.callHashCache.get( chain );
  15658. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  15659. const environmentNode = this.getEnvironmentNode( scene );
  15660. const fogNode = this.getFogNode( scene );
  15661. const values = [];
  15662. if ( lightsNode ) values.push( lightsNode.getCacheKey( true ) );
  15663. if ( environmentNode ) values.push( environmentNode.getCacheKey() );
  15664. if ( fogNode ) values.push( fogNode.getCacheKey() );
  15665. values.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  15666. cacheKeyData = {
  15667. callId,
  15668. cacheKey: hashArray( values )
  15669. };
  15670. this.callHashCache.set( chain, cacheKeyData );
  15671. }
  15672. return cacheKeyData.cacheKey;
  15673. }
  15674. updateScene( scene ) {
  15675. this.updateEnvironment( scene );
  15676. this.updateFog( scene );
  15677. this.updateBackground( scene );
  15678. }
  15679. get isToneMappingState() {
  15680. return this.renderer.getRenderTarget() ? false : true;
  15681. }
  15682. updateBackground( scene ) {
  15683. const sceneData = this.get( scene );
  15684. const background = scene.background;
  15685. if ( background ) {
  15686. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  15687. if ( sceneData.background !== background || forceUpdate ) {
  15688. let backgroundNode = null;
  15689. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  15690. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  15691. backgroundNode = pmremTexture( background );
  15692. } else {
  15693. let envMap;
  15694. if ( background.isCubeTexture === true ) {
  15695. envMap = cubeTexture( background );
  15696. } else {
  15697. envMap = texture( background );
  15698. }
  15699. backgroundNode = cubeMapNode( envMap );
  15700. }
  15701. } else if ( background.isTexture === true ) {
  15702. backgroundNode = texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  15703. } else if ( background.isColor !== true ) {
  15704. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  15705. }
  15706. sceneData.backgroundNode = backgroundNode;
  15707. sceneData.background = background;
  15708. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  15709. }
  15710. } else if ( sceneData.backgroundNode ) {
  15711. delete sceneData.backgroundNode;
  15712. delete sceneData.background;
  15713. }
  15714. }
  15715. updateFog( scene ) {
  15716. const sceneData = this.get( scene );
  15717. const fog = scene.fog;
  15718. if ( fog ) {
  15719. if ( sceneData.fog !== fog ) {
  15720. let fogNode = null;
  15721. if ( fog.isFogExp2 ) {
  15722. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  15723. const density = reference( 'density', 'float', fog ).setGroup( renderGroup );
  15724. fogNode = densityFog( color, density );
  15725. } else if ( fog.isFog ) {
  15726. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  15727. const near = reference( 'near', 'float', fog ).setGroup( renderGroup );
  15728. const far = reference( 'far', 'float', fog ).setGroup( renderGroup );
  15729. fogNode = rangeFog( color, near, far );
  15730. } else {
  15731. console.error( 'WebGPUNodes: Unsupported fog configuration.', fog );
  15732. }
  15733. sceneData.fogNode = fogNode;
  15734. sceneData.fog = fog;
  15735. }
  15736. } else {
  15737. delete sceneData.fogNode;
  15738. delete sceneData.fog;
  15739. }
  15740. }
  15741. updateEnvironment( scene ) {
  15742. const sceneData = this.get( scene );
  15743. const environment = scene.environment;
  15744. if ( environment ) {
  15745. if ( sceneData.environment !== environment ) {
  15746. let environmentNode = null;
  15747. if ( environment.isCubeTexture === true ) {
  15748. environmentNode = cubeTexture( environment );
  15749. } else if ( environment.isTexture === true ) {
  15750. environmentNode = texture( environment );
  15751. } else {
  15752. console.error( 'Nodes: Unsupported environment configuration.', environment );
  15753. }
  15754. sceneData.environmentNode = environmentNode;
  15755. sceneData.environment = environment;
  15756. }
  15757. } else if ( sceneData.environmentNode ) {
  15758. delete sceneData.environmentNode;
  15759. delete sceneData.environment;
  15760. }
  15761. }
  15762. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  15763. const nodeFrame = this.nodeFrame;
  15764. nodeFrame.renderer = renderer;
  15765. nodeFrame.scene = scene;
  15766. nodeFrame.object = object;
  15767. nodeFrame.camera = camera;
  15768. nodeFrame.material = material;
  15769. return nodeFrame;
  15770. }
  15771. getNodeFrameForRender( renderObject ) {
  15772. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  15773. }
  15774. getOutputCacheKey() {
  15775. const renderer = this.renderer;
  15776. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  15777. }
  15778. hasOutputChange( outputTarget ) {
  15779. const cacheKey = outputNodeMap.get( outputTarget );
  15780. return cacheKey !== this.getOutputCacheKey();
  15781. }
  15782. getOutputNode( outputTexture ) {
  15783. const renderer = this.renderer;
  15784. const cacheKey = this.getOutputCacheKey();
  15785. const output = texture( outputTexture, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  15786. outputNodeMap.set( outputTexture, cacheKey );
  15787. return output;
  15788. }
  15789. updateBefore( renderObject ) {
  15790. const nodeBuilder = renderObject.getNodeBuilderState();
  15791. for ( const node of nodeBuilder.updateBeforeNodes ) {
  15792. // update frame state for each node
  15793. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  15794. }
  15795. }
  15796. updateAfter( renderObject ) {
  15797. const nodeBuilder = renderObject.getNodeBuilderState();
  15798. for ( const node of nodeBuilder.updateAfterNodes ) {
  15799. // update frame state for each node
  15800. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  15801. }
  15802. }
  15803. updateForCompute( computeNode ) {
  15804. const nodeFrame = this.getNodeFrame();
  15805. const nodeBuilder = this.getForCompute( computeNode );
  15806. for ( const node of nodeBuilder.updateNodes ) {
  15807. nodeFrame.updateNode( node );
  15808. }
  15809. }
  15810. updateForRender( renderObject ) {
  15811. const nodeFrame = this.getNodeFrameForRender( renderObject );
  15812. const nodeBuilder = renderObject.getNodeBuilderState();
  15813. for ( const node of nodeBuilder.updateNodes ) {
  15814. nodeFrame.updateNode( node );
  15815. }
  15816. }
  15817. needsRefresh( renderObject ) {
  15818. const nodeFrame = this.getNodeFrameForRender( renderObject );
  15819. const monitor = renderObject.getMonitor();
  15820. return monitor.needsRefresh( renderObject, nodeFrame );
  15821. }
  15822. dispose() {
  15823. super.dispose();
  15824. this.nodeFrame = new NodeFrame();
  15825. this.nodeBuilderCache = new Map();
  15826. }
  15827. }
  15828. const _plane = /*@__PURE__*/ new Plane();
  15829. class ClippingContext {
  15830. constructor( parentContext = null ) {
  15831. this.version = 0;
  15832. this.clipIntersection = null;
  15833. this.cacheKey = '';
  15834. if ( parentContext === null ) {
  15835. this.intersectionPlanes = [];
  15836. this.unionPlanes = [];
  15837. this.viewNormalMatrix = new Matrix3();
  15838. this.clippingGroupContexts = new WeakMap();
  15839. this.shadowPass = false;
  15840. } else {
  15841. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  15842. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  15843. this.shadowPass = parentContext.shadowPass;
  15844. this.viewMatrix = parentContext.viewMatrix;
  15845. }
  15846. this.parentVersion = null;
  15847. }
  15848. projectPlanes( source, destination, offset ) {
  15849. const l = source.length;
  15850. for ( let i = 0; i < l; i ++ ) {
  15851. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  15852. const v = destination[ offset + i ];
  15853. const normal = _plane.normal;
  15854. v.x = - normal.x;
  15855. v.y = - normal.y;
  15856. v.z = - normal.z;
  15857. v.w = _plane.constant;
  15858. }
  15859. }
  15860. updateGlobal( scene, camera ) {
  15861. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowNodeMaterial );
  15862. this.viewMatrix = camera.matrixWorldInverse;
  15863. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  15864. }
  15865. update( parentContext, clippingGroup ) {
  15866. let update = false;
  15867. if ( parentContext.version !== this.parentVersion ) {
  15868. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  15869. this.unionPlanes = Array.from( parentContext.unionPlanes );
  15870. this.parentVersion = parentContext.version;
  15871. }
  15872. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  15873. this.clipIntersection = clippingGroup.clipIntersection;
  15874. if ( this.clipIntersection ) {
  15875. this.unionPlanes.length = parentContext.unionPlanes.length;
  15876. } else {
  15877. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  15878. }
  15879. }
  15880. const srcClippingPlanes = clippingGroup.clippingPlanes;
  15881. const l = srcClippingPlanes.length;
  15882. let dstClippingPlanes;
  15883. let offset;
  15884. if ( this.clipIntersection ) {
  15885. dstClippingPlanes = this.intersectionPlanes;
  15886. offset = parentContext.intersectionPlanes.length;
  15887. } else {
  15888. dstClippingPlanes = this.unionPlanes;
  15889. offset = parentContext.unionPlanes.length;
  15890. }
  15891. if ( dstClippingPlanes.length !== offset + l ) {
  15892. dstClippingPlanes.length = offset + l;
  15893. for ( let i = 0; i < l; i ++ ) {
  15894. dstClippingPlanes[ offset + i ] = new Vector4();
  15895. }
  15896. update = true;
  15897. }
  15898. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  15899. if ( update ) {
  15900. this.version ++;
  15901. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  15902. }
  15903. }
  15904. getGroupContext( clippingGroup ) {
  15905. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  15906. let context = this.clippingGroupContexts.get( clippingGroup );
  15907. if ( context === undefined ) {
  15908. context = new ClippingContext( this );
  15909. this.clippingGroupContexts.set( clippingGroup, context );
  15910. }
  15911. context.update( this, clippingGroup );
  15912. return context;
  15913. }
  15914. get unionClippingCount() {
  15915. return this.unionPlanes.length;
  15916. }
  15917. }
  15918. class RenderBundle {
  15919. constructor( scene, camera ) {
  15920. this.scene = scene;
  15921. this.camera = camera;
  15922. }
  15923. clone() {
  15924. return Object.assign( new this.constructor(), this );
  15925. }
  15926. }
  15927. class RenderBundles {
  15928. constructor() {
  15929. this.lists = new ChainMap();
  15930. }
  15931. get( scene, camera ) {
  15932. const lists = this.lists;
  15933. const keys = [ scene, camera ];
  15934. let list = lists.get( keys );
  15935. if ( list === undefined ) {
  15936. list = new RenderBundle( scene, camera );
  15937. lists.set( keys, list );
  15938. }
  15939. return list;
  15940. }
  15941. dispose() {
  15942. this.lists = new ChainMap();
  15943. }
  15944. }
  15945. class NodeLibrary {
  15946. constructor() {
  15947. this.lightNodes = new WeakMap();
  15948. this.materialNodes = new Map();
  15949. this.toneMappingNodes = new Map();
  15950. }
  15951. fromMaterial( material ) {
  15952. if ( material.isNodeMaterial ) return material;
  15953. let nodeMaterial = null;
  15954. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  15955. if ( nodeMaterialClass !== null ) {
  15956. nodeMaterial = new nodeMaterialClass();
  15957. for ( const key in material ) {
  15958. nodeMaterial[ key ] = material[ key ];
  15959. }
  15960. }
  15961. return nodeMaterial;
  15962. }
  15963. addToneMapping( toneMappingNode, toneMapping ) {
  15964. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  15965. }
  15966. getToneMappingFunction( toneMapping ) {
  15967. return this.toneMappingNodes.get( toneMapping ) || null;
  15968. }
  15969. getMaterialNodeClass( materialType ) {
  15970. return this.materialNodes.get( materialType ) || null;
  15971. }
  15972. addMaterial( materialNodeClass, materialClassType ) {
  15973. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  15974. }
  15975. getLightNodeClass( light ) {
  15976. return this.lightNodes.get( light ) || null;
  15977. }
  15978. addLight( lightNodeClass, lightClass ) {
  15979. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  15980. }
  15981. addType( nodeClass, type, library ) {
  15982. if ( library.has( type ) ) {
  15983. console.warn( `Redefinition of node ${ type }` );
  15984. return;
  15985. }
  15986. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  15987. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  15988. library.set( type, nodeClass );
  15989. }
  15990. addClass( nodeClass, baseClass, library ) {
  15991. if ( library.has( baseClass ) ) {
  15992. console.warn( `Redefinition of node ${ baseClass.name }` );
  15993. return;
  15994. }
  15995. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  15996. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  15997. library.set( baseClass, nodeClass );
  15998. }
  15999. }
  16000. const _defaultLights = /*@__PURE__*/ new LightsNode();
  16001. class Lighting extends ChainMap {
  16002. constructor() {
  16003. super();
  16004. }
  16005. createNode( lights = [] ) {
  16006. return new LightsNode().setLights( lights );
  16007. }
  16008. getNode( scene, camera ) {
  16009. // ignore post-processing
  16010. if ( scene.isQuadMesh ) return _defaultLights;
  16011. // tiled lighting
  16012. const keys = [ scene, camera ];
  16013. let node = this.get( keys );
  16014. if ( node === undefined ) {
  16015. node = this.createNode();
  16016. this.set( keys, node );
  16017. }
  16018. return node;
  16019. }
  16020. }
  16021. const _scene = /*@__PURE__*/ new Scene();
  16022. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  16023. const _screen = /*@__PURE__*/ new Vector4();
  16024. const _frustum = /*@__PURE__*/ new Frustum();
  16025. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  16026. const _vector4 = /*@__PURE__*/ new Vector4();
  16027. class Renderer {
  16028. constructor( backend, parameters = {} ) {
  16029. this.isRenderer = true;
  16030. //
  16031. const {
  16032. logarithmicDepthBuffer = false,
  16033. alpha = true,
  16034. depth = true,
  16035. stencil = false,
  16036. antialias = false,
  16037. samples = 0,
  16038. getFallback = null
  16039. } = parameters;
  16040. // public
  16041. this.domElement = backend.getDomElement();
  16042. this.backend = backend;
  16043. this.samples = samples || ( antialias === true ) ? 4 : 0;
  16044. this.autoClear = true;
  16045. this.autoClearColor = true;
  16046. this.autoClearDepth = true;
  16047. this.autoClearStencil = true;
  16048. this.alpha = alpha;
  16049. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  16050. this.outputColorSpace = SRGBColorSpace;
  16051. this.toneMapping = NoToneMapping;
  16052. this.toneMappingExposure = 1.0;
  16053. this.sortObjects = true;
  16054. this.depth = depth;
  16055. this.stencil = stencil;
  16056. this.info = new Info();
  16057. this.nodes = {
  16058. modelViewMatrix: null,
  16059. modelNormalViewMatrix: null
  16060. };
  16061. this.library = new NodeLibrary();
  16062. this.lighting = new Lighting();
  16063. // internals
  16064. this._getFallback = getFallback;
  16065. this._pixelRatio = 1;
  16066. this._width = this.domElement.width;
  16067. this._height = this.domElement.height;
  16068. this._viewport = new Vector4( 0, 0, this._width, this._height );
  16069. this._scissor = new Vector4( 0, 0, this._width, this._height );
  16070. this._scissorTest = false;
  16071. this._attributes = null;
  16072. this._geometries = null;
  16073. this._nodes = null;
  16074. this._animation = null;
  16075. this._bindings = null;
  16076. this._objects = null;
  16077. this._pipelines = null;
  16078. this._bundles = null;
  16079. this._renderLists = null;
  16080. this._renderContexts = null;
  16081. this._textures = null;
  16082. this._background = null;
  16083. this._quad = new QuadMesh( new NodeMaterial() );
  16084. this._quad.material.type = 'Renderer_output';
  16085. this._currentRenderContext = null;
  16086. this._opaqueSort = null;
  16087. this._transparentSort = null;
  16088. this._frameBufferTarget = null;
  16089. const alphaClear = this.alpha === true ? 0 : 1;
  16090. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  16091. this._clearDepth = 1;
  16092. this._clearStencil = 0;
  16093. this._renderTarget = null;
  16094. this._activeCubeFace = 0;
  16095. this._activeMipmapLevel = 0;
  16096. this._mrt = null;
  16097. this._renderObjectFunction = null;
  16098. this._currentRenderObjectFunction = null;
  16099. this._currentRenderBundle = null;
  16100. this._handleObjectFunction = this._renderObjectDirect;
  16101. this._isDeviceLost = false;
  16102. this.onDeviceLost = this._onDeviceLost;
  16103. this._initialized = false;
  16104. this._initPromise = null;
  16105. this._compilationPromises = null;
  16106. this.transparent = true;
  16107. this.opaque = true;
  16108. this.shadowMap = {
  16109. enabled: false,
  16110. type: PCFShadowMap$1
  16111. };
  16112. this.xr = {
  16113. enabled: false
  16114. };
  16115. this.debug = {
  16116. checkShaderErrors: true,
  16117. onShaderError: null,
  16118. getShaderAsync: async ( scene, camera, object ) => {
  16119. await this.compileAsync( scene, camera );
  16120. const renderList = this._renderLists.get( scene, camera );
  16121. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  16122. const material = scene.overrideMaterial || object.material;
  16123. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  16124. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  16125. return { fragmentShader, vertexShader };
  16126. }
  16127. };
  16128. }
  16129. async init() {
  16130. if ( this._initialized ) {
  16131. throw new Error( 'Renderer: Backend has already been initialized.' );
  16132. }
  16133. if ( this._initPromise !== null ) {
  16134. return this._initPromise;
  16135. }
  16136. this._initPromise = new Promise( async ( resolve, reject ) => {
  16137. let backend = this.backend;
  16138. try {
  16139. await backend.init( this );
  16140. } catch ( error ) {
  16141. if ( this._getFallback !== null ) {
  16142. // try the fallback
  16143. try {
  16144. this.backend = backend = this._getFallback( error );
  16145. await backend.init( this );
  16146. } catch ( error ) {
  16147. reject( error );
  16148. return;
  16149. }
  16150. } else {
  16151. reject( error );
  16152. return;
  16153. }
  16154. }
  16155. this._nodes = new Nodes( this, backend );
  16156. this._animation = new Animation( this._nodes, this.info );
  16157. this._attributes = new Attributes( backend );
  16158. this._background = new Background( this, this._nodes );
  16159. this._geometries = new Geometries( this._attributes, this.info );
  16160. this._textures = new Textures( this, backend, this.info );
  16161. this._pipelines = new Pipelines( backend, this._nodes );
  16162. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  16163. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  16164. this._renderLists = new RenderLists( this.lighting );
  16165. this._bundles = new RenderBundles();
  16166. this._renderContexts = new RenderContexts();
  16167. //
  16168. this._animation.start();
  16169. this._initialized = true;
  16170. resolve();
  16171. } );
  16172. return this._initPromise;
  16173. }
  16174. get coordinateSystem() {
  16175. return this.backend.coordinateSystem;
  16176. }
  16177. async compileAsync( scene, camera, targetScene = null ) {
  16178. if ( this._isDeviceLost === true ) return;
  16179. if ( this._initialized === false ) await this.init();
  16180. // preserve render tree
  16181. const nodeFrame = this._nodes.nodeFrame;
  16182. const previousRenderId = nodeFrame.renderId;
  16183. const previousRenderContext = this._currentRenderContext;
  16184. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  16185. const previousCompilationPromises = this._compilationPromises;
  16186. //
  16187. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  16188. if ( targetScene === null ) targetScene = scene;
  16189. const renderTarget = this._renderTarget;
  16190. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  16191. const activeMipmapLevel = this._activeMipmapLevel;
  16192. const compilationPromises = [];
  16193. this._currentRenderContext = renderContext;
  16194. this._currentRenderObjectFunction = this.renderObject;
  16195. this._handleObjectFunction = this._createObjectPipeline;
  16196. this._compilationPromises = compilationPromises;
  16197. nodeFrame.renderId ++;
  16198. //
  16199. nodeFrame.update();
  16200. //
  16201. renderContext.depth = this.depth;
  16202. renderContext.stencil = this.stencil;
  16203. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  16204. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  16205. //
  16206. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  16207. //
  16208. const renderList = this._renderLists.get( scene, camera );
  16209. renderList.begin();
  16210. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  16211. // include lights from target scene
  16212. if ( targetScene !== scene ) {
  16213. targetScene.traverseVisible( function ( object ) {
  16214. if ( object.isLight && object.layers.test( camera.layers ) ) {
  16215. renderList.pushLight( object );
  16216. }
  16217. } );
  16218. }
  16219. renderList.finish();
  16220. //
  16221. if ( renderTarget !== null ) {
  16222. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  16223. const renderTargetData = this._textures.get( renderTarget );
  16224. renderContext.textures = renderTargetData.textures;
  16225. renderContext.depthTexture = renderTargetData.depthTexture;
  16226. } else {
  16227. renderContext.textures = null;
  16228. renderContext.depthTexture = null;
  16229. }
  16230. //
  16231. this._nodes.updateScene( sceneRef );
  16232. //
  16233. this._background.update( sceneRef, renderList, renderContext );
  16234. // process render lists
  16235. const opaqueObjects = renderList.opaque;
  16236. const transparentObjects = renderList.transparent;
  16237. const transparentDoublePassObjects = renderList.transparentDoublePass;
  16238. const lightsNode = renderList.lightsNode;
  16239. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  16240. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  16241. // restore render tree
  16242. nodeFrame.renderId = previousRenderId;
  16243. this._currentRenderContext = previousRenderContext;
  16244. this._currentRenderObjectFunction = previousRenderObjectFunction;
  16245. this._compilationPromises = previousCompilationPromises;
  16246. this._handleObjectFunction = this._renderObjectDirect;
  16247. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  16248. await Promise.all( compilationPromises );
  16249. }
  16250. async renderAsync( scene, camera ) {
  16251. if ( this._initialized === false ) await this.init();
  16252. const renderContext = this._renderScene( scene, camera );
  16253. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  16254. }
  16255. async waitForGPU() {
  16256. await this.backend.waitForGPU();
  16257. }
  16258. setMRT( mrt ) {
  16259. this._mrt = mrt;
  16260. return this;
  16261. }
  16262. getMRT() {
  16263. return this._mrt;
  16264. }
  16265. _onDeviceLost( info ) {
  16266. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  16267. if ( info.reason ) {
  16268. errorMessage += `\nReason: ${info.reason}`;
  16269. }
  16270. console.error( errorMessage );
  16271. this._isDeviceLost = true;
  16272. }
  16273. _renderBundle( bundle, sceneRef, lightsNode ) {
  16274. const { bundleGroup, camera, renderList } = bundle;
  16275. const renderContext = this._currentRenderContext;
  16276. //
  16277. const renderBundle = this._bundles.get( bundleGroup, camera );
  16278. const renderBundleData = this.backend.get( renderBundle );
  16279. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  16280. //
  16281. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  16282. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  16283. renderBundleData.renderContexts.add( renderContext );
  16284. if ( renderBundleNeedsUpdate ) {
  16285. this.backend.beginBundle( renderContext );
  16286. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  16287. renderBundleData.renderObjects = [];
  16288. }
  16289. this._currentRenderBundle = renderBundle;
  16290. const opaqueObjects = renderList.opaque;
  16291. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  16292. this._currentRenderBundle = null;
  16293. //
  16294. this.backend.finishBundle( renderContext, renderBundle );
  16295. renderBundleData.version = bundleGroup.version;
  16296. } else {
  16297. const { renderObjects } = renderBundleData;
  16298. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  16299. const renderObject = renderObjects[ i ];
  16300. if ( this._nodes.needsRefresh( renderObject ) ) {
  16301. this._nodes.updateBefore( renderObject );
  16302. this._nodes.updateForRender( renderObject );
  16303. this._bindings.updateForRender( renderObject );
  16304. this._nodes.updateAfter( renderObject );
  16305. }
  16306. }
  16307. }
  16308. this.backend.addBundle( renderContext, renderBundle );
  16309. }
  16310. render( scene, camera ) {
  16311. if ( this._initialized === false ) {
  16312. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  16313. return this.renderAsync( scene, camera );
  16314. }
  16315. this._renderScene( scene, camera );
  16316. }
  16317. _getFrameBufferTarget() {
  16318. const { currentToneMapping, currentColorSpace } = this;
  16319. const useToneMapping = currentToneMapping !== NoToneMapping;
  16320. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  16321. if ( useToneMapping === false && useColorSpace === false ) return null;
  16322. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  16323. const { depth, stencil } = this;
  16324. let frameBufferTarget = this._frameBufferTarget;
  16325. if ( frameBufferTarget === null ) {
  16326. frameBufferTarget = new RenderTarget( width, height, {
  16327. depthBuffer: depth,
  16328. stencilBuffer: stencil,
  16329. type: HalfFloatType, // FloatType
  16330. format: RGBAFormat,
  16331. colorSpace: LinearSRGBColorSpace,
  16332. generateMipmaps: false,
  16333. minFilter: LinearFilter,
  16334. magFilter: LinearFilter,
  16335. samples: this.samples
  16336. } );
  16337. frameBufferTarget.isPostProcessingRenderTarget = true;
  16338. this._frameBufferTarget = frameBufferTarget;
  16339. }
  16340. frameBufferTarget.depthBuffer = depth;
  16341. frameBufferTarget.stencilBuffer = stencil;
  16342. frameBufferTarget.setSize( width, height );
  16343. frameBufferTarget.viewport.copy( this._viewport );
  16344. frameBufferTarget.scissor.copy( this._scissor );
  16345. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  16346. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  16347. frameBufferTarget.scissorTest = this._scissorTest;
  16348. return frameBufferTarget;
  16349. }
  16350. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  16351. if ( this._isDeviceLost === true ) return;
  16352. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  16353. // preserve render tree
  16354. const nodeFrame = this._nodes.nodeFrame;
  16355. const previousRenderId = nodeFrame.renderId;
  16356. const previousRenderContext = this._currentRenderContext;
  16357. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  16358. //
  16359. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  16360. const outputRenderTarget = this._renderTarget;
  16361. const activeCubeFace = this._activeCubeFace;
  16362. const activeMipmapLevel = this._activeMipmapLevel;
  16363. //
  16364. let renderTarget;
  16365. if ( frameBufferTarget !== null ) {
  16366. renderTarget = frameBufferTarget;
  16367. this.setRenderTarget( renderTarget );
  16368. } else {
  16369. renderTarget = outputRenderTarget;
  16370. }
  16371. //
  16372. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  16373. this._currentRenderContext = renderContext;
  16374. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  16375. //
  16376. this.info.calls ++;
  16377. this.info.render.calls ++;
  16378. this.info.render.frameCalls ++;
  16379. nodeFrame.renderId = this.info.calls;
  16380. //
  16381. const coordinateSystem = this.coordinateSystem;
  16382. if ( camera.coordinateSystem !== coordinateSystem ) {
  16383. camera.coordinateSystem = coordinateSystem;
  16384. camera.updateProjectionMatrix();
  16385. }
  16386. //
  16387. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  16388. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  16389. //
  16390. let viewport = this._viewport;
  16391. let scissor = this._scissor;
  16392. let pixelRatio = this._pixelRatio;
  16393. if ( renderTarget !== null ) {
  16394. viewport = renderTarget.viewport;
  16395. scissor = renderTarget.scissor;
  16396. pixelRatio = 1;
  16397. }
  16398. this.getDrawingBufferSize( _drawingBufferSize );
  16399. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  16400. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  16401. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  16402. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  16403. renderContext.viewportValue.width >>= activeMipmapLevel;
  16404. renderContext.viewportValue.height >>= activeMipmapLevel;
  16405. renderContext.viewportValue.minDepth = minDepth;
  16406. renderContext.viewportValue.maxDepth = maxDepth;
  16407. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  16408. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  16409. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  16410. renderContext.scissorValue.width >>= activeMipmapLevel;
  16411. renderContext.scissorValue.height >>= activeMipmapLevel;
  16412. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  16413. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  16414. //
  16415. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  16416. //
  16417. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16418. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  16419. const renderList = this._renderLists.get( scene, camera );
  16420. renderList.begin();
  16421. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  16422. renderList.finish();
  16423. if ( this.sortObjects === true ) {
  16424. renderList.sort( this._opaqueSort, this._transparentSort );
  16425. }
  16426. //
  16427. if ( renderTarget !== null ) {
  16428. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  16429. const renderTargetData = this._textures.get( renderTarget );
  16430. renderContext.textures = renderTargetData.textures;
  16431. renderContext.depthTexture = renderTargetData.depthTexture;
  16432. renderContext.width = renderTargetData.width;
  16433. renderContext.height = renderTargetData.height;
  16434. renderContext.renderTarget = renderTarget;
  16435. renderContext.depth = renderTarget.depthBuffer;
  16436. renderContext.stencil = renderTarget.stencilBuffer;
  16437. } else {
  16438. renderContext.textures = null;
  16439. renderContext.depthTexture = null;
  16440. renderContext.width = this.domElement.width;
  16441. renderContext.height = this.domElement.height;
  16442. renderContext.depth = this.depth;
  16443. renderContext.stencil = this.stencil;
  16444. }
  16445. renderContext.width >>= activeMipmapLevel;
  16446. renderContext.height >>= activeMipmapLevel;
  16447. renderContext.activeCubeFace = activeCubeFace;
  16448. renderContext.activeMipmapLevel = activeMipmapLevel;
  16449. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  16450. //
  16451. this._nodes.updateScene( sceneRef );
  16452. //
  16453. this._background.update( sceneRef, renderList, renderContext );
  16454. //
  16455. this.backend.beginRender( renderContext );
  16456. // process render lists
  16457. const {
  16458. bundles,
  16459. lightsNode,
  16460. transparentDoublePass: transparentDoublePassObjects,
  16461. transparent: transparentObjects,
  16462. opaque: opaqueObjects
  16463. } = renderList;
  16464. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  16465. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  16466. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  16467. // finish render pass
  16468. this.backend.finishRender( renderContext );
  16469. // restore render tree
  16470. nodeFrame.renderId = previousRenderId;
  16471. this._currentRenderContext = previousRenderContext;
  16472. this._currentRenderObjectFunction = previousRenderObjectFunction;
  16473. //
  16474. if ( frameBufferTarget !== null ) {
  16475. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  16476. const quad = this._quad;
  16477. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  16478. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  16479. quad.material.needsUpdate = true;
  16480. }
  16481. this._renderScene( quad, quad.camera, false );
  16482. }
  16483. //
  16484. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  16485. //
  16486. return renderContext;
  16487. }
  16488. getMaxAnisotropy() {
  16489. return this.backend.getMaxAnisotropy();
  16490. }
  16491. getActiveCubeFace() {
  16492. return this._activeCubeFace;
  16493. }
  16494. getActiveMipmapLevel() {
  16495. return this._activeMipmapLevel;
  16496. }
  16497. async setAnimationLoop( callback ) {
  16498. if ( this._initialized === false ) await this.init();
  16499. this._animation.setAnimationLoop( callback );
  16500. }
  16501. async getArrayBufferAsync( attribute ) {
  16502. return await this.backend.getArrayBufferAsync( attribute );
  16503. }
  16504. getContext() {
  16505. return this.backend.getContext();
  16506. }
  16507. getPixelRatio() {
  16508. return this._pixelRatio;
  16509. }
  16510. getDrawingBufferSize( target ) {
  16511. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  16512. }
  16513. getSize( target ) {
  16514. return target.set( this._width, this._height );
  16515. }
  16516. setPixelRatio( value = 1 ) {
  16517. if ( this._pixelRatio === value ) return;
  16518. this._pixelRatio = value;
  16519. this.setSize( this._width, this._height, false );
  16520. }
  16521. setDrawingBufferSize( width, height, pixelRatio ) {
  16522. this._width = width;
  16523. this._height = height;
  16524. this._pixelRatio = pixelRatio;
  16525. this.domElement.width = Math.floor( width * pixelRatio );
  16526. this.domElement.height = Math.floor( height * pixelRatio );
  16527. this.setViewport( 0, 0, width, height );
  16528. if ( this._initialized ) this.backend.updateSize();
  16529. }
  16530. setSize( width, height, updateStyle = true ) {
  16531. this._width = width;
  16532. this._height = height;
  16533. this.domElement.width = Math.floor( width * this._pixelRatio );
  16534. this.domElement.height = Math.floor( height * this._pixelRatio );
  16535. if ( updateStyle === true ) {
  16536. this.domElement.style.width = width + 'px';
  16537. this.domElement.style.height = height + 'px';
  16538. }
  16539. this.setViewport( 0, 0, width, height );
  16540. if ( this._initialized ) this.backend.updateSize();
  16541. }
  16542. setOpaqueSort( method ) {
  16543. this._opaqueSort = method;
  16544. }
  16545. setTransparentSort( method ) {
  16546. this._transparentSort = method;
  16547. }
  16548. getScissor( target ) {
  16549. const scissor = this._scissor;
  16550. target.x = scissor.x;
  16551. target.y = scissor.y;
  16552. target.width = scissor.width;
  16553. target.height = scissor.height;
  16554. return target;
  16555. }
  16556. setScissor( x, y, width, height ) {
  16557. const scissor = this._scissor;
  16558. if ( x.isVector4 ) {
  16559. scissor.copy( x );
  16560. } else {
  16561. scissor.set( x, y, width, height );
  16562. }
  16563. }
  16564. getScissorTest() {
  16565. return this._scissorTest;
  16566. }
  16567. setScissorTest( boolean ) {
  16568. this._scissorTest = boolean;
  16569. this.backend.setScissorTest( boolean );
  16570. }
  16571. getViewport( target ) {
  16572. return target.copy( this._viewport );
  16573. }
  16574. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  16575. const viewport = this._viewport;
  16576. if ( x.isVector4 ) {
  16577. viewport.copy( x );
  16578. } else {
  16579. viewport.set( x, y, width, height );
  16580. }
  16581. viewport.minDepth = minDepth;
  16582. viewport.maxDepth = maxDepth;
  16583. }
  16584. getClearColor( target ) {
  16585. return target.copy( this._clearColor );
  16586. }
  16587. setClearColor( color, alpha = 1 ) {
  16588. this._clearColor.set( color );
  16589. this._clearColor.a = alpha;
  16590. }
  16591. getClearAlpha() {
  16592. return this._clearColor.a;
  16593. }
  16594. setClearAlpha( alpha ) {
  16595. this._clearColor.a = alpha;
  16596. }
  16597. getClearDepth() {
  16598. return this._clearDepth;
  16599. }
  16600. setClearDepth( depth ) {
  16601. this._clearDepth = depth;
  16602. }
  16603. getClearStencil() {
  16604. return this._clearStencil;
  16605. }
  16606. setClearStencil( stencil ) {
  16607. this._clearStencil = stencil;
  16608. }
  16609. isOccluded( object ) {
  16610. const renderContext = this._currentRenderContext;
  16611. return renderContext && this.backend.isOccluded( renderContext, object );
  16612. }
  16613. clear( color = true, depth = true, stencil = true ) {
  16614. if ( this._initialized === false ) {
  16615. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  16616. return this.clearAsync( color, depth, stencil );
  16617. }
  16618. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  16619. let renderTargetData = null;
  16620. if ( renderTarget !== null ) {
  16621. this._textures.updateRenderTarget( renderTarget );
  16622. renderTargetData = this._textures.get( renderTarget );
  16623. }
  16624. this.backend.clear( color, depth, stencil, renderTargetData );
  16625. if ( renderTarget !== null && this._renderTarget === null ) {
  16626. // If a color space transform or tone mapping is required,
  16627. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  16628. const quad = this._quad;
  16629. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  16630. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  16631. quad.material.needsUpdate = true;
  16632. }
  16633. this._renderScene( quad, quad.camera, false );
  16634. }
  16635. }
  16636. clearColor() {
  16637. return this.clear( true, false, false );
  16638. }
  16639. clearDepth() {
  16640. return this.clear( false, true, false );
  16641. }
  16642. clearStencil() {
  16643. return this.clear( false, false, true );
  16644. }
  16645. async clearAsync( color = true, depth = true, stencil = true ) {
  16646. if ( this._initialized === false ) await this.init();
  16647. this.clear( color, depth, stencil );
  16648. }
  16649. clearColorAsync() {
  16650. return this.clearAsync( true, false, false );
  16651. }
  16652. clearDepthAsync() {
  16653. return this.clearAsync( false, true, false );
  16654. }
  16655. clearStencilAsync() {
  16656. return this.clearAsync( false, false, true );
  16657. }
  16658. get currentToneMapping() {
  16659. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  16660. }
  16661. get currentColorSpace() {
  16662. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  16663. }
  16664. dispose() {
  16665. this.info.dispose();
  16666. this.backend.dispose();
  16667. this._animation.dispose();
  16668. this._objects.dispose();
  16669. this._pipelines.dispose();
  16670. this._nodes.dispose();
  16671. this._bindings.dispose();
  16672. this._renderLists.dispose();
  16673. this._renderContexts.dispose();
  16674. this._textures.dispose();
  16675. this.setRenderTarget( null );
  16676. this.setAnimationLoop( null );
  16677. }
  16678. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  16679. this._renderTarget = renderTarget;
  16680. this._activeCubeFace = activeCubeFace;
  16681. this._activeMipmapLevel = activeMipmapLevel;
  16682. }
  16683. getRenderTarget() {
  16684. return this._renderTarget;
  16685. }
  16686. setRenderObjectFunction( renderObjectFunction ) {
  16687. this._renderObjectFunction = renderObjectFunction;
  16688. }
  16689. getRenderObjectFunction() {
  16690. return this._renderObjectFunction;
  16691. }
  16692. compute( computeNodes ) {
  16693. if ( this.isDeviceLost === true ) return;
  16694. if ( this._initialized === false ) {
  16695. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  16696. return this.computeAsync( computeNodes );
  16697. }
  16698. //
  16699. const nodeFrame = this._nodes.nodeFrame;
  16700. const previousRenderId = nodeFrame.renderId;
  16701. //
  16702. this.info.calls ++;
  16703. this.info.compute.calls ++;
  16704. this.info.compute.frameCalls ++;
  16705. nodeFrame.renderId = this.info.calls;
  16706. //
  16707. const backend = this.backend;
  16708. const pipelines = this._pipelines;
  16709. const bindings = this._bindings;
  16710. const nodes = this._nodes;
  16711. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  16712. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  16713. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  16714. }
  16715. backend.beginCompute( computeNodes );
  16716. for ( const computeNode of computeList ) {
  16717. // onInit
  16718. if ( pipelines.has( computeNode ) === false ) {
  16719. const dispose = () => {
  16720. computeNode.removeEventListener( 'dispose', dispose );
  16721. pipelines.delete( computeNode );
  16722. bindings.delete( computeNode );
  16723. nodes.delete( computeNode );
  16724. };
  16725. computeNode.addEventListener( 'dispose', dispose );
  16726. //
  16727. const onInitFn = computeNode.onInitFunction;
  16728. if ( onInitFn !== null ) {
  16729. onInitFn.call( computeNode, { renderer: this } );
  16730. }
  16731. }
  16732. nodes.updateForCompute( computeNode );
  16733. bindings.updateForCompute( computeNode );
  16734. const computeBindings = bindings.getForCompute( computeNode );
  16735. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  16736. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  16737. }
  16738. backend.finishCompute( computeNodes );
  16739. //
  16740. nodeFrame.renderId = previousRenderId;
  16741. }
  16742. async computeAsync( computeNodes ) {
  16743. if ( this._initialized === false ) await this.init();
  16744. this.compute( computeNodes );
  16745. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  16746. }
  16747. async hasFeatureAsync( name ) {
  16748. if ( this._initialized === false ) await this.init();
  16749. return this.backend.hasFeature( name );
  16750. }
  16751. hasFeature( name ) {
  16752. if ( this._initialized === false ) {
  16753. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  16754. return false;
  16755. }
  16756. return this.backend.hasFeature( name );
  16757. }
  16758. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  16759. if ( rectangle !== null ) {
  16760. if ( rectangle.isVector2 ) {
  16761. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  16762. } else if ( rectangle.isVector4 ) {
  16763. rectangle = _vector4.copy( rectangle ).floor();
  16764. } else {
  16765. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  16766. return;
  16767. }
  16768. } else {
  16769. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  16770. }
  16771. //
  16772. let renderContext = this._currentRenderContext;
  16773. let renderTarget;
  16774. if ( renderContext !== null ) {
  16775. renderTarget = renderContext.renderTarget;
  16776. } else {
  16777. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  16778. if ( renderTarget !== null ) {
  16779. this._textures.updateRenderTarget( renderTarget );
  16780. renderContext = this._textures.get( renderTarget );
  16781. }
  16782. }
  16783. //
  16784. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  16785. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  16786. }
  16787. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  16788. this._textures.updateTexture( srcTexture );
  16789. this._textures.updateTexture( dstTexture );
  16790. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  16791. }
  16792. readRenderTargetPixelsAsync( renderTarget, x, y, width, height, index = 0, faceIndex = 0 ) {
  16793. return this.backend.copyTextureToBuffer( renderTarget.textures[ index ], x, y, width, height, faceIndex );
  16794. }
  16795. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  16796. if ( object.visible === false ) return;
  16797. const visible = object.layers.test( camera.layers );
  16798. if ( visible ) {
  16799. if ( object.isGroup ) {
  16800. groupOrder = object.renderOrder;
  16801. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  16802. } else if ( object.isLOD ) {
  16803. if ( object.autoUpdate === true ) object.update( camera );
  16804. } else if ( object.isLight ) {
  16805. renderList.pushLight( object );
  16806. } else if ( object.isSprite ) {
  16807. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  16808. if ( this.sortObjects === true ) {
  16809. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  16810. }
  16811. const { geometry, material } = object;
  16812. if ( material.visible ) {
  16813. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  16814. }
  16815. }
  16816. } else if ( object.isLineLoop ) {
  16817. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  16818. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  16819. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  16820. const { geometry, material } = object;
  16821. if ( this.sortObjects === true ) {
  16822. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  16823. _vector4
  16824. .copy( geometry.boundingSphere.center )
  16825. .applyMatrix4( object.matrixWorld )
  16826. .applyMatrix4( _projScreenMatrix );
  16827. }
  16828. if ( Array.isArray( material ) ) {
  16829. const groups = geometry.groups;
  16830. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  16831. const group = groups[ i ];
  16832. const groupMaterial = material[ group.materialIndex ];
  16833. if ( groupMaterial && groupMaterial.visible ) {
  16834. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  16835. }
  16836. }
  16837. } else if ( material.visible ) {
  16838. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  16839. }
  16840. }
  16841. }
  16842. }
  16843. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  16844. const baseRenderList = renderList;
  16845. // replace render list
  16846. renderList = this._renderLists.get( object, camera );
  16847. renderList.begin();
  16848. baseRenderList.pushBundle( {
  16849. bundleGroup: object,
  16850. camera,
  16851. renderList,
  16852. } );
  16853. renderList.finish();
  16854. }
  16855. const children = object.children;
  16856. for ( let i = 0, l = children.length; i < l; i ++ ) {
  16857. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  16858. }
  16859. }
  16860. _renderBundles( bundles, sceneRef, lightsNode ) {
  16861. for ( const bundle of bundles ) {
  16862. this._renderBundle( bundle, sceneRef, lightsNode );
  16863. }
  16864. }
  16865. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  16866. if ( doublePassList.length > 0 ) {
  16867. // render back side
  16868. for ( const { material } of doublePassList ) {
  16869. material.side = BackSide;
  16870. }
  16871. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  16872. // render front side
  16873. for ( const { material } of doublePassList ) {
  16874. material.side = FrontSide;
  16875. }
  16876. this._renderObjects( renderList, camera, scene, lightsNode );
  16877. // restore
  16878. for ( const { material } of doublePassList ) {
  16879. material.side = DoubleSide;
  16880. }
  16881. } else {
  16882. this._renderObjects( renderList, camera, scene, lightsNode );
  16883. }
  16884. }
  16885. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  16886. // process renderable objects
  16887. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  16888. const renderItem = renderList[ i ];
  16889. // @TODO: Add support for multiple materials per object. This will require to extract
  16890. // the material from the renderItem object and pass it with its group data to renderObject().
  16891. const { object, geometry, material, group, clippingContext } = renderItem;
  16892. if ( camera.isArrayCamera ) {
  16893. const cameras = camera.cameras;
  16894. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  16895. const camera2 = cameras[ j ];
  16896. if ( object.layers.test( camera2.layers ) ) {
  16897. const vp = camera2.viewport;
  16898. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  16899. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  16900. const viewportValue = this._currentRenderContext.viewportValue;
  16901. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  16902. viewportValue.minDepth = minDepth;
  16903. viewportValue.maxDepth = maxDepth;
  16904. this.backend.updateViewport( this._currentRenderContext );
  16905. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode, clippingContext, passId );
  16906. }
  16907. }
  16908. } else {
  16909. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  16910. }
  16911. }
  16912. }
  16913. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  16914. let overridePositionNode;
  16915. let overrideFragmentNode;
  16916. let overrideDepthNode;
  16917. //
  16918. object.onBeforeRender( this, scene, camera, geometry, material, group );
  16919. //
  16920. if ( scene.overrideMaterial !== null ) {
  16921. const overrideMaterial = scene.overrideMaterial;
  16922. if ( material.positionNode && material.positionNode.isNode ) {
  16923. overridePositionNode = overrideMaterial.positionNode;
  16924. overrideMaterial.positionNode = material.positionNode;
  16925. }
  16926. if ( overrideMaterial.isShadowNodeMaterial ) {
  16927. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  16928. if ( material.depthNode && material.depthNode.isNode ) {
  16929. overrideDepthNode = overrideMaterial.depthNode;
  16930. overrideMaterial.depthNode = material.depthNode;
  16931. }
  16932. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  16933. overrideFragmentNode = overrideMaterial.fragmentNode;
  16934. overrideMaterial.fragmentNode = material.castShadowNode;
  16935. }
  16936. }
  16937. material = overrideMaterial;
  16938. }
  16939. //
  16940. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  16941. material.side = BackSide;
  16942. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  16943. material.side = FrontSide;
  16944. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  16945. material.side = DoubleSide;
  16946. } else {
  16947. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  16948. }
  16949. //
  16950. if ( overridePositionNode !== undefined ) {
  16951. scene.overrideMaterial.positionNode = overridePositionNode;
  16952. }
  16953. if ( overrideDepthNode !== undefined ) {
  16954. scene.overrideMaterial.depthNode = overrideDepthNode;
  16955. }
  16956. if ( overrideFragmentNode !== undefined ) {
  16957. scene.overrideMaterial.fragmentNode = overrideFragmentNode;
  16958. }
  16959. //
  16960. object.onAfterRender( this, scene, camera, geometry, material, group );
  16961. }
  16962. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  16963. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  16964. renderObject.drawRange = object.geometry.drawRange;
  16965. renderObject.group = group;
  16966. //
  16967. const needsRefresh = this._nodes.needsRefresh( renderObject );
  16968. if ( needsRefresh ) {
  16969. this._nodes.updateBefore( renderObject );
  16970. this._geometries.updateForRender( renderObject );
  16971. this._nodes.updateForRender( renderObject );
  16972. this._bindings.updateForRender( renderObject );
  16973. }
  16974. this._pipelines.updateForRender( renderObject );
  16975. //
  16976. if ( this._currentRenderBundle !== null ) {
  16977. const renderBundleData = this.backend.get( this._currentRenderBundle );
  16978. renderBundleData.renderObjects.push( renderObject );
  16979. renderObject.bundle = this._currentRenderBundle.scene;
  16980. }
  16981. this.backend.draw( renderObject, this.info );
  16982. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  16983. }
  16984. _createObjectPipeline( object, material, scene, camera, lightsNode, clippingContext, passId ) {
  16985. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  16986. //
  16987. this._nodes.updateBefore( renderObject );
  16988. this._geometries.updateForRender( renderObject );
  16989. this._nodes.updateForRender( renderObject );
  16990. this._bindings.updateForRender( renderObject );
  16991. this._pipelines.getForRender( renderObject, this._compilationPromises );
  16992. this._nodes.updateAfter( renderObject );
  16993. }
  16994. get compile() {
  16995. return this.compileAsync;
  16996. }
  16997. }
  16998. class Binding {
  16999. constructor( name = '' ) {
  17000. this.name = name;
  17001. this.visibility = 0;
  17002. }
  17003. setVisibility( visibility ) {
  17004. this.visibility |= visibility;
  17005. }
  17006. clone() {
  17007. return Object.assign( new this.constructor(), this );
  17008. }
  17009. }
  17010. function getFloatLength( floatLength ) {
  17011. // ensure chunk size alignment (STD140 layout)
  17012. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  17013. }
  17014. class Buffer extends Binding {
  17015. constructor( name, buffer = null ) {
  17016. super( name );
  17017. this.isBuffer = true;
  17018. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  17019. this._buffer = buffer;
  17020. }
  17021. get byteLength() {
  17022. return getFloatLength( this._buffer.byteLength );
  17023. }
  17024. get buffer() {
  17025. return this._buffer;
  17026. }
  17027. update() {
  17028. return true;
  17029. }
  17030. }
  17031. class UniformBuffer extends Buffer {
  17032. constructor( name, buffer = null ) {
  17033. super( name, buffer );
  17034. this.isUniformBuffer = true;
  17035. }
  17036. }
  17037. let _id$4 = 0;
  17038. class NodeUniformBuffer extends UniformBuffer {
  17039. constructor( nodeUniform, groupNode ) {
  17040. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  17041. this.nodeUniform = nodeUniform;
  17042. this.groupNode = groupNode;
  17043. }
  17044. get buffer() {
  17045. return this.nodeUniform.value;
  17046. }
  17047. }
  17048. class UniformsGroup extends UniformBuffer {
  17049. constructor( name ) {
  17050. super( name );
  17051. this.isUniformsGroup = true;
  17052. this._values = null;
  17053. // the order of uniforms in this array must match the order of uniforms in the shader
  17054. this.uniforms = [];
  17055. }
  17056. addUniform( uniform ) {
  17057. this.uniforms.push( uniform );
  17058. return this;
  17059. }
  17060. removeUniform( uniform ) {
  17061. const index = this.uniforms.indexOf( uniform );
  17062. if ( index !== - 1 ) {
  17063. this.uniforms.splice( index, 1 );
  17064. }
  17065. return this;
  17066. }
  17067. get values() {
  17068. if ( this._values === null ) {
  17069. this._values = Array.from( this.buffer );
  17070. }
  17071. return this._values;
  17072. }
  17073. get buffer() {
  17074. let buffer = this._buffer;
  17075. if ( buffer === null ) {
  17076. const byteLength = this.byteLength;
  17077. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  17078. this._buffer = buffer;
  17079. }
  17080. return buffer;
  17081. }
  17082. get byteLength() {
  17083. let offset = 0; // global buffer offset in bytes
  17084. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  17085. const uniform = this.uniforms[ i ];
  17086. const { boundary, itemSize } = uniform;
  17087. // offset within a single chunk in bytes
  17088. const chunkOffset = offset % GPU_CHUNK_BYTES;
  17089. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  17090. // conformance tests
  17091. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  17092. // check for chunk overflow
  17093. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  17094. } else if ( chunkOffset % boundary !== 0 ) {
  17095. // check for correct alignment
  17096. offset += ( chunkOffset % boundary );
  17097. }
  17098. uniform.offset = ( offset / this.bytesPerElement );
  17099. offset += ( itemSize * this.bytesPerElement );
  17100. }
  17101. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  17102. }
  17103. update() {
  17104. let updated = false;
  17105. for ( const uniform of this.uniforms ) {
  17106. if ( this.updateByType( uniform ) === true ) {
  17107. updated = true;
  17108. }
  17109. }
  17110. return updated;
  17111. }
  17112. updateByType( uniform ) {
  17113. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  17114. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  17115. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  17116. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  17117. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  17118. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  17119. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  17120. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  17121. }
  17122. updateNumber( uniform ) {
  17123. let updated = false;
  17124. const a = this.values;
  17125. const v = uniform.getValue();
  17126. const offset = uniform.offset;
  17127. if ( a[ offset ] !== v ) {
  17128. const b = this.buffer;
  17129. b[ offset ] = a[ offset ] = v;
  17130. updated = true;
  17131. }
  17132. return updated;
  17133. }
  17134. updateVector2( uniform ) {
  17135. let updated = false;
  17136. const a = this.values;
  17137. const v = uniform.getValue();
  17138. const offset = uniform.offset;
  17139. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  17140. const b = this.buffer;
  17141. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  17142. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  17143. updated = true;
  17144. }
  17145. return updated;
  17146. }
  17147. updateVector3( uniform ) {
  17148. let updated = false;
  17149. const a = this.values;
  17150. const v = uniform.getValue();
  17151. const offset = uniform.offset;
  17152. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  17153. const b = this.buffer;
  17154. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  17155. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  17156. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  17157. updated = true;
  17158. }
  17159. return updated;
  17160. }
  17161. updateVector4( uniform ) {
  17162. let updated = false;
  17163. const a = this.values;
  17164. const v = uniform.getValue();
  17165. const offset = uniform.offset;
  17166. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  17167. const b = this.buffer;
  17168. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  17169. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  17170. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  17171. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  17172. updated = true;
  17173. }
  17174. return updated;
  17175. }
  17176. updateColor( uniform ) {
  17177. let updated = false;
  17178. const a = this.values;
  17179. const c = uniform.getValue();
  17180. const offset = uniform.offset;
  17181. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  17182. const b = this.buffer;
  17183. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  17184. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  17185. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  17186. updated = true;
  17187. }
  17188. return updated;
  17189. }
  17190. updateMatrix3( uniform ) {
  17191. let updated = false;
  17192. const a = this.values;
  17193. const e = uniform.getValue().elements;
  17194. const offset = uniform.offset;
  17195. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  17196. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  17197. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  17198. const b = this.buffer;
  17199. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  17200. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  17201. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  17202. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  17203. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  17204. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  17205. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  17206. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  17207. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  17208. updated = true;
  17209. }
  17210. return updated;
  17211. }
  17212. updateMatrix4( uniform ) {
  17213. let updated = false;
  17214. const a = this.values;
  17215. const e = uniform.getValue().elements;
  17216. const offset = uniform.offset;
  17217. if ( arraysEqual( a, e, offset ) === false ) {
  17218. const b = this.buffer;
  17219. b.set( e, offset );
  17220. setArray( a, e, offset );
  17221. updated = true;
  17222. }
  17223. return updated;
  17224. }
  17225. }
  17226. function setArray( a, b, offset ) {
  17227. for ( let i = 0, l = b.length; i < l; i ++ ) {
  17228. a[ offset + i ] = b[ i ];
  17229. }
  17230. }
  17231. function arraysEqual( a, b, offset ) {
  17232. for ( let i = 0, l = b.length; i < l; i ++ ) {
  17233. if ( a[ offset + i ] !== b[ i ] ) return false;
  17234. }
  17235. return true;
  17236. }
  17237. let _id$3 = 0;
  17238. class NodeUniformsGroup extends UniformsGroup {
  17239. constructor( name, groupNode ) {
  17240. super( name );
  17241. this.id = _id$3 ++;
  17242. this.groupNode = groupNode;
  17243. this.isNodeUniformsGroup = true;
  17244. }
  17245. getNodes() {
  17246. const nodes = [];
  17247. for ( const uniform of this.uniforms ) {
  17248. const node = uniform.nodeUniform.node;
  17249. if ( ! node ) throw new Error( 'NodeUniformsGroup: Uniform has no node.' );
  17250. nodes.push( node );
  17251. }
  17252. return nodes;
  17253. }
  17254. }
  17255. let _id$2 = 0;
  17256. class SampledTexture extends Binding {
  17257. constructor( name, texture ) {
  17258. super( name );
  17259. this.id = _id$2 ++;
  17260. this.texture = texture;
  17261. this.version = texture ? texture.version : 0;
  17262. this.store = false;
  17263. this.generation = null;
  17264. this.isSampledTexture = true;
  17265. }
  17266. needsBindingsUpdate( generation ) {
  17267. const { texture } = this;
  17268. if ( generation !== this.generation ) {
  17269. this.generation = generation;
  17270. return true;
  17271. }
  17272. return texture.isVideoTexture;
  17273. }
  17274. update() {
  17275. const { texture, version } = this;
  17276. if ( version !== texture.version ) {
  17277. this.version = texture.version;
  17278. return true;
  17279. }
  17280. return false;
  17281. }
  17282. }
  17283. class NodeSampledTexture extends SampledTexture {
  17284. constructor( name, textureNode, groupNode, access = null ) {
  17285. super( name, textureNode ? textureNode.value : null );
  17286. this.textureNode = textureNode;
  17287. this.groupNode = groupNode;
  17288. this.access = access;
  17289. }
  17290. needsBindingsUpdate( generation ) {
  17291. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  17292. }
  17293. update() {
  17294. const { textureNode } = this;
  17295. if ( this.texture !== textureNode.value ) {
  17296. this.texture = textureNode.value;
  17297. return true;
  17298. }
  17299. return super.update();
  17300. }
  17301. }
  17302. class NodeSampledCubeTexture extends NodeSampledTexture {
  17303. constructor( name, textureNode, groupNode, access ) {
  17304. super( name, textureNode, groupNode, access );
  17305. this.isSampledCubeTexture = true;
  17306. }
  17307. }
  17308. class NodeSampledTexture3D extends NodeSampledTexture {
  17309. constructor( name, textureNode, groupNode, access ) {
  17310. super( name, textureNode, groupNode, access );
  17311. this.isSampledTexture3D = true;
  17312. }
  17313. }
  17314. const glslMethods = {
  17315. atan2: 'atan',
  17316. textureDimensions: 'textureSize',
  17317. equals: 'equal'
  17318. };
  17319. const precisionLib = {
  17320. low: 'lowp',
  17321. medium: 'mediump',
  17322. high: 'highp'
  17323. };
  17324. const supports$1 = {
  17325. swizzleAssign: true,
  17326. storageBuffer: false
  17327. };
  17328. const defaultPrecisions = `
  17329. precision highp float;
  17330. precision highp int;
  17331. precision highp sampler2D;
  17332. precision highp sampler3D;
  17333. precision highp samplerCube;
  17334. precision highp sampler2DArray;
  17335. precision highp usampler2D;
  17336. precision highp usampler3D;
  17337. precision highp usamplerCube;
  17338. precision highp usampler2DArray;
  17339. precision highp isampler2D;
  17340. precision highp isampler3D;
  17341. precision highp isamplerCube;
  17342. precision highp isampler2DArray;
  17343. precision lowp sampler2DShadow;
  17344. `;
  17345. class GLSLNodeBuilder extends NodeBuilder {
  17346. constructor( object, renderer ) {
  17347. super( object, renderer, new GLSLNodeParser() );
  17348. this.uniformGroups = {};
  17349. this.transforms = [];
  17350. this.extensions = {};
  17351. this.builtins = { vertex: [], fragment: [], compute: [] };
  17352. this.useComparisonMethod = true;
  17353. }
  17354. needsColorSpaceToLinearSRGB( texture ) {
  17355. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  17356. }
  17357. getMethod( method ) {
  17358. return glslMethods[ method ] || method;
  17359. }
  17360. getOutputStructName() {
  17361. return '';
  17362. }
  17363. buildFunctionCode( shaderNode ) {
  17364. const layout = shaderNode.layout;
  17365. const flowData = this.flowShaderNode( shaderNode );
  17366. const parameters = [];
  17367. for ( const input of layout.inputs ) {
  17368. parameters.push( this.getType( input.type ) + ' ' + input.name );
  17369. }
  17370. //
  17371. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  17372. ${ flowData.vars }
  17373. ${ flowData.code }
  17374. return ${ flowData.result };
  17375. }`;
  17376. //
  17377. return code;
  17378. }
  17379. setupPBO( storageBufferNode ) {
  17380. const attribute = storageBufferNode.value;
  17381. if ( attribute.pbo === undefined ) {
  17382. const originalArray = attribute.array;
  17383. const numElements = attribute.count * attribute.itemSize;
  17384. const { itemSize } = attribute;
  17385. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  17386. let format = isInteger ? RedIntegerFormat : RedFormat;
  17387. if ( itemSize === 2 ) {
  17388. format = isInteger ? RGIntegerFormat : RGFormat;
  17389. } else if ( itemSize === 3 ) {
  17390. format = isInteger ? RGBIntegerFormat : RGBFormat;
  17391. } else if ( itemSize === 4 ) {
  17392. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  17393. }
  17394. const typeMap = {
  17395. Float32Array: FloatType,
  17396. Uint8Array: UnsignedByteType,
  17397. Uint16Array: UnsignedShortType,
  17398. Uint32Array: UnsignedIntType,
  17399. Int8Array: ByteType,
  17400. Int16Array: ShortType,
  17401. Int32Array: IntType,
  17402. Uint8ClampedArray: UnsignedByteType,
  17403. };
  17404. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  17405. let height = Math.ceil( ( numElements / itemSize ) / width );
  17406. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  17407. const newSize = width * height * itemSize;
  17408. const newArray = new originalArray.constructor( newSize );
  17409. newArray.set( originalArray, 0 );
  17410. attribute.array = newArray;
  17411. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  17412. pboTexture.needsUpdate = true;
  17413. pboTexture.isPBOTexture = true;
  17414. const pbo = new TextureNode( pboTexture, null, null );
  17415. pbo.setPrecision( 'high' );
  17416. attribute.pboNode = pbo;
  17417. attribute.pbo = pbo.value;
  17418. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  17419. }
  17420. }
  17421. getPropertyName( node, shaderStage = this.shaderStage ) {
  17422. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  17423. return shaderStage.charAt( 0 ) + '_' + node.name;
  17424. }
  17425. return super.getPropertyName( node, shaderStage );
  17426. }
  17427. generatePBO( storageArrayElementNode ) {
  17428. const { node, indexNode } = storageArrayElementNode;
  17429. const attribute = node.value;
  17430. if ( this.renderer.backend.has( attribute ) ) {
  17431. const attributeData = this.renderer.backend.get( attribute );
  17432. attributeData.pbo = attribute.pbo;
  17433. }
  17434. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  17435. const textureName = this.getPropertyName( nodeUniform );
  17436. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  17437. const indexSnippet = indexNode.build( this, 'uint' );
  17438. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  17439. let propertyName = elementNodeData.propertyName;
  17440. if ( propertyName === undefined ) {
  17441. // property element
  17442. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  17443. propertyName = this.getPropertyName( nodeVar );
  17444. // property size
  17445. const bufferNodeData = this.getDataFromNode( node );
  17446. let propertySizeName = bufferNodeData.propertySizeName;
  17447. if ( propertySizeName === undefined ) {
  17448. propertySizeName = propertyName + 'Size';
  17449. this.getVarFromNode( node, propertySizeName, 'uint' );
  17450. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  17451. bufferNodeData.propertySizeName = propertySizeName;
  17452. }
  17453. //
  17454. const { itemSize } = attribute;
  17455. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  17456. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  17457. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  17458. //
  17459. let prefix = 'vec4';
  17460. if ( attribute.pbo.type === UnsignedIntType ) {
  17461. prefix = 'uvec4';
  17462. } else if ( attribute.pbo.type === IntType ) {
  17463. prefix = 'ivec4';
  17464. }
  17465. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  17466. elementNodeData.propertyName = propertyName;
  17467. }
  17468. return propertyName;
  17469. }
  17470. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  17471. if ( depthSnippet ) {
  17472. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  17473. } else {
  17474. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  17475. }
  17476. }
  17477. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  17478. if ( texture.isDepthTexture ) {
  17479. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  17480. } else {
  17481. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  17482. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  17483. }
  17484. }
  17485. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  17486. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  17487. }
  17488. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  17489. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  17490. }
  17491. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  17492. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  17493. }
  17494. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  17495. if ( shaderStage === 'fragment' ) {
  17496. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  17497. } else {
  17498. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  17499. }
  17500. }
  17501. getVars( shaderStage ) {
  17502. const snippets = [];
  17503. const vars = this.vars[ shaderStage ];
  17504. if ( vars !== undefined ) {
  17505. for ( const variable of vars ) {
  17506. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  17507. }
  17508. }
  17509. return snippets.join( '\n\t' );
  17510. }
  17511. getUniforms( shaderStage ) {
  17512. const uniforms = this.uniforms[ shaderStage ];
  17513. const bindingSnippets = [];
  17514. const uniformGroups = {};
  17515. for ( const uniform of uniforms ) {
  17516. let snippet = null;
  17517. let group = false;
  17518. if ( uniform.type === 'texture' ) {
  17519. const texture = uniform.node.value;
  17520. let typePrefix = '';
  17521. if ( texture.isDataTexture === true ) {
  17522. if ( texture.type === UnsignedIntType ) {
  17523. typePrefix = 'u';
  17524. } else if ( texture.type === IntType ) {
  17525. typePrefix = 'i';
  17526. }
  17527. }
  17528. if ( texture.compareFunction ) {
  17529. snippet = `sampler2DShadow ${ uniform.name };`;
  17530. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  17531. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  17532. } else {
  17533. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  17534. }
  17535. } else if ( uniform.type === 'cubeTexture' ) {
  17536. snippet = `samplerCube ${ uniform.name };`;
  17537. } else if ( uniform.type === 'texture3D' ) {
  17538. snippet = `sampler3D ${ uniform.name };`;
  17539. } else if ( uniform.type === 'buffer' ) {
  17540. const bufferNode = uniform.node;
  17541. const bufferType = this.getType( bufferNode.bufferType );
  17542. const bufferCount = bufferNode.bufferCount;
  17543. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  17544. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  17545. } else {
  17546. const vectorType = this.getVectorType( uniform.type );
  17547. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  17548. group = true;
  17549. }
  17550. const precision = uniform.node.precision;
  17551. if ( precision !== null ) {
  17552. snippet = precisionLib[ precision ] + ' ' + snippet;
  17553. }
  17554. if ( group ) {
  17555. snippet = '\t' + snippet;
  17556. const groupName = uniform.groupNode.name;
  17557. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  17558. groupSnippets.push( snippet );
  17559. } else {
  17560. snippet = 'uniform ' + snippet;
  17561. bindingSnippets.push( snippet );
  17562. }
  17563. }
  17564. let output = '';
  17565. for ( const name in uniformGroups ) {
  17566. const groupSnippets = uniformGroups[ name ];
  17567. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  17568. }
  17569. output += bindingSnippets.join( '\n' );
  17570. return output;
  17571. }
  17572. getTypeFromAttribute( attribute ) {
  17573. let nodeType = super.getTypeFromAttribute( attribute );
  17574. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  17575. let dataAttribute = attribute;
  17576. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  17577. const array = dataAttribute.array;
  17578. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  17579. nodeType = nodeType.slice( 1 );
  17580. }
  17581. }
  17582. return nodeType;
  17583. }
  17584. getAttributes( shaderStage ) {
  17585. let snippet = '';
  17586. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  17587. const attributes = this.getAttributesArray();
  17588. let location = 0;
  17589. for ( const attribute of attributes ) {
  17590. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  17591. }
  17592. }
  17593. return snippet;
  17594. }
  17595. getStructMembers( struct ) {
  17596. const snippets = [];
  17597. const members = struct.getMemberTypes();
  17598. for ( let i = 0; i < members.length; i ++ ) {
  17599. const member = members[ i ];
  17600. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  17601. }
  17602. return snippets.join( '\n' );
  17603. }
  17604. getStructs( shaderStage ) {
  17605. const snippets = [];
  17606. const structs = this.structs[ shaderStage ];
  17607. if ( structs.length === 0 ) {
  17608. return 'layout( location = 0 ) out vec4 fragColor;\n';
  17609. }
  17610. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  17611. const struct = structs[ index ];
  17612. let snippet = '\n';
  17613. snippet += this.getStructMembers( struct );
  17614. snippet += '\n';
  17615. snippets.push( snippet );
  17616. }
  17617. return snippets.join( '\n\n' );
  17618. }
  17619. getVaryings( shaderStage ) {
  17620. let snippet = '';
  17621. const varyings = this.varyings;
  17622. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  17623. for ( const varying of varyings ) {
  17624. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  17625. const type = varying.type;
  17626. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  17627. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  17628. }
  17629. } else if ( shaderStage === 'fragment' ) {
  17630. for ( const varying of varyings ) {
  17631. if ( varying.needsInterpolation ) {
  17632. const type = varying.type;
  17633. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  17634. snippet += `${flat}in ${type} ${varying.name};\n`;
  17635. }
  17636. }
  17637. }
  17638. for ( const builtin of this.builtins[ shaderStage ] ) {
  17639. snippet += `${builtin};\n`;
  17640. }
  17641. return snippet;
  17642. }
  17643. getVertexIndex() {
  17644. return 'uint( gl_VertexID )';
  17645. }
  17646. getInstanceIndex() {
  17647. return 'uint( gl_InstanceID )';
  17648. }
  17649. getInvocationLocalIndex() {
  17650. const workgroupSize = this.object.workgroupSize;
  17651. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  17652. return `uint( gl_InstanceID ) % ${size}u`;
  17653. }
  17654. getDrawIndex() {
  17655. const extensions = this.renderer.backend.extensions;
  17656. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  17657. return 'uint( gl_DrawID )';
  17658. }
  17659. return null;
  17660. }
  17661. getFrontFacing() {
  17662. return 'gl_FrontFacing';
  17663. }
  17664. getFragCoord() {
  17665. return 'gl_FragCoord.xy';
  17666. }
  17667. getFragDepth() {
  17668. return 'gl_FragDepth';
  17669. }
  17670. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  17671. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  17672. if ( map.has( name ) === false ) {
  17673. map.set( name, {
  17674. name,
  17675. behavior
  17676. } );
  17677. }
  17678. }
  17679. getExtensions( shaderStage ) {
  17680. const snippets = [];
  17681. if ( shaderStage === 'vertex' ) {
  17682. const ext = this.renderer.backend.extensions;
  17683. const isBatchedMesh = this.object.isBatchedMesh;
  17684. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  17685. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  17686. }
  17687. }
  17688. const extensions = this.extensions[ shaderStage ];
  17689. if ( extensions !== undefined ) {
  17690. for ( const { name, behavior } of extensions.values() ) {
  17691. snippets.push( `#extension ${name} : ${behavior}` );
  17692. }
  17693. }
  17694. return snippets.join( '\n' );
  17695. }
  17696. getClipDistance() {
  17697. return 'gl_ClipDistance';
  17698. }
  17699. isAvailable( name ) {
  17700. let result = supports$1[ name ];
  17701. if ( result === undefined ) {
  17702. let extensionName;
  17703. result = false;
  17704. switch ( name ) {
  17705. case 'float32Filterable':
  17706. extensionName = 'OES_texture_float_linear';
  17707. break;
  17708. case 'clipDistance':
  17709. extensionName = 'WEBGL_clip_cull_distance';
  17710. break;
  17711. }
  17712. if ( extensionName !== undefined ) {
  17713. const extensions = this.renderer.backend.extensions;
  17714. if ( extensions.has( extensionName ) ) {
  17715. extensions.get( extensionName );
  17716. result = true;
  17717. }
  17718. }
  17719. supports$1[ name ] = result;
  17720. }
  17721. return result;
  17722. }
  17723. isFlipY() {
  17724. return true;
  17725. }
  17726. enableHardwareClipping( planeCount ) {
  17727. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  17728. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  17729. }
  17730. registerTransform( varyingName, attributeNode ) {
  17731. this.transforms.push( { varyingName, attributeNode } );
  17732. }
  17733. getTransforms( /* shaderStage */ ) {
  17734. const transforms = this.transforms;
  17735. let snippet = '';
  17736. for ( let i = 0; i < transforms.length; i ++ ) {
  17737. const transform = transforms[ i ];
  17738. const attributeName = this.getPropertyName( transform.attributeNode );
  17739. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  17740. }
  17741. return snippet;
  17742. }
  17743. _getGLSLUniformStruct( name, vars ) {
  17744. return `
  17745. layout( std140 ) uniform ${name} {
  17746. ${vars}
  17747. };`;
  17748. }
  17749. _getGLSLVertexCode( shaderData ) {
  17750. return `#version 300 es
  17751. ${ this.getSignature() }
  17752. // extensions
  17753. ${shaderData.extensions}
  17754. // precision
  17755. ${ defaultPrecisions }
  17756. // uniforms
  17757. ${shaderData.uniforms}
  17758. // varyings
  17759. ${shaderData.varyings}
  17760. // attributes
  17761. ${shaderData.attributes}
  17762. // codes
  17763. ${shaderData.codes}
  17764. void main() {
  17765. // vars
  17766. ${shaderData.vars}
  17767. // transforms
  17768. ${shaderData.transforms}
  17769. // flow
  17770. ${shaderData.flow}
  17771. gl_PointSize = 1.0;
  17772. }
  17773. `;
  17774. }
  17775. _getGLSLFragmentCode( shaderData ) {
  17776. return `#version 300 es
  17777. ${ this.getSignature() }
  17778. // precision
  17779. ${ defaultPrecisions }
  17780. // uniforms
  17781. ${shaderData.uniforms}
  17782. // varyings
  17783. ${shaderData.varyings}
  17784. // codes
  17785. ${shaderData.codes}
  17786. ${shaderData.structs}
  17787. void main() {
  17788. // vars
  17789. ${shaderData.vars}
  17790. // flow
  17791. ${shaderData.flow}
  17792. }
  17793. `;
  17794. }
  17795. buildCode() {
  17796. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  17797. this.sortBindingGroups();
  17798. for ( const shaderStage in shadersData ) {
  17799. let flow = '// code\n\n';
  17800. flow += this.flowCode[ shaderStage ];
  17801. const flowNodes = this.flowNodes[ shaderStage ];
  17802. const mainNode = flowNodes[ flowNodes.length - 1 ];
  17803. for ( const node of flowNodes ) {
  17804. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  17805. const slotName = node.name;
  17806. if ( slotName ) {
  17807. if ( flow.length > 0 ) flow += '\n';
  17808. flow += `\t// flow -> ${ slotName }\n\t`;
  17809. }
  17810. flow += `${ flowSlotData.code }\n\t`;
  17811. if ( node === mainNode && shaderStage !== 'compute' ) {
  17812. flow += '// result\n\t';
  17813. if ( shaderStage === 'vertex' ) {
  17814. flow += 'gl_Position = ';
  17815. flow += `${ flowSlotData.result };`;
  17816. } else if ( shaderStage === 'fragment' ) {
  17817. if ( ! node.outputNode.isOutputStructNode ) {
  17818. flow += 'fragColor = ';
  17819. flow += `${ flowSlotData.result };`;
  17820. }
  17821. }
  17822. }
  17823. }
  17824. const stageData = shadersData[ shaderStage ];
  17825. stageData.extensions = this.getExtensions( shaderStage );
  17826. stageData.uniforms = this.getUniforms( shaderStage );
  17827. stageData.attributes = this.getAttributes( shaderStage );
  17828. stageData.varyings = this.getVaryings( shaderStage );
  17829. stageData.vars = this.getVars( shaderStage );
  17830. stageData.structs = this.getStructs( shaderStage );
  17831. stageData.codes = this.getCodes( shaderStage );
  17832. stageData.transforms = this.getTransforms( shaderStage );
  17833. stageData.flow = flow;
  17834. }
  17835. if ( this.material !== null ) {
  17836. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  17837. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  17838. } else {
  17839. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  17840. }
  17841. }
  17842. getUniformFromNode( node, type, shaderStage, name = null ) {
  17843. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  17844. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  17845. let uniformGPU = nodeData.uniformGPU;
  17846. if ( uniformGPU === undefined ) {
  17847. const group = node.groupNode;
  17848. const groupName = group.name;
  17849. const bindings = this.getBindGroupArray( groupName, shaderStage );
  17850. if ( type === 'texture' ) {
  17851. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  17852. bindings.push( uniformGPU );
  17853. } else if ( type === 'cubeTexture' ) {
  17854. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  17855. bindings.push( uniformGPU );
  17856. } else if ( type === 'texture3D' ) {
  17857. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  17858. bindings.push( uniformGPU );
  17859. } else if ( type === 'buffer' ) {
  17860. node.name = `NodeBuffer_${ node.id }`;
  17861. uniformNode.name = `buffer${ node.id }`;
  17862. const buffer = new NodeUniformBuffer( node, group );
  17863. buffer.name = node.name;
  17864. bindings.push( buffer );
  17865. uniformGPU = buffer;
  17866. } else {
  17867. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  17868. let uniformsGroup = uniformsStage[ groupName ];
  17869. if ( uniformsGroup === undefined ) {
  17870. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  17871. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  17872. uniformsStage[ groupName ] = uniformsGroup;
  17873. bindings.push( uniformsGroup );
  17874. }
  17875. uniformGPU = this.getNodeUniform( uniformNode, type );
  17876. uniformsGroup.addUniform( uniformGPU );
  17877. }
  17878. nodeData.uniformGPU = uniformGPU;
  17879. }
  17880. return uniformNode;
  17881. }
  17882. }
  17883. let vector2 = null;
  17884. let vector4 = null;
  17885. let color4 = null;
  17886. class Backend {
  17887. constructor( parameters = {} ) {
  17888. this.parameters = Object.assign( {}, parameters );
  17889. this.data = new WeakMap();
  17890. this.renderer = null;
  17891. this.domElement = null;
  17892. }
  17893. async init( renderer ) {
  17894. this.renderer = renderer;
  17895. }
  17896. // render context
  17897. begin( /*renderContext*/ ) { }
  17898. finish( /*renderContext*/ ) { }
  17899. // render object
  17900. draw( /*renderObject, info*/ ) { }
  17901. // program
  17902. createProgram( /*program*/ ) { }
  17903. destroyProgram( /*program*/ ) { }
  17904. // bindings
  17905. createBindings( /*bingGroup, bindings*/ ) { }
  17906. updateBindings( /*bingGroup, bindings*/ ) { }
  17907. // pipeline
  17908. createRenderPipeline( /*renderObject*/ ) { }
  17909. createComputePipeline( /*computeNode, pipeline*/ ) { }
  17910. destroyPipeline( /*pipeline*/ ) { }
  17911. // cache key
  17912. needsRenderUpdate( /*renderObject*/ ) { } // return Boolean ( fast test )
  17913. getRenderCacheKey( /*renderObject*/ ) { } // return String
  17914. // node builder
  17915. createNodeBuilder( /*renderObject*/ ) { } // return NodeBuilder (ADD IT)
  17916. // textures
  17917. createSampler( /*texture*/ ) { }
  17918. createDefaultTexture( /*texture*/ ) { }
  17919. createTexture( /*texture*/ ) { }
  17920. copyTextureToBuffer( /*texture, x, y, width, height*/ ) {}
  17921. // attributes
  17922. createAttribute( /*attribute*/ ) { }
  17923. createIndexAttribute( /*attribute*/ ) { }
  17924. updateAttribute( /*attribute*/ ) { }
  17925. destroyAttribute( /*attribute*/ ) { }
  17926. // canvas
  17927. getContext() { }
  17928. updateSize() { }
  17929. // utils
  17930. resolveTimestampAsync( /*renderContext, type*/ ) { }
  17931. hasFeatureAsync( /*name*/ ) { } // return Boolean
  17932. hasFeature( /*name*/ ) { } // return Boolean
  17933. getInstanceCount( renderObject ) {
  17934. const { object, geometry } = renderObject;
  17935. return geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  17936. }
  17937. getDrawingBufferSize() {
  17938. vector2 = vector2 || new Vector2();
  17939. return this.renderer.getDrawingBufferSize( vector2 );
  17940. }
  17941. getScissor() {
  17942. vector4 = vector4 || new Vector4();
  17943. return this.renderer.getScissor( vector4 );
  17944. }
  17945. setScissorTest( /*boolean*/ ) { }
  17946. getClearColor() {
  17947. const renderer = this.renderer;
  17948. color4 = color4 || new Color4();
  17949. renderer.getClearColor( color4 );
  17950. color4.getRGB( color4, this.renderer.currentColorSpace );
  17951. return color4;
  17952. }
  17953. getDomElement() {
  17954. let domElement = this.domElement;
  17955. if ( domElement === null ) {
  17956. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  17957. // OffscreenCanvas does not have setAttribute, see #22811
  17958. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  17959. this.domElement = domElement;
  17960. }
  17961. return domElement;
  17962. }
  17963. // resource properties
  17964. set( object, value ) {
  17965. this.data.set( object, value );
  17966. }
  17967. get( object ) {
  17968. let map = this.data.get( object );
  17969. if ( map === undefined ) {
  17970. map = {};
  17971. this.data.set( object, map );
  17972. }
  17973. return map;
  17974. }
  17975. has( object ) {
  17976. return this.data.has( object );
  17977. }
  17978. delete( object ) {
  17979. this.data.delete( object );
  17980. }
  17981. dispose() { }
  17982. }
  17983. let _id$1 = 0;
  17984. class DualAttributeData {
  17985. constructor( attributeData, dualBuffer ) {
  17986. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  17987. this.type = attributeData.type;
  17988. this.bufferType = attributeData.bufferType;
  17989. this.pbo = attributeData.pbo;
  17990. this.byteLength = attributeData.byteLength;
  17991. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  17992. this.version = attributeData.version;
  17993. this.isInteger = attributeData.isInteger;
  17994. this.activeBufferIndex = 0;
  17995. this.baseId = attributeData.id;
  17996. }
  17997. get id() {
  17998. return `${ this.baseId }|${ this.activeBufferIndex }`;
  17999. }
  18000. get bufferGPU() {
  18001. return this.buffers[ this.activeBufferIndex ];
  18002. }
  18003. get transformBuffer() {
  18004. return this.buffers[ this.activeBufferIndex ^ 1 ];
  18005. }
  18006. switchBuffers() {
  18007. this.activeBufferIndex ^= 1;
  18008. }
  18009. }
  18010. class WebGLAttributeUtils {
  18011. constructor( backend ) {
  18012. this.backend = backend;
  18013. }
  18014. createAttribute( attribute, bufferType ) {
  18015. const backend = this.backend;
  18016. const { gl } = backend;
  18017. const array = attribute.array;
  18018. const usage = attribute.usage || gl.STATIC_DRAW;
  18019. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  18020. const bufferData = backend.get( bufferAttribute );
  18021. let bufferGPU = bufferData.bufferGPU;
  18022. if ( bufferGPU === undefined ) {
  18023. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  18024. bufferData.bufferGPU = bufferGPU;
  18025. bufferData.bufferType = bufferType;
  18026. bufferData.version = bufferAttribute.version;
  18027. }
  18028. //attribute.onUploadCallback();
  18029. let type;
  18030. if ( array instanceof Float32Array ) {
  18031. type = gl.FLOAT;
  18032. } else if ( array instanceof Uint16Array ) {
  18033. if ( attribute.isFloat16BufferAttribute ) {
  18034. type = gl.HALF_FLOAT;
  18035. } else {
  18036. type = gl.UNSIGNED_SHORT;
  18037. }
  18038. } else if ( array instanceof Int16Array ) {
  18039. type = gl.SHORT;
  18040. } else if ( array instanceof Uint32Array ) {
  18041. type = gl.UNSIGNED_INT;
  18042. } else if ( array instanceof Int32Array ) {
  18043. type = gl.INT;
  18044. } else if ( array instanceof Int8Array ) {
  18045. type = gl.BYTE;
  18046. } else if ( array instanceof Uint8Array ) {
  18047. type = gl.UNSIGNED_BYTE;
  18048. } else if ( array instanceof Uint8ClampedArray ) {
  18049. type = gl.UNSIGNED_BYTE;
  18050. } else {
  18051. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  18052. }
  18053. let attributeData = {
  18054. bufferGPU,
  18055. bufferType,
  18056. type,
  18057. byteLength: array.byteLength,
  18058. bytesPerElement: array.BYTES_PER_ELEMENT,
  18059. version: attribute.version,
  18060. pbo: attribute.pbo,
  18061. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  18062. id: _id$1 ++
  18063. };
  18064. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  18065. // create buffer for tranform feedback use
  18066. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  18067. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  18068. }
  18069. backend.set( attribute, attributeData );
  18070. }
  18071. updateAttribute( attribute ) {
  18072. const backend = this.backend;
  18073. const { gl } = backend;
  18074. const array = attribute.array;
  18075. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  18076. const bufferData = backend.get( bufferAttribute );
  18077. const bufferType = bufferData.bufferType;
  18078. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  18079. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  18080. if ( updateRanges.length === 0 ) {
  18081. // Not using update ranges
  18082. gl.bufferSubData( bufferType, 0, array );
  18083. } else {
  18084. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  18085. const range = updateRanges[ i ];
  18086. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  18087. array, range.start, range.count );
  18088. }
  18089. bufferAttribute.clearUpdateRanges();
  18090. }
  18091. gl.bindBuffer( bufferType, null );
  18092. bufferData.version = bufferAttribute.version;
  18093. }
  18094. destroyAttribute( attribute ) {
  18095. const backend = this.backend;
  18096. const { gl } = backend;
  18097. if ( attribute.isInterleavedBufferAttribute ) {
  18098. backend.delete( attribute.data );
  18099. }
  18100. const attributeData = backend.get( attribute );
  18101. gl.deleteBuffer( attributeData.bufferGPU );
  18102. backend.delete( attribute );
  18103. }
  18104. async getArrayBufferAsync( attribute ) {
  18105. const backend = this.backend;
  18106. const { gl } = backend;
  18107. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  18108. const { bufferGPU } = backend.get( bufferAttribute );
  18109. const array = attribute.array;
  18110. const byteLength = array.byteLength;
  18111. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  18112. const writeBuffer = gl.createBuffer();
  18113. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  18114. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  18115. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  18116. await backend.utils._clientWaitAsync();
  18117. const dstBuffer = new attribute.array.constructor( array.length );
  18118. // Ensure the buffer is bound before reading
  18119. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  18120. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  18121. gl.deleteBuffer( writeBuffer );
  18122. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  18123. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  18124. return dstBuffer.buffer;
  18125. }
  18126. _createBuffer( gl, bufferType, array, usage ) {
  18127. const bufferGPU = gl.createBuffer();
  18128. gl.bindBuffer( bufferType, bufferGPU );
  18129. gl.bufferData( bufferType, array, usage );
  18130. gl.bindBuffer( bufferType, null );
  18131. return bufferGPU;
  18132. }
  18133. }
  18134. let initialized$1 = false, equationToGL, factorToGL;
  18135. class WebGLState {
  18136. constructor( backend ) {
  18137. this.backend = backend;
  18138. this.gl = this.backend.gl;
  18139. this.enabled = {};
  18140. this.currentFlipSided = null;
  18141. this.currentCullFace = null;
  18142. this.currentProgram = null;
  18143. this.currentBlendingEnabled = false;
  18144. this.currentBlending = null;
  18145. this.currentBlendSrc = null;
  18146. this.currentBlendDst = null;
  18147. this.currentBlendSrcAlpha = null;
  18148. this.currentBlendDstAlpha = null;
  18149. this.currentPremultipledAlpha = null;
  18150. this.currentPolygonOffsetFactor = null;
  18151. this.currentPolygonOffsetUnits = null;
  18152. this.currentColorMask = null;
  18153. this.currentDepthFunc = null;
  18154. this.currentDepthMask = null;
  18155. this.currentStencilFunc = null;
  18156. this.currentStencilRef = null;
  18157. this.currentStencilFuncMask = null;
  18158. this.currentStencilFail = null;
  18159. this.currentStencilZFail = null;
  18160. this.currentStencilZPass = null;
  18161. this.currentStencilMask = null;
  18162. this.currentLineWidth = null;
  18163. this.currentClippingPlanes = 0;
  18164. this.currentBoundFramebuffers = {};
  18165. this.currentDrawbuffers = new WeakMap();
  18166. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  18167. this.currentTextureSlot = null;
  18168. this.currentBoundTextures = {};
  18169. this.currentBoundBufferBases = {};
  18170. if ( initialized$1 === false ) {
  18171. this._init( this.gl );
  18172. initialized$1 = true;
  18173. }
  18174. }
  18175. _init( gl ) {
  18176. // Store only WebGL constants here.
  18177. equationToGL = {
  18178. [ AddEquation ]: gl.FUNC_ADD,
  18179. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  18180. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  18181. };
  18182. factorToGL = {
  18183. [ ZeroFactor ]: gl.ZERO,
  18184. [ OneFactor ]: gl.ONE,
  18185. [ SrcColorFactor ]: gl.SRC_COLOR,
  18186. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  18187. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  18188. [ DstColorFactor ]: gl.DST_COLOR,
  18189. [ DstAlphaFactor ]: gl.DST_ALPHA,
  18190. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  18191. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  18192. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  18193. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  18194. };
  18195. }
  18196. enable( id ) {
  18197. const { enabled } = this;
  18198. if ( enabled[ id ] !== true ) {
  18199. this.gl.enable( id );
  18200. enabled[ id ] = true;
  18201. }
  18202. }
  18203. disable( id ) {
  18204. const { enabled } = this;
  18205. if ( enabled[ id ] !== false ) {
  18206. this.gl.disable( id );
  18207. enabled[ id ] = false;
  18208. }
  18209. }
  18210. setFlipSided( flipSided ) {
  18211. if ( this.currentFlipSided !== flipSided ) {
  18212. const { gl } = this;
  18213. if ( flipSided ) {
  18214. gl.frontFace( gl.CW );
  18215. } else {
  18216. gl.frontFace( gl.CCW );
  18217. }
  18218. this.currentFlipSided = flipSided;
  18219. }
  18220. }
  18221. setCullFace( cullFace ) {
  18222. const { gl } = this;
  18223. if ( cullFace !== CullFaceNone ) {
  18224. this.enable( gl.CULL_FACE );
  18225. if ( cullFace !== this.currentCullFace ) {
  18226. if ( cullFace === CullFaceBack ) {
  18227. gl.cullFace( gl.BACK );
  18228. } else if ( cullFace === CullFaceFront ) {
  18229. gl.cullFace( gl.FRONT );
  18230. } else {
  18231. gl.cullFace( gl.FRONT_AND_BACK );
  18232. }
  18233. }
  18234. } else {
  18235. this.disable( gl.CULL_FACE );
  18236. }
  18237. this.currentCullFace = cullFace;
  18238. }
  18239. setLineWidth( width ) {
  18240. const { currentLineWidth, gl } = this;
  18241. if ( width !== currentLineWidth ) {
  18242. gl.lineWidth( width );
  18243. this.currentLineWidth = width;
  18244. }
  18245. }
  18246. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  18247. const { gl } = this;
  18248. if ( blending === NoBlending ) {
  18249. if ( this.currentBlendingEnabled === true ) {
  18250. this.disable( gl.BLEND );
  18251. this.currentBlendingEnabled = false;
  18252. }
  18253. return;
  18254. }
  18255. if ( this.currentBlendingEnabled === false ) {
  18256. this.enable( gl.BLEND );
  18257. this.currentBlendingEnabled = true;
  18258. }
  18259. if ( blending !== CustomBlending ) {
  18260. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  18261. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  18262. gl.blendEquation( gl.FUNC_ADD );
  18263. this.currentBlendEquation = AddEquation;
  18264. this.currentBlendEquationAlpha = AddEquation;
  18265. }
  18266. if ( premultipliedAlpha ) {
  18267. switch ( blending ) {
  18268. case NormalBlending:
  18269. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  18270. break;
  18271. case AdditiveBlending:
  18272. gl.blendFunc( gl.ONE, gl.ONE );
  18273. break;
  18274. case SubtractiveBlending:
  18275. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  18276. break;
  18277. case MultiplyBlending:
  18278. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  18279. break;
  18280. default:
  18281. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  18282. break;
  18283. }
  18284. } else {
  18285. switch ( blending ) {
  18286. case NormalBlending:
  18287. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  18288. break;
  18289. case AdditiveBlending:
  18290. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  18291. break;
  18292. case SubtractiveBlending:
  18293. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  18294. break;
  18295. case MultiplyBlending:
  18296. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  18297. break;
  18298. default:
  18299. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  18300. break;
  18301. }
  18302. }
  18303. this.currentBlendSrc = null;
  18304. this.currentBlendDst = null;
  18305. this.currentBlendSrcAlpha = null;
  18306. this.currentBlendDstAlpha = null;
  18307. this.currentBlending = blending;
  18308. this.currentPremultipledAlpha = premultipliedAlpha;
  18309. }
  18310. return;
  18311. }
  18312. // custom blending
  18313. blendEquationAlpha = blendEquationAlpha || blendEquation;
  18314. blendSrcAlpha = blendSrcAlpha || blendSrc;
  18315. blendDstAlpha = blendDstAlpha || blendDst;
  18316. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  18317. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  18318. this.currentBlendEquation = blendEquation;
  18319. this.currentBlendEquationAlpha = blendEquationAlpha;
  18320. }
  18321. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  18322. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  18323. this.currentBlendSrc = blendSrc;
  18324. this.currentBlendDst = blendDst;
  18325. this.currentBlendSrcAlpha = blendSrcAlpha;
  18326. this.currentBlendDstAlpha = blendDstAlpha;
  18327. }
  18328. this.currentBlending = blending;
  18329. this.currentPremultipledAlpha = false;
  18330. }
  18331. setColorMask( colorMask ) {
  18332. if ( this.currentColorMask !== colorMask ) {
  18333. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  18334. this.currentColorMask = colorMask;
  18335. }
  18336. }
  18337. setDepthTest( depthTest ) {
  18338. const { gl } = this;
  18339. if ( depthTest ) {
  18340. this.enable( gl.DEPTH_TEST );
  18341. } else {
  18342. this.disable( gl.DEPTH_TEST );
  18343. }
  18344. }
  18345. setDepthMask( depthMask ) {
  18346. if ( this.currentDepthMask !== depthMask ) {
  18347. this.gl.depthMask( depthMask );
  18348. this.currentDepthMask = depthMask;
  18349. }
  18350. }
  18351. setDepthFunc( depthFunc ) {
  18352. if ( this.currentDepthFunc !== depthFunc ) {
  18353. const { gl } = this;
  18354. switch ( depthFunc ) {
  18355. case NeverDepth:
  18356. gl.depthFunc( gl.NEVER );
  18357. break;
  18358. case AlwaysDepth:
  18359. gl.depthFunc( gl.ALWAYS );
  18360. break;
  18361. case LessDepth:
  18362. gl.depthFunc( gl.LESS );
  18363. break;
  18364. case LessEqualDepth:
  18365. gl.depthFunc( gl.LEQUAL );
  18366. break;
  18367. case EqualDepth:
  18368. gl.depthFunc( gl.EQUAL );
  18369. break;
  18370. case GreaterEqualDepth:
  18371. gl.depthFunc( gl.GEQUAL );
  18372. break;
  18373. case GreaterDepth:
  18374. gl.depthFunc( gl.GREATER );
  18375. break;
  18376. case NotEqualDepth:
  18377. gl.depthFunc( gl.NOTEQUAL );
  18378. break;
  18379. default:
  18380. gl.depthFunc( gl.LEQUAL );
  18381. }
  18382. this.currentDepthFunc = depthFunc;
  18383. }
  18384. }
  18385. setStencilTest( stencilTest ) {
  18386. const { gl } = this;
  18387. if ( stencilTest ) {
  18388. this.enable( gl.STENCIL_TEST );
  18389. } else {
  18390. this.disable( gl.STENCIL_TEST );
  18391. }
  18392. }
  18393. setStencilMask( stencilMask ) {
  18394. if ( this.currentStencilMask !== stencilMask ) {
  18395. this.gl.stencilMask( stencilMask );
  18396. this.currentStencilMask = stencilMask;
  18397. }
  18398. }
  18399. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  18400. if ( this.currentStencilFunc !== stencilFunc ||
  18401. this.currentStencilRef !== stencilRef ||
  18402. this.currentStencilFuncMask !== stencilMask ) {
  18403. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  18404. this.currentStencilFunc = stencilFunc;
  18405. this.currentStencilRef = stencilRef;
  18406. this.currentStencilFuncMask = stencilMask;
  18407. }
  18408. }
  18409. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  18410. if ( this.currentStencilFail !== stencilFail ||
  18411. this.currentStencilZFail !== stencilZFail ||
  18412. this.currentStencilZPass !== stencilZPass ) {
  18413. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  18414. this.currentStencilFail = stencilFail;
  18415. this.currentStencilZFail = stencilZFail;
  18416. this.currentStencilZPass = stencilZPass;
  18417. }
  18418. }
  18419. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  18420. const { gl } = this;
  18421. material.side === DoubleSide
  18422. ? this.disable( gl.CULL_FACE )
  18423. : this.enable( gl.CULL_FACE );
  18424. let flipSided = ( material.side === BackSide );
  18425. if ( frontFaceCW ) flipSided = ! flipSided;
  18426. this.setFlipSided( flipSided );
  18427. ( material.blending === NormalBlending && material.transparent === false )
  18428. ? this.setBlending( NoBlending )
  18429. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  18430. this.setDepthFunc( material.depthFunc );
  18431. this.setDepthTest( material.depthTest );
  18432. this.setDepthMask( material.depthWrite );
  18433. this.setColorMask( material.colorWrite );
  18434. const stencilWrite = material.stencilWrite;
  18435. this.setStencilTest( stencilWrite );
  18436. if ( stencilWrite ) {
  18437. this.setStencilMask( material.stencilWriteMask );
  18438. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  18439. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  18440. }
  18441. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  18442. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  18443. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  18444. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  18445. if ( hardwareClippingPlanes > 0 ) {
  18446. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  18447. const CLIP_DISTANCE0_WEBGL = 0x3000;
  18448. for ( let i = 0; i < 8; i ++ ) {
  18449. if ( i < hardwareClippingPlanes ) {
  18450. this.enable( CLIP_DISTANCE0_WEBGL + i );
  18451. } else {
  18452. this.disable( CLIP_DISTANCE0_WEBGL + i );
  18453. }
  18454. }
  18455. }
  18456. }
  18457. }
  18458. setPolygonOffset( polygonOffset, factor, units ) {
  18459. const { gl } = this;
  18460. if ( polygonOffset ) {
  18461. this.enable( gl.POLYGON_OFFSET_FILL );
  18462. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  18463. gl.polygonOffset( factor, units );
  18464. this.currentPolygonOffsetFactor = factor;
  18465. this.currentPolygonOffsetUnits = units;
  18466. }
  18467. } else {
  18468. this.disable( gl.POLYGON_OFFSET_FILL );
  18469. }
  18470. }
  18471. useProgram( program ) {
  18472. if ( this.currentProgram !== program ) {
  18473. this.gl.useProgram( program );
  18474. this.currentProgram = program;
  18475. return true;
  18476. }
  18477. return false;
  18478. }
  18479. // framebuffer
  18480. bindFramebuffer( target, framebuffer ) {
  18481. const { gl, currentBoundFramebuffers } = this;
  18482. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  18483. gl.bindFramebuffer( target, framebuffer );
  18484. currentBoundFramebuffers[ target ] = framebuffer;
  18485. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  18486. if ( target === gl.DRAW_FRAMEBUFFER ) {
  18487. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  18488. }
  18489. if ( target === gl.FRAMEBUFFER ) {
  18490. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  18491. }
  18492. return true;
  18493. }
  18494. return false;
  18495. }
  18496. drawBuffers( renderContext, framebuffer ) {
  18497. const { gl } = this;
  18498. let drawBuffers = [];
  18499. let needsUpdate = false;
  18500. if ( renderContext.textures !== null ) {
  18501. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  18502. if ( drawBuffers === undefined ) {
  18503. drawBuffers = [];
  18504. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  18505. }
  18506. const textures = renderContext.textures;
  18507. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  18508. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  18509. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  18510. }
  18511. drawBuffers.length = textures.length;
  18512. needsUpdate = true;
  18513. }
  18514. } else {
  18515. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  18516. drawBuffers[ 0 ] = gl.BACK;
  18517. needsUpdate = true;
  18518. }
  18519. }
  18520. if ( needsUpdate ) {
  18521. gl.drawBuffers( drawBuffers );
  18522. }
  18523. }
  18524. // texture
  18525. activeTexture( webglSlot ) {
  18526. const { gl, currentTextureSlot, maxTextures } = this;
  18527. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  18528. if ( currentTextureSlot !== webglSlot ) {
  18529. gl.activeTexture( webglSlot );
  18530. this.currentTextureSlot = webglSlot;
  18531. }
  18532. }
  18533. bindTexture( webglType, webglTexture, webglSlot ) {
  18534. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  18535. if ( webglSlot === undefined ) {
  18536. if ( currentTextureSlot === null ) {
  18537. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  18538. } else {
  18539. webglSlot = currentTextureSlot;
  18540. }
  18541. }
  18542. let boundTexture = currentBoundTextures[ webglSlot ];
  18543. if ( boundTexture === undefined ) {
  18544. boundTexture = { type: undefined, texture: undefined };
  18545. currentBoundTextures[ webglSlot ] = boundTexture;
  18546. }
  18547. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  18548. if ( currentTextureSlot !== webglSlot ) {
  18549. gl.activeTexture( webglSlot );
  18550. this.currentTextureSlot = webglSlot;
  18551. }
  18552. gl.bindTexture( webglType, webglTexture );
  18553. boundTexture.type = webglType;
  18554. boundTexture.texture = webglTexture;
  18555. }
  18556. }
  18557. bindBufferBase( target, index, buffer ) {
  18558. const { gl } = this;
  18559. const key = `${target}-${index}`;
  18560. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  18561. gl.bindBufferBase( target, index, buffer );
  18562. this.currentBoundBufferBases[ key ] = buffer;
  18563. return true;
  18564. }
  18565. return false;
  18566. }
  18567. unbindTexture() {
  18568. const { gl, currentTextureSlot, currentBoundTextures } = this;
  18569. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  18570. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  18571. gl.bindTexture( boundTexture.type, null );
  18572. boundTexture.type = undefined;
  18573. boundTexture.texture = undefined;
  18574. }
  18575. }
  18576. }
  18577. class WebGLUtils {
  18578. constructor( backend ) {
  18579. this.backend = backend;
  18580. this.gl = this.backend.gl;
  18581. this.extensions = backend.extensions;
  18582. }
  18583. convert( p, colorSpace = NoColorSpace ) {
  18584. const { gl, extensions } = this;
  18585. let extension;
  18586. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  18587. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  18588. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  18589. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  18590. if ( p === ByteType ) return gl.BYTE;
  18591. if ( p === ShortType ) return gl.SHORT;
  18592. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  18593. if ( p === IntType ) return gl.INT;
  18594. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  18595. if ( p === FloatType ) return gl.FLOAT;
  18596. if ( p === HalfFloatType ) {
  18597. return gl.HALF_FLOAT;
  18598. }
  18599. if ( p === AlphaFormat ) return gl.ALPHA;
  18600. if ( p === RGBFormat ) return gl.RGB;
  18601. if ( p === RGBAFormat ) return gl.RGBA;
  18602. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  18603. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  18604. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  18605. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  18606. // WebGL2 formats.
  18607. if ( p === RedFormat ) return gl.RED;
  18608. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  18609. if ( p === RGFormat ) return gl.RG;
  18610. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  18611. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  18612. // S3TC
  18613. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  18614. if ( colorSpace === SRGBColorSpace ) {
  18615. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  18616. if ( extension !== null ) {
  18617. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  18618. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  18619. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  18620. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  18621. } else {
  18622. return null;
  18623. }
  18624. } else {
  18625. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  18626. if ( extension !== null ) {
  18627. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  18628. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  18629. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  18630. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  18631. } else {
  18632. return null;
  18633. }
  18634. }
  18635. }
  18636. // PVRTC
  18637. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  18638. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  18639. if ( extension !== null ) {
  18640. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  18641. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  18642. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  18643. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  18644. } else {
  18645. return null;
  18646. }
  18647. }
  18648. // ETC
  18649. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  18650. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  18651. if ( extension !== null ) {
  18652. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  18653. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  18654. } else {
  18655. return null;
  18656. }
  18657. }
  18658. // ASTC
  18659. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  18660. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  18661. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  18662. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  18663. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  18664. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  18665. if ( extension !== null ) {
  18666. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  18667. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  18668. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  18669. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  18670. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  18671. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  18672. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  18673. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  18674. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  18675. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  18676. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  18677. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  18678. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  18679. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  18680. } else {
  18681. return null;
  18682. }
  18683. }
  18684. // BPTC
  18685. if ( p === RGBA_BPTC_Format ) {
  18686. extension = extensions.get( 'EXT_texture_compression_bptc' );
  18687. if ( extension !== null ) {
  18688. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  18689. } else {
  18690. return null;
  18691. }
  18692. }
  18693. // RGTC
  18694. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  18695. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  18696. if ( extension !== null ) {
  18697. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  18698. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  18699. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  18700. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  18701. } else {
  18702. return null;
  18703. }
  18704. }
  18705. //
  18706. if ( p === UnsignedInt248Type ) {
  18707. return gl.UNSIGNED_INT_24_8;
  18708. }
  18709. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  18710. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  18711. }
  18712. _clientWaitAsync() {
  18713. const { gl } = this;
  18714. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  18715. gl.flush();
  18716. return new Promise( ( resolve, reject ) => {
  18717. function test() {
  18718. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  18719. if ( res === gl.WAIT_FAILED ) {
  18720. gl.deleteSync( sync );
  18721. reject();
  18722. return;
  18723. }
  18724. if ( res === gl.TIMEOUT_EXPIRED ) {
  18725. requestAnimationFrame( test );
  18726. return;
  18727. }
  18728. gl.deleteSync( sync );
  18729. resolve();
  18730. }
  18731. test();
  18732. } );
  18733. }
  18734. }
  18735. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  18736. class WebGLTextureUtils {
  18737. constructor( backend ) {
  18738. this.backend = backend;
  18739. this.gl = backend.gl;
  18740. this.extensions = backend.extensions;
  18741. this.defaultTextures = {};
  18742. if ( initialized === false ) {
  18743. this._init( this.gl );
  18744. initialized = true;
  18745. }
  18746. }
  18747. _init( gl ) {
  18748. // Store only WebGL constants here.
  18749. wrappingToGL = {
  18750. [ RepeatWrapping ]: gl.REPEAT,
  18751. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  18752. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  18753. };
  18754. filterToGL = {
  18755. [ NearestFilter ]: gl.NEAREST,
  18756. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  18757. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  18758. [ LinearFilter ]: gl.LINEAR,
  18759. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  18760. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  18761. };
  18762. compareToGL = {
  18763. [ NeverCompare ]: gl.NEVER,
  18764. [ AlwaysCompare ]: gl.ALWAYS,
  18765. [ LessCompare ]: gl.LESS,
  18766. [ LessEqualCompare ]: gl.LEQUAL,
  18767. [ EqualCompare ]: gl.EQUAL,
  18768. [ GreaterEqualCompare ]: gl.GEQUAL,
  18769. [ GreaterCompare ]: gl.GREATER,
  18770. [ NotEqualCompare ]: gl.NOTEQUAL
  18771. };
  18772. }
  18773. filterFallback( f ) {
  18774. const { gl } = this;
  18775. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  18776. return gl.NEAREST;
  18777. }
  18778. return gl.LINEAR;
  18779. }
  18780. getGLTextureType( texture ) {
  18781. const { gl } = this;
  18782. let glTextureType;
  18783. if ( texture.isCubeTexture === true ) {
  18784. glTextureType = gl.TEXTURE_CUBE_MAP;
  18785. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  18786. glTextureType = gl.TEXTURE_2D_ARRAY;
  18787. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  18788. glTextureType = gl.TEXTURE_3D;
  18789. } else {
  18790. glTextureType = gl.TEXTURE_2D;
  18791. }
  18792. return glTextureType;
  18793. }
  18794. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  18795. const { gl, extensions } = this;
  18796. if ( internalFormatName !== null ) {
  18797. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  18798. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  18799. }
  18800. let internalFormat = glFormat;
  18801. if ( glFormat === gl.RED ) {
  18802. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  18803. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  18804. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  18805. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  18806. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  18807. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  18808. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  18809. if ( glType === gl.INT ) internalFormat = gl.R32I;
  18810. }
  18811. if ( glFormat === gl.RED_INTEGER ) {
  18812. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  18813. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  18814. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  18815. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  18816. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  18817. if ( glType === gl.INT ) internalFormat = gl.R32I;
  18818. }
  18819. if ( glFormat === gl.RG ) {
  18820. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  18821. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  18822. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  18823. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  18824. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  18825. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  18826. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  18827. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  18828. }
  18829. if ( glFormat === gl.RG_INTEGER ) {
  18830. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  18831. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  18832. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  18833. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  18834. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  18835. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  18836. }
  18837. if ( glFormat === gl.RGB ) {
  18838. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  18839. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  18840. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  18841. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  18842. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  18843. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  18844. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  18845. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  18846. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  18847. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  18848. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  18849. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  18850. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  18851. }
  18852. if ( glFormat === gl.RGB_INTEGER ) {
  18853. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  18854. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  18855. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  18856. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  18857. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  18858. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  18859. }
  18860. if ( glFormat === gl.RGBA ) {
  18861. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  18862. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  18863. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  18864. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  18865. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  18866. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  18867. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  18868. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  18869. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  18870. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  18871. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  18872. }
  18873. if ( glFormat === gl.RGBA_INTEGER ) {
  18874. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  18875. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  18876. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  18877. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  18878. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  18879. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  18880. }
  18881. if ( glFormat === gl.DEPTH_COMPONENT ) {
  18882. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  18883. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  18884. }
  18885. if ( glFormat === gl.DEPTH_STENCIL ) {
  18886. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  18887. }
  18888. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  18889. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  18890. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  18891. extensions.get( 'EXT_color_buffer_float' );
  18892. }
  18893. return internalFormat;
  18894. }
  18895. setTextureParameters( textureType, texture ) {
  18896. const { gl, extensions, backend } = this;
  18897. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  18898. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  18899. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  18900. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  18901. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  18902. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  18903. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  18904. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  18905. }
  18906. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  18907. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  18908. // follow WebGPU backend mapping for texture filtering
  18909. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  18910. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  18911. if ( texture.compareFunction ) {
  18912. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  18913. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  18914. }
  18915. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  18916. if ( texture.magFilter === NearestFilter ) return;
  18917. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  18918. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  18919. if ( texture.anisotropy > 1 ) {
  18920. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  18921. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  18922. }
  18923. }
  18924. }
  18925. createDefaultTexture( texture ) {
  18926. const { gl, backend, defaultTextures } = this;
  18927. const glTextureType = this.getGLTextureType( texture );
  18928. let textureGPU = defaultTextures[ glTextureType ];
  18929. if ( textureGPU === undefined ) {
  18930. textureGPU = gl.createTexture();
  18931. backend.state.bindTexture( glTextureType, textureGPU );
  18932. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  18933. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  18934. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  18935. defaultTextures[ glTextureType ] = textureGPU;
  18936. }
  18937. backend.set( texture, {
  18938. textureGPU,
  18939. glTextureType,
  18940. isDefault: true
  18941. } );
  18942. }
  18943. createTexture( texture, options ) {
  18944. const { gl, backend } = this;
  18945. const { levels, width, height, depth } = options;
  18946. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  18947. const glType = backend.utils.convert( texture.type );
  18948. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  18949. const textureGPU = gl.createTexture();
  18950. const glTextureType = this.getGLTextureType( texture );
  18951. backend.state.bindTexture( glTextureType, textureGPU );
  18952. this.setTextureParameters( glTextureType, texture );
  18953. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  18954. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  18955. } else if ( texture.isData3DTexture ) {
  18956. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  18957. } else if ( ! texture.isVideoTexture ) {
  18958. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  18959. }
  18960. backend.set( texture, {
  18961. textureGPU,
  18962. glTextureType,
  18963. glFormat,
  18964. glType,
  18965. glInternalFormat
  18966. } );
  18967. }
  18968. copyBufferToTexture( buffer, texture ) {
  18969. const { gl, backend } = this;
  18970. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  18971. const { width, height } = texture.source.data;
  18972. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  18973. backend.state.bindTexture( glTextureType, textureGPU );
  18974. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  18975. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  18976. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  18977. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  18978. backend.state.unbindTexture();
  18979. // debug
  18980. // const framebuffer = gl.createFramebuffer();
  18981. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  18982. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  18983. // const readout = new Float32Array( width * height * 4 );
  18984. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  18985. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  18986. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  18987. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  18988. // console.log( readout );
  18989. }
  18990. updateTexture( texture, options ) {
  18991. const { gl } = this;
  18992. const { width, height } = options;
  18993. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  18994. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  18995. return;
  18996. const getImage = ( source ) => {
  18997. if ( source.isDataTexture ) {
  18998. return source.image.data;
  18999. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  19000. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  19001. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  19002. source instanceof OffscreenCanvas ) {
  19003. return source;
  19004. }
  19005. return source.data;
  19006. };
  19007. this.backend.state.bindTexture( glTextureType, textureGPU );
  19008. this.setTextureParameters( glTextureType, texture );
  19009. if ( texture.isCompressedTexture ) {
  19010. const mipmaps = texture.mipmaps;
  19011. const image = options.image;
  19012. for ( let i = 0; i < mipmaps.length; i ++ ) {
  19013. const mipmap = mipmaps[ i ];
  19014. if ( texture.isCompressedArrayTexture ) {
  19015. if ( texture.format !== gl.RGBA ) {
  19016. if ( glFormat !== null ) {
  19017. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  19018. } else {
  19019. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  19020. }
  19021. } else {
  19022. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  19023. }
  19024. } else {
  19025. if ( glFormat !== null ) {
  19026. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  19027. } else {
  19028. console.warn( 'Unsupported compressed texture format' );
  19029. }
  19030. }
  19031. }
  19032. } else if ( texture.isCubeTexture ) {
  19033. const images = options.images;
  19034. for ( let i = 0; i < 6; i ++ ) {
  19035. const image = getImage( images[ i ] );
  19036. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  19037. }
  19038. } else if ( texture.isDataArrayTexture ) {
  19039. const image = options.image;
  19040. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  19041. } else if ( texture.isData3DTexture ) {
  19042. const image = options.image;
  19043. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  19044. } else if ( texture.isVideoTexture ) {
  19045. texture.update();
  19046. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  19047. } else {
  19048. const image = getImage( options.image );
  19049. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  19050. }
  19051. }
  19052. generateMipmaps( texture ) {
  19053. const { gl, backend } = this;
  19054. const { textureGPU, glTextureType } = backend.get( texture );
  19055. backend.state.bindTexture( glTextureType, textureGPU );
  19056. gl.generateMipmap( glTextureType );
  19057. }
  19058. deallocateRenderBuffers( renderTarget ) {
  19059. const { gl, backend } = this;
  19060. // remove framebuffer reference
  19061. if ( renderTarget ) {
  19062. const renderContextData = backend.get( renderTarget );
  19063. renderContextData.renderBufferStorageSetup = undefined;
  19064. if ( renderContextData.framebuffers ) {
  19065. for ( const cacheKey in renderContextData.framebuffers ) {
  19066. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  19067. }
  19068. delete renderContextData.framebuffers;
  19069. }
  19070. if ( renderContextData.depthRenderbuffer ) {
  19071. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  19072. delete renderContextData.depthRenderbuffer;
  19073. }
  19074. if ( renderContextData.stencilRenderbuffer ) {
  19075. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  19076. delete renderContextData.stencilRenderbuffer;
  19077. }
  19078. if ( renderContextData.msaaFrameBuffer ) {
  19079. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  19080. delete renderContextData.msaaFrameBuffer;
  19081. }
  19082. if ( renderContextData.msaaRenderbuffers ) {
  19083. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  19084. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  19085. }
  19086. delete renderContextData.msaaRenderbuffers;
  19087. }
  19088. }
  19089. }
  19090. destroyTexture( texture ) {
  19091. const { gl, backend } = this;
  19092. const { textureGPU, renderTarget } = backend.get( texture );
  19093. this.deallocateRenderBuffers( renderTarget );
  19094. gl.deleteTexture( textureGPU );
  19095. backend.delete( texture );
  19096. }
  19097. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  19098. const { gl, backend } = this;
  19099. const { state } = this.backend;
  19100. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  19101. let width, height, minX, minY;
  19102. let dstX, dstY;
  19103. if ( srcRegion !== null ) {
  19104. width = srcRegion.max.x - srcRegion.min.x;
  19105. height = srcRegion.max.y - srcRegion.min.y;
  19106. minX = srcRegion.min.x;
  19107. minY = srcRegion.min.y;
  19108. } else {
  19109. width = srcTexture.image.width;
  19110. height = srcTexture.image.height;
  19111. minX = 0;
  19112. minY = 0;
  19113. }
  19114. if ( dstPosition !== null ) {
  19115. dstX = dstPosition.x;
  19116. dstY = dstPosition.y;
  19117. } else {
  19118. dstX = 0;
  19119. dstY = 0;
  19120. }
  19121. state.bindTexture( glTextureType, dstTextureGPU );
  19122. // As another texture upload may have changed pixelStorei
  19123. // parameters, make sure they are correct for the dstTexture
  19124. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  19125. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  19126. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  19127. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  19128. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  19129. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  19130. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  19131. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  19132. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  19133. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  19134. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  19135. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  19136. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  19137. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  19138. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  19139. const srcTextureData = backend.get( srcTexture );
  19140. const dstTextureData = backend.get( dstTexture );
  19141. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  19142. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  19143. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  19144. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  19145. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  19146. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  19147. let mask = gl.COLOR_BUFFER_BIT;
  19148. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  19149. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  19150. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  19151. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  19152. } else {
  19153. if ( srcTexture.isDataTexture ) {
  19154. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  19155. } else {
  19156. if ( srcTexture.isCompressedTexture ) {
  19157. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  19158. } else {
  19159. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  19160. }
  19161. }
  19162. }
  19163. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  19164. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  19165. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  19166. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  19167. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  19168. // Generate mipmaps only when copying level 0
  19169. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  19170. state.unbindTexture();
  19171. }
  19172. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  19173. const { gl } = this;
  19174. const { state } = this.backend;
  19175. const { textureGPU } = this.backend.get( texture );
  19176. const { x, y, z: width, w: height } = rectangle;
  19177. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  19178. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.gerDrawingBufferSize().y;
  19179. if ( requireDrawFrameBuffer ) {
  19180. const partial = ( x !== 0 || y !== 0 );
  19181. let mask;
  19182. let attachment;
  19183. if ( texture.isDepthTexture === true ) {
  19184. mask = gl.DEPTH_BUFFER_BIT;
  19185. attachment = gl.DEPTH_ATTACHMENT;
  19186. if ( renderContext.stencil ) {
  19187. mask |= gl.STENCIL_BUFFER_BIT;
  19188. }
  19189. } else {
  19190. mask = gl.COLOR_BUFFER_BIT;
  19191. attachment = gl.COLOR_ATTACHMENT0;
  19192. }
  19193. if ( partial ) {
  19194. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  19195. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  19196. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  19197. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  19198. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  19199. const flippedY = srcHeight - y - height;
  19200. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  19201. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  19202. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  19203. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  19204. state.unbindTexture();
  19205. } else {
  19206. const fb = gl.createFramebuffer();
  19207. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  19208. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  19209. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  19210. gl.deleteFramebuffer( fb );
  19211. }
  19212. } else {
  19213. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  19214. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  19215. state.unbindTexture();
  19216. }
  19217. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  19218. this.backend._setFramebuffer( renderContext );
  19219. }
  19220. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  19221. setupRenderBufferStorage( renderbuffer, renderContext ) {
  19222. const { gl } = this;
  19223. const renderTarget = renderContext.renderTarget;
  19224. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  19225. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  19226. if ( depthBuffer && ! stencilBuffer ) {
  19227. let glInternalFormat = gl.DEPTH_COMPONENT24;
  19228. if ( samples > 0 ) {
  19229. if ( depthTexture && depthTexture.isDepthTexture ) {
  19230. if ( depthTexture.type === gl.FLOAT ) {
  19231. glInternalFormat = gl.DEPTH_COMPONENT32F;
  19232. }
  19233. }
  19234. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  19235. } else {
  19236. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  19237. }
  19238. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  19239. } else if ( depthBuffer && stencilBuffer ) {
  19240. if ( samples > 0 ) {
  19241. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  19242. } else {
  19243. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  19244. }
  19245. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  19246. }
  19247. }
  19248. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  19249. const { backend, gl } = this;
  19250. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  19251. const fb = gl.createFramebuffer();
  19252. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  19253. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  19254. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  19255. const typedArrayType = this._getTypedArrayType( glType );
  19256. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  19257. const elementCount = width * height;
  19258. const byteLength = elementCount * bytesPerTexel;
  19259. const buffer = gl.createBuffer();
  19260. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  19261. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  19262. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  19263. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  19264. await backend.utils._clientWaitAsync();
  19265. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  19266. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  19267. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  19268. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  19269. gl.deleteFramebuffer( fb );
  19270. return dstBuffer;
  19271. }
  19272. _getTypedArrayType( glType ) {
  19273. const { gl } = this;
  19274. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  19275. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  19276. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  19277. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  19278. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  19279. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  19280. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  19281. if ( glType === gl.FLOAT ) return Float32Array;
  19282. throw new Error( `Unsupported WebGL type: ${glType}` );
  19283. }
  19284. _getBytesPerTexel( glType, glFormat ) {
  19285. const { gl } = this;
  19286. let bytesPerComponent = 0;
  19287. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  19288. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  19289. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  19290. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  19291. glType === gl.UNSIGNED_SHORT ||
  19292. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  19293. if ( glType === gl.UNSIGNED_INT ||
  19294. glType === gl.FLOAT ) bytesPerComponent = 4;
  19295. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  19296. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  19297. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  19298. }
  19299. }
  19300. class WebGLExtensions {
  19301. constructor( backend ) {
  19302. this.backend = backend;
  19303. this.gl = this.backend.gl;
  19304. this.availableExtensions = this.gl.getSupportedExtensions();
  19305. this.extensions = {};
  19306. }
  19307. get( name ) {
  19308. let extension = this.extensions[ name ];
  19309. if ( extension === undefined ) {
  19310. extension = this.gl.getExtension( name );
  19311. this.extensions[ name ] = extension;
  19312. }
  19313. return extension;
  19314. }
  19315. has( name ) {
  19316. return this.availableExtensions.includes( name );
  19317. }
  19318. }
  19319. class WebGLCapabilities {
  19320. constructor( backend ) {
  19321. this.backend = backend;
  19322. this.maxAnisotropy = null;
  19323. }
  19324. getMaxAnisotropy() {
  19325. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  19326. const gl = this.backend.gl;
  19327. const extensions = this.backend.extensions;
  19328. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  19329. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  19330. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  19331. } else {
  19332. this.maxAnisotropy = 0;
  19333. }
  19334. return this.maxAnisotropy;
  19335. }
  19336. }
  19337. const GLFeatureName = {
  19338. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  19339. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  19340. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  19341. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  19342. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  19343. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  19344. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  19345. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  19346. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  19347. };
  19348. class WebGLBufferRenderer {
  19349. constructor( backend ) {
  19350. this.gl = backend.gl;
  19351. this.extensions = backend.extensions;
  19352. this.info = backend.renderer.info;
  19353. this.mode = null;
  19354. this.index = 0;
  19355. this.type = null;
  19356. this.object = null;
  19357. }
  19358. render( start, count ) {
  19359. const { gl, mode, object, type, info, index } = this;
  19360. if ( index !== 0 ) {
  19361. gl.drawElements( mode, count, type, start );
  19362. } else {
  19363. gl.drawArrays( mode, start, count );
  19364. }
  19365. info.update( object, count, mode, 1 );
  19366. }
  19367. renderInstances( start, count, primcount ) {
  19368. const { gl, mode, type, index, object, info } = this;
  19369. if ( primcount === 0 ) return;
  19370. if ( index !== 0 ) {
  19371. gl.drawElementsInstanced( mode, count, type, start, primcount );
  19372. } else {
  19373. gl.drawArraysInstanced( mode, start, count, primcount );
  19374. }
  19375. info.update( object, count, mode, primcount );
  19376. }
  19377. renderMultiDraw( starts, counts, drawCount ) {
  19378. const { extensions, mode, object, info } = this;
  19379. if ( drawCount === 0 ) return;
  19380. const extension = extensions.get( 'WEBGL_multi_draw' );
  19381. if ( extension === null ) {
  19382. for ( let i = 0; i < drawCount; i ++ ) {
  19383. this.render( starts[ i ], counts[ i ] );
  19384. }
  19385. } else {
  19386. if ( this.index !== 0 ) {
  19387. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  19388. } else {
  19389. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  19390. }
  19391. let elementCount = 0;
  19392. for ( let i = 0; i < drawCount; i ++ ) {
  19393. elementCount += counts[ i ];
  19394. }
  19395. info.update( object, elementCount, mode, 1 );
  19396. }
  19397. }
  19398. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  19399. const { extensions, mode, object, info } = this;
  19400. if ( drawCount === 0 ) return;
  19401. const extension = extensions.get( 'WEBGL_multi_draw' );
  19402. if ( extension === null ) {
  19403. for ( let i = 0; i < drawCount; i ++ ) {
  19404. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  19405. }
  19406. } else {
  19407. if ( this.index !== 0 ) {
  19408. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  19409. } else {
  19410. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  19411. }
  19412. let elementCount = 0;
  19413. for ( let i = 0; i < drawCount; i ++ ) {
  19414. elementCount += counts[ i ] * primcount[ i ];
  19415. }
  19416. info.update( object, elementCount, mode, 1 );
  19417. }
  19418. }
  19419. //
  19420. }
  19421. //
  19422. class WebGLBackend extends Backend {
  19423. constructor( parameters = {} ) {
  19424. super( parameters );
  19425. this.isWebGLBackend = true;
  19426. }
  19427. init( renderer ) {
  19428. super.init( renderer );
  19429. //
  19430. const parameters = this.parameters;
  19431. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  19432. function onContextLost( event ) {
  19433. event.preventDefault();
  19434. const contextLossInfo = {
  19435. api: 'WebGL',
  19436. message: event.statusMessage || 'Unknown reason',
  19437. reason: null,
  19438. originalEvent: event
  19439. };
  19440. renderer.onDeviceLost( contextLossInfo );
  19441. }
  19442. this._onContextLost = onContextLost;
  19443. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  19444. this.gl = glContext;
  19445. this.extensions = new WebGLExtensions( this );
  19446. this.capabilities = new WebGLCapabilities( this );
  19447. this.attributeUtils = new WebGLAttributeUtils( this );
  19448. this.textureUtils = new WebGLTextureUtils( this );
  19449. this.bufferRenderer = new WebGLBufferRenderer( this );
  19450. this.state = new WebGLState( this );
  19451. this.utils = new WebGLUtils( this );
  19452. this.vaoCache = {};
  19453. this.transformFeedbackCache = {};
  19454. this.discard = false;
  19455. this.trackTimestamp = ( parameters.trackTimestamp === true );
  19456. this.extensions.get( 'EXT_color_buffer_float' );
  19457. this.extensions.get( 'WEBGL_clip_cull_distance' );
  19458. this.extensions.get( 'OES_texture_float_linear' );
  19459. this.extensions.get( 'EXT_color_buffer_half_float' );
  19460. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  19461. this.extensions.get( 'WEBGL_render_shared_exponent' );
  19462. this.extensions.get( 'WEBGL_multi_draw' );
  19463. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  19464. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  19465. this._knownBindings = new WeakSet();
  19466. this._currentContext = null;
  19467. }
  19468. get coordinateSystem() {
  19469. return WebGLCoordinateSystem;
  19470. }
  19471. async getArrayBufferAsync( attribute ) {
  19472. return await this.attributeUtils.getArrayBufferAsync( attribute );
  19473. }
  19474. async waitForGPU() {
  19475. await this.utils._clientWaitAsync();
  19476. }
  19477. initTimestampQuery( renderContext ) {
  19478. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  19479. const renderContextData = this.get( renderContext );
  19480. if ( this.queryRunning ) {
  19481. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  19482. renderContextData.queryQueue.push( renderContext );
  19483. return;
  19484. }
  19485. if ( renderContextData.activeQuery ) {
  19486. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  19487. renderContextData.activeQuery = null;
  19488. }
  19489. renderContextData.activeQuery = this.gl.createQuery();
  19490. if ( renderContextData.activeQuery !== null ) {
  19491. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  19492. this.queryRunning = true;
  19493. }
  19494. }
  19495. // timestamp utils
  19496. prepareTimestampBuffer( renderContext ) {
  19497. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  19498. const renderContextData = this.get( renderContext );
  19499. if ( renderContextData.activeQuery ) {
  19500. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  19501. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  19502. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  19503. renderContextData.activeQuery = null;
  19504. this.queryRunning = false;
  19505. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  19506. const nextRenderContext = renderContextData.queryQueue.shift();
  19507. this.initTimestampQuery( nextRenderContext );
  19508. }
  19509. }
  19510. }
  19511. async resolveTimestampAsync( renderContext, type = 'render' ) {
  19512. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  19513. const renderContextData = this.get( renderContext );
  19514. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  19515. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  19516. const queryInfo = renderContextData.gpuQueries[ i ];
  19517. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  19518. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  19519. if ( available && ! disjoint ) {
  19520. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  19521. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  19522. this.gl.deleteQuery( queryInfo.query );
  19523. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  19524. i --;
  19525. this.renderer.info.updateTimestamp( type, duration );
  19526. }
  19527. }
  19528. }
  19529. getContext() {
  19530. return this.gl;
  19531. }
  19532. beginRender( renderContext ) {
  19533. const { gl } = this;
  19534. const renderContextData = this.get( renderContext );
  19535. //
  19536. //
  19537. this.initTimestampQuery( renderContext );
  19538. renderContextData.previousContext = this._currentContext;
  19539. this._currentContext = renderContext;
  19540. this._setFramebuffer( renderContext );
  19541. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  19542. //
  19543. if ( renderContext.viewport ) {
  19544. this.updateViewport( renderContext );
  19545. } else {
  19546. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  19547. }
  19548. if ( renderContext.scissor ) {
  19549. const { x, y, width, height } = renderContext.scissorValue;
  19550. gl.scissor( x, renderContext.height - height - y, width, height );
  19551. }
  19552. const occlusionQueryCount = renderContext.occlusionQueryCount;
  19553. if ( occlusionQueryCount > 0 ) {
  19554. // Get a reference to the array of objects with queries. The renderContextData property
  19555. // can be changed by another render pass before the async reading of all previous queries complete
  19556. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  19557. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  19558. renderContextData.lastOcclusionObject = null;
  19559. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  19560. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  19561. renderContextData.occlusionQueryIndex = 0;
  19562. }
  19563. }
  19564. finishRender( renderContext ) {
  19565. const { gl, state } = this;
  19566. const renderContextData = this.get( renderContext );
  19567. const previousContext = renderContextData.previousContext;
  19568. const occlusionQueryCount = renderContext.occlusionQueryCount;
  19569. if ( occlusionQueryCount > 0 ) {
  19570. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  19571. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  19572. }
  19573. this.resolveOccludedAsync( renderContext );
  19574. }
  19575. const textures = renderContext.textures;
  19576. if ( textures !== null ) {
  19577. for ( let i = 0; i < textures.length; i ++ ) {
  19578. const texture = textures[ i ];
  19579. if ( texture.generateMipmaps ) {
  19580. this.generateMipmaps( texture );
  19581. }
  19582. }
  19583. }
  19584. this._currentContext = previousContext;
  19585. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  19586. const renderTargetContextData = this.get( renderContext.renderTarget );
  19587. const { samples } = renderContext.renderTarget;
  19588. if ( samples > 0 ) {
  19589. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  19590. const mask = gl.COLOR_BUFFER_BIT;
  19591. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  19592. const textures = renderContext.textures;
  19593. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  19594. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  19595. for ( let i = 0; i < textures.length; i ++ ) {
  19596. // TODO Add support for MRT
  19597. if ( renderContext.scissor ) {
  19598. const { x, y, width, height } = renderContext.scissorValue;
  19599. const viewY = renderContext.height - height - y;
  19600. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  19601. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  19602. } else {
  19603. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  19604. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  19605. }
  19606. }
  19607. }
  19608. }
  19609. if ( previousContext !== null ) {
  19610. this._setFramebuffer( previousContext );
  19611. if ( previousContext.viewport ) {
  19612. this.updateViewport( previousContext );
  19613. } else {
  19614. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  19615. }
  19616. }
  19617. this.prepareTimestampBuffer( renderContext );
  19618. }
  19619. resolveOccludedAsync( renderContext ) {
  19620. const renderContextData = this.get( renderContext );
  19621. // handle occlusion query results
  19622. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  19623. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  19624. const occluded = new WeakSet();
  19625. const { gl } = this;
  19626. renderContextData.currentOcclusionQueryObjects = null;
  19627. renderContextData.currentOcclusionQueries = null;
  19628. const check = () => {
  19629. let completed = 0;
  19630. // check all queries and requeue as appropriate
  19631. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  19632. const query = currentOcclusionQueries[ i ];
  19633. if ( query === null ) continue;
  19634. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  19635. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  19636. currentOcclusionQueries[ i ] = null;
  19637. gl.deleteQuery( query );
  19638. completed ++;
  19639. }
  19640. }
  19641. if ( completed < currentOcclusionQueries.length ) {
  19642. requestAnimationFrame( check );
  19643. } else {
  19644. renderContextData.occluded = occluded;
  19645. }
  19646. };
  19647. check();
  19648. }
  19649. }
  19650. isOccluded( renderContext, object ) {
  19651. const renderContextData = this.get( renderContext );
  19652. return renderContextData.occluded && renderContextData.occluded.has( object );
  19653. }
  19654. updateViewport( renderContext ) {
  19655. const gl = this.gl;
  19656. const { x, y, width, height } = renderContext.viewportValue;
  19657. gl.viewport( x, renderContext.height - height - y, width, height );
  19658. }
  19659. setScissorTest( boolean ) {
  19660. const gl = this.gl;
  19661. if ( boolean ) {
  19662. gl.enable( gl.SCISSOR_TEST );
  19663. } else {
  19664. gl.disable( gl.SCISSOR_TEST );
  19665. }
  19666. }
  19667. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  19668. const { gl } = this;
  19669. if ( descriptor === null ) {
  19670. const clearColor = this.getClearColor();
  19671. // premultiply alpha
  19672. clearColor.r *= clearColor.a;
  19673. clearColor.g *= clearColor.a;
  19674. clearColor.b *= clearColor.a;
  19675. descriptor = {
  19676. textures: null,
  19677. clearColorValue: clearColor
  19678. };
  19679. }
  19680. //
  19681. let clear = 0;
  19682. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  19683. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  19684. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  19685. if ( clear !== 0 ) {
  19686. let clearColor;
  19687. if ( descriptor.clearColorValue ) {
  19688. clearColor = descriptor.clearColorValue;
  19689. } else {
  19690. clearColor = this.getClearColor();
  19691. // premultiply alpha
  19692. clearColor.r *= clearColor.a;
  19693. clearColor.g *= clearColor.a;
  19694. clearColor.b *= clearColor.a;
  19695. }
  19696. if ( depth ) this.state.setDepthMask( true );
  19697. if ( descriptor.textures === null ) {
  19698. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  19699. gl.clear( clear );
  19700. } else {
  19701. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  19702. if ( color ) {
  19703. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  19704. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  19705. }
  19706. }
  19707. if ( depth && stencil ) {
  19708. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  19709. } else if ( depth ) {
  19710. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  19711. } else if ( stencil ) {
  19712. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  19713. }
  19714. }
  19715. }
  19716. }
  19717. beginCompute( computeGroup ) {
  19718. const { state, gl } = this;
  19719. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  19720. this.initTimestampQuery( computeGroup );
  19721. }
  19722. compute( computeGroup, computeNode, bindings, pipeline ) {
  19723. const { state, gl } = this;
  19724. if ( ! this.discard ) {
  19725. // required here to handle async behaviour of render.compute()
  19726. gl.enable( gl.RASTERIZER_DISCARD );
  19727. this.discard = true;
  19728. }
  19729. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  19730. const vaoKey = this._getVaoKey( null, attributes );
  19731. const vaoGPU = this.vaoCache[ vaoKey ];
  19732. if ( vaoGPU === undefined ) {
  19733. this._createVao( null, attributes );
  19734. } else {
  19735. gl.bindVertexArray( vaoGPU );
  19736. }
  19737. state.useProgram( programGPU );
  19738. this._bindUniforms( bindings );
  19739. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  19740. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  19741. gl.beginTransformFeedback( gl.POINTS );
  19742. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  19743. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  19744. } else {
  19745. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  19746. }
  19747. gl.endTransformFeedback();
  19748. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  19749. // switch active buffers
  19750. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  19751. const dualAttributeData = transformBuffers[ i ];
  19752. if ( dualAttributeData.pbo ) {
  19753. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  19754. }
  19755. dualAttributeData.switchBuffers();
  19756. }
  19757. }
  19758. finishCompute( computeGroup ) {
  19759. const gl = this.gl;
  19760. this.discard = false;
  19761. gl.disable( gl.RASTERIZER_DISCARD );
  19762. this.prepareTimestampBuffer( computeGroup );
  19763. if ( this._currentContext ) {
  19764. this._setFramebuffer( this._currentContext );
  19765. }
  19766. }
  19767. draw( renderObject/*, info*/ ) {
  19768. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  19769. const { programGPU } = this.get( pipeline );
  19770. const { gl, state } = this;
  19771. const contextData = this.get( context );
  19772. const drawParams = renderObject.getDrawParameters();
  19773. if ( drawParams === null ) return;
  19774. //
  19775. this._bindUniforms( renderObject.getBindings() );
  19776. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  19777. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  19778. state.useProgram( programGPU );
  19779. //
  19780. const renderObjectData = this.get( renderObject );
  19781. let vaoGPU = renderObjectData.staticVao;
  19782. if ( vaoGPU === undefined || renderObjectData.geometryId !== renderObject.geometry.id ) {
  19783. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  19784. vaoGPU = this.vaoCache[ vaoKey ];
  19785. if ( vaoGPU === undefined ) {
  19786. let staticVao;
  19787. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  19788. if ( staticVao ) {
  19789. renderObjectData.staticVao = vaoGPU;
  19790. renderObjectData.geometryId = renderObject.geometry.id;
  19791. }
  19792. }
  19793. }
  19794. gl.bindVertexArray( vaoGPU );
  19795. //
  19796. const index = renderObject.getIndex();
  19797. //
  19798. const lastObject = contextData.lastOcclusionObject;
  19799. if ( lastObject !== object && lastObject !== undefined ) {
  19800. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  19801. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  19802. contextData.occlusionQueryIndex ++;
  19803. }
  19804. if ( object.occlusionTest === true ) {
  19805. const query = gl.createQuery();
  19806. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  19807. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  19808. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  19809. }
  19810. contextData.lastOcclusionObject = object;
  19811. }
  19812. //
  19813. const renderer = this.bufferRenderer;
  19814. if ( object.isPoints ) renderer.mode = gl.POINTS;
  19815. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  19816. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  19817. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  19818. else {
  19819. if ( material.wireframe === true ) {
  19820. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  19821. renderer.mode = gl.LINES;
  19822. } else {
  19823. renderer.mode = gl.TRIANGLES;
  19824. }
  19825. }
  19826. //
  19827. const { vertexCount, instanceCount } = drawParams;
  19828. let { firstVertex } = drawParams;
  19829. renderer.object = object;
  19830. if ( index !== null ) {
  19831. firstVertex *= index.array.BYTES_PER_ELEMENT;
  19832. const indexData = this.get( index );
  19833. renderer.index = index.count;
  19834. renderer.type = indexData.type;
  19835. } else {
  19836. renderer.index = 0;
  19837. }
  19838. if ( object.isBatchedMesh ) {
  19839. if ( object._multiDrawInstances !== null ) {
  19840. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  19841. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  19842. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  19843. } else {
  19844. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  19845. }
  19846. } else if ( instanceCount > 1 ) {
  19847. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  19848. } else {
  19849. renderer.render( firstVertex, vertexCount );
  19850. }
  19851. //
  19852. gl.bindVertexArray( null );
  19853. }
  19854. needsRenderUpdate( /*renderObject*/ ) {
  19855. return false;
  19856. }
  19857. getRenderCacheKey( /*renderObject*/ ) {
  19858. return '';
  19859. }
  19860. // textures
  19861. createDefaultTexture( texture ) {
  19862. this.textureUtils.createDefaultTexture( texture );
  19863. }
  19864. createTexture( texture, options ) {
  19865. this.textureUtils.createTexture( texture, options );
  19866. }
  19867. updateTexture( texture, options ) {
  19868. this.textureUtils.updateTexture( texture, options );
  19869. }
  19870. generateMipmaps( texture ) {
  19871. this.textureUtils.generateMipmaps( texture );
  19872. }
  19873. destroyTexture( texture ) {
  19874. this.textureUtils.destroyTexture( texture );
  19875. }
  19876. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  19877. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  19878. }
  19879. createSampler( /*texture*/ ) {
  19880. //console.warn( 'Abstract class.' );
  19881. }
  19882. destroySampler() {}
  19883. // node builder
  19884. createNodeBuilder( object, renderer ) {
  19885. return new GLSLNodeBuilder( object, renderer );
  19886. }
  19887. // program
  19888. createProgram( program ) {
  19889. const gl = this.gl;
  19890. const { stage, code } = program;
  19891. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  19892. gl.shaderSource( shader, code );
  19893. gl.compileShader( shader );
  19894. this.set( program, {
  19895. shaderGPU: shader
  19896. } );
  19897. }
  19898. destroyProgram( /*program*/ ) {
  19899. console.warn( 'Abstract class.' );
  19900. }
  19901. createRenderPipeline( renderObject, promises ) {
  19902. const gl = this.gl;
  19903. const pipeline = renderObject.pipeline;
  19904. // Program
  19905. const { fragmentProgram, vertexProgram } = pipeline;
  19906. const programGPU = gl.createProgram();
  19907. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  19908. const vertexShader = this.get( vertexProgram ).shaderGPU;
  19909. gl.attachShader( programGPU, fragmentShader );
  19910. gl.attachShader( programGPU, vertexShader );
  19911. gl.linkProgram( programGPU );
  19912. this.set( pipeline, {
  19913. programGPU,
  19914. fragmentShader,
  19915. vertexShader
  19916. } );
  19917. if ( promises !== null && this.parallel ) {
  19918. const p = new Promise( ( resolve /*, reject*/ ) => {
  19919. const parallel = this.parallel;
  19920. const checkStatus = () => {
  19921. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  19922. this._completeCompile( renderObject, pipeline );
  19923. resolve();
  19924. } else {
  19925. requestAnimationFrame( checkStatus );
  19926. }
  19927. };
  19928. checkStatus();
  19929. } );
  19930. promises.push( p );
  19931. return;
  19932. }
  19933. this._completeCompile( renderObject, pipeline );
  19934. }
  19935. _handleSource( string, errorLine ) {
  19936. const lines = string.split( '\n' );
  19937. const lines2 = [];
  19938. const from = Math.max( errorLine - 6, 0 );
  19939. const to = Math.min( errorLine + 6, lines.length );
  19940. for ( let i = from; i < to; i ++ ) {
  19941. const line = i + 1;
  19942. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  19943. }
  19944. return lines2.join( '\n' );
  19945. }
  19946. _getShaderErrors( gl, shader, type ) {
  19947. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  19948. const errors = gl.getShaderInfoLog( shader ).trim();
  19949. if ( status && errors === '' ) return '';
  19950. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  19951. if ( errorMatches ) {
  19952. const errorLine = parseInt( errorMatches[ 1 ] );
  19953. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  19954. } else {
  19955. return errors;
  19956. }
  19957. }
  19958. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  19959. if ( this.renderer.debug.checkShaderErrors ) {
  19960. const gl = this.gl;
  19961. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  19962. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  19963. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  19964. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  19965. } else {
  19966. // default error reporting
  19967. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  19968. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  19969. console.error(
  19970. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  19971. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  19972. 'Program Info Log: ' + programLog + '\n' +
  19973. vertexErrors + '\n' +
  19974. fragmentErrors
  19975. );
  19976. }
  19977. } else if ( programLog !== '' ) {
  19978. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  19979. }
  19980. }
  19981. }
  19982. _completeCompile( renderObject, pipeline ) {
  19983. const { state, gl } = this;
  19984. const pipelineData = this.get( pipeline );
  19985. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  19986. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  19987. this._logProgramError( programGPU, fragmentShader, vertexShader );
  19988. }
  19989. state.useProgram( programGPU );
  19990. // Bindings
  19991. const bindings = renderObject.getBindings();
  19992. this._setupBindings( bindings, programGPU );
  19993. //
  19994. this.set( pipeline, {
  19995. programGPU
  19996. } );
  19997. }
  19998. createComputePipeline( computePipeline, bindings ) {
  19999. const { state, gl } = this;
  20000. // Program
  20001. const fragmentProgram = {
  20002. stage: 'fragment',
  20003. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  20004. };
  20005. this.createProgram( fragmentProgram );
  20006. const { computeProgram } = computePipeline;
  20007. const programGPU = gl.createProgram();
  20008. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  20009. const vertexShader = this.get( computeProgram ).shaderGPU;
  20010. const transforms = computeProgram.transforms;
  20011. const transformVaryingNames = [];
  20012. const transformAttributeNodes = [];
  20013. for ( let i = 0; i < transforms.length; i ++ ) {
  20014. const transform = transforms[ i ];
  20015. transformVaryingNames.push( transform.varyingName );
  20016. transformAttributeNodes.push( transform.attributeNode );
  20017. }
  20018. gl.attachShader( programGPU, fragmentShader );
  20019. gl.attachShader( programGPU, vertexShader );
  20020. gl.transformFeedbackVaryings(
  20021. programGPU,
  20022. transformVaryingNames,
  20023. gl.SEPARATE_ATTRIBS
  20024. );
  20025. gl.linkProgram( programGPU );
  20026. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  20027. this._logProgramError( programGPU, fragmentShader, vertexShader );
  20028. }
  20029. state.useProgram( programGPU );
  20030. // Bindings
  20031. this._setupBindings( bindings, programGPU );
  20032. const attributeNodes = computeProgram.attributes;
  20033. const attributes = [];
  20034. const transformBuffers = [];
  20035. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  20036. const attribute = attributeNodes[ i ].node.attribute;
  20037. attributes.push( attribute );
  20038. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  20039. }
  20040. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  20041. const attribute = transformAttributeNodes[ i ].attribute;
  20042. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  20043. const attributeData = this.get( attribute );
  20044. transformBuffers.push( attributeData );
  20045. }
  20046. //
  20047. this.set( computePipeline, {
  20048. programGPU,
  20049. transformBuffers,
  20050. attributes
  20051. } );
  20052. }
  20053. createBindings( bindGroup, bindings ) {
  20054. if ( this._knownBindings.has( bindings ) === false ) {
  20055. this._knownBindings.add( bindings );
  20056. let uniformBuffers = 0;
  20057. let textures = 0;
  20058. for ( const bindGroup of bindings ) {
  20059. this.set( bindGroup, {
  20060. textures: textures,
  20061. uniformBuffers: uniformBuffers
  20062. } );
  20063. for ( const binding of bindGroup.bindings ) {
  20064. if ( binding.isUniformBuffer ) uniformBuffers ++;
  20065. if ( binding.isSampledTexture ) textures ++;
  20066. }
  20067. }
  20068. }
  20069. this.updateBindings( bindGroup, bindings );
  20070. }
  20071. updateBindings( bindGroup /*, bindings*/ ) {
  20072. const { gl } = this;
  20073. const bindGroupData = this.get( bindGroup );
  20074. let i = bindGroupData.uniformBuffers;
  20075. let t = bindGroupData.textures;
  20076. for ( const binding of bindGroup.bindings ) {
  20077. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  20078. const data = binding.buffer;
  20079. const bufferGPU = gl.createBuffer();
  20080. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  20081. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  20082. this.set( binding, {
  20083. index: i ++,
  20084. bufferGPU
  20085. } );
  20086. } else if ( binding.isSampledTexture ) {
  20087. const { textureGPU, glTextureType } = this.get( binding.texture );
  20088. this.set( binding, {
  20089. index: t ++,
  20090. textureGPU,
  20091. glTextureType
  20092. } );
  20093. }
  20094. }
  20095. }
  20096. updateBinding( binding ) {
  20097. const gl = this.gl;
  20098. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  20099. const bindingData = this.get( binding );
  20100. const bufferGPU = bindingData.bufferGPU;
  20101. const data = binding.buffer;
  20102. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  20103. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  20104. }
  20105. }
  20106. // attributes
  20107. createIndexAttribute( attribute ) {
  20108. const gl = this.gl;
  20109. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  20110. }
  20111. createAttribute( attribute ) {
  20112. if ( this.has( attribute ) ) return;
  20113. const gl = this.gl;
  20114. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  20115. }
  20116. createStorageAttribute( attribute ) {
  20117. if ( this.has( attribute ) ) return;
  20118. const gl = this.gl;
  20119. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  20120. }
  20121. updateAttribute( attribute ) {
  20122. this.attributeUtils.updateAttribute( attribute );
  20123. }
  20124. destroyAttribute( attribute ) {
  20125. this.attributeUtils.destroyAttribute( attribute );
  20126. }
  20127. updateSize() {
  20128. //console.warn( 'Abstract class.' );
  20129. }
  20130. hasFeature( name ) {
  20131. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  20132. const extensions = this.extensions;
  20133. for ( let i = 0; i < keysMatching.length; i ++ ) {
  20134. if ( extensions.has( keysMatching[ i ] ) ) return true;
  20135. }
  20136. return false;
  20137. }
  20138. getMaxAnisotropy() {
  20139. return this.capabilities.getMaxAnisotropy();
  20140. }
  20141. copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level ) {
  20142. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  20143. }
  20144. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  20145. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  20146. }
  20147. _setFramebuffer( descriptor ) {
  20148. const { gl, state } = this;
  20149. let currentFrameBuffer = null;
  20150. if ( descriptor.textures !== null ) {
  20151. const renderTarget = descriptor.renderTarget;
  20152. const renderTargetContextData = this.get( renderTarget );
  20153. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  20154. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  20155. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  20156. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  20157. const cacheKey = getCacheKey( descriptor );
  20158. let fb;
  20159. if ( isCube ) {
  20160. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  20161. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  20162. } else {
  20163. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  20164. fb = renderTargetContextData.framebuffers[ cacheKey ];
  20165. }
  20166. if ( fb === undefined ) {
  20167. fb = gl.createFramebuffer();
  20168. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  20169. const textures = descriptor.textures;
  20170. if ( isCube ) {
  20171. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  20172. const { textureGPU } = this.get( textures[ 0 ] );
  20173. const cubeFace = this.renderer._activeCubeFace;
  20174. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  20175. } else {
  20176. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  20177. for ( let i = 0; i < textures.length; i ++ ) {
  20178. const texture = textures[ i ];
  20179. const textureData = this.get( texture );
  20180. textureData.renderTarget = descriptor.renderTarget;
  20181. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  20182. const attachment = gl.COLOR_ATTACHMENT0 + i;
  20183. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  20184. }
  20185. state.drawBuffers( descriptor, fb );
  20186. }
  20187. if ( descriptor.depthTexture !== null ) {
  20188. const textureData = this.get( descriptor.depthTexture );
  20189. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  20190. textureData.renderTarget = descriptor.renderTarget;
  20191. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  20192. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  20193. }
  20194. }
  20195. if ( samples > 0 ) {
  20196. if ( msaaFb === undefined ) {
  20197. const invalidationArray = [];
  20198. msaaFb = gl.createFramebuffer();
  20199. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  20200. const msaaRenderbuffers = [];
  20201. const textures = descriptor.textures;
  20202. for ( let i = 0; i < textures.length; i ++ ) {
  20203. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  20204. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  20205. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  20206. if ( depthBuffer ) {
  20207. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  20208. invalidationArray.push( depthStyle );
  20209. }
  20210. const texture = descriptor.textures[ i ];
  20211. const textureData = this.get( texture );
  20212. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  20213. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  20214. }
  20215. renderTargetContextData.msaaFrameBuffer = msaaFb;
  20216. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  20217. if ( depthRenderbuffer === undefined ) {
  20218. depthRenderbuffer = gl.createRenderbuffer();
  20219. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor );
  20220. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  20221. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  20222. invalidationArray.push( depthStyle );
  20223. }
  20224. renderTargetContextData.invalidationArray = invalidationArray;
  20225. }
  20226. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  20227. } else {
  20228. currentFrameBuffer = fb;
  20229. }
  20230. }
  20231. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  20232. }
  20233. _getVaoKey( index, attributes ) {
  20234. let key = [];
  20235. if ( index !== null ) {
  20236. const indexData = this.get( index );
  20237. key += ':' + indexData.id;
  20238. }
  20239. for ( let i = 0; i < attributes.length; i ++ ) {
  20240. const attributeData = this.get( attributes[ i ] );
  20241. key += ':' + attributeData.id;
  20242. }
  20243. return key;
  20244. }
  20245. _createVao( index, attributes ) {
  20246. const { gl } = this;
  20247. const vaoGPU = gl.createVertexArray();
  20248. let key = '';
  20249. let staticVao = true;
  20250. gl.bindVertexArray( vaoGPU );
  20251. if ( index !== null ) {
  20252. const indexData = this.get( index );
  20253. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  20254. key += ':' + indexData.id;
  20255. }
  20256. for ( let i = 0; i < attributes.length; i ++ ) {
  20257. const attribute = attributes[ i ];
  20258. const attributeData = this.get( attribute );
  20259. key += ':' + attributeData.id;
  20260. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  20261. gl.enableVertexAttribArray( i );
  20262. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  20263. let stride, offset;
  20264. if ( attribute.isInterleavedBufferAttribute === true ) {
  20265. stride = attribute.data.stride * attributeData.bytesPerElement;
  20266. offset = attribute.offset * attributeData.bytesPerElement;
  20267. } else {
  20268. stride = 0;
  20269. offset = 0;
  20270. }
  20271. if ( attributeData.isInteger ) {
  20272. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  20273. } else {
  20274. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  20275. }
  20276. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  20277. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  20278. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  20279. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  20280. }
  20281. }
  20282. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  20283. this.vaoCache[ key ] = vaoGPU;
  20284. return { vaoGPU, staticVao };
  20285. }
  20286. _getTransformFeedback( transformBuffers ) {
  20287. let key = '';
  20288. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  20289. key += ':' + transformBuffers[ i ].id;
  20290. }
  20291. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  20292. if ( transformFeedbackGPU !== undefined ) {
  20293. return transformFeedbackGPU;
  20294. }
  20295. const { gl } = this;
  20296. transformFeedbackGPU = gl.createTransformFeedback();
  20297. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  20298. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  20299. const attributeData = transformBuffers[ i ];
  20300. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  20301. }
  20302. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  20303. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  20304. return transformFeedbackGPU;
  20305. }
  20306. _setupBindings( bindings, programGPU ) {
  20307. const gl = this.gl;
  20308. for ( const bindGroup of bindings ) {
  20309. for ( const binding of bindGroup.bindings ) {
  20310. const bindingData = this.get( binding );
  20311. const index = bindingData.index;
  20312. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  20313. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  20314. gl.uniformBlockBinding( programGPU, location, index );
  20315. } else if ( binding.isSampledTexture ) {
  20316. const location = gl.getUniformLocation( programGPU, binding.name );
  20317. gl.uniform1i( location, index );
  20318. }
  20319. }
  20320. }
  20321. }
  20322. _bindUniforms( bindings ) {
  20323. const { gl, state } = this;
  20324. for ( const bindGroup of bindings ) {
  20325. for ( const binding of bindGroup.bindings ) {
  20326. const bindingData = this.get( binding );
  20327. const index = bindingData.index;
  20328. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  20329. // TODO USE bindBufferRange to group multiple uniform buffers
  20330. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  20331. } else if ( binding.isSampledTexture ) {
  20332. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  20333. }
  20334. }
  20335. }
  20336. }
  20337. dispose() {
  20338. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  20339. }
  20340. }
  20341. class Sampler extends Binding {
  20342. constructor( name, texture ) {
  20343. super( name );
  20344. this.texture = texture;
  20345. this.version = texture ? texture.version : 0;
  20346. this.isSampler = true;
  20347. }
  20348. }
  20349. class NodeSampler extends Sampler {
  20350. constructor( name, textureNode, groupNode ) {
  20351. super( name, textureNode ? textureNode.value : null );
  20352. this.textureNode = textureNode;
  20353. this.groupNode = groupNode;
  20354. }
  20355. update() {
  20356. this.texture = this.textureNode.value;
  20357. }
  20358. }
  20359. class StorageBuffer extends Buffer {
  20360. constructor( name, attribute ) {
  20361. super( name, attribute ? attribute.array : null );
  20362. this.attribute = attribute;
  20363. this.isStorageBuffer = true;
  20364. }
  20365. }
  20366. let _id = 0;
  20367. class NodeStorageBuffer extends StorageBuffer {
  20368. constructor( nodeUniform, groupNode ) {
  20369. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  20370. this.nodeUniform = nodeUniform;
  20371. this.access = nodeUniform ? nodeUniform.access : GPUBufferBindingType.Storage;
  20372. this.groupNode = groupNode;
  20373. }
  20374. get buffer() {
  20375. return this.nodeUniform.value;
  20376. }
  20377. }
  20378. class WebGPUTexturePassUtils extends DataMap {
  20379. constructor( device ) {
  20380. super();
  20381. this.device = device;
  20382. const mipmapVertexSource = `
  20383. struct VarysStruct {
  20384. @builtin( position ) Position: vec4<f32>,
  20385. @location( 0 ) vTex : vec2<f32>
  20386. };
  20387. @vertex
  20388. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  20389. var Varys : VarysStruct;
  20390. var pos = array< vec2<f32>, 4 >(
  20391. vec2<f32>( -1.0, 1.0 ),
  20392. vec2<f32>( 1.0, 1.0 ),
  20393. vec2<f32>( -1.0, -1.0 ),
  20394. vec2<f32>( 1.0, -1.0 )
  20395. );
  20396. var tex = array< vec2<f32>, 4 >(
  20397. vec2<f32>( 0.0, 0.0 ),
  20398. vec2<f32>( 1.0, 0.0 ),
  20399. vec2<f32>( 0.0, 1.0 ),
  20400. vec2<f32>( 1.0, 1.0 )
  20401. );
  20402. Varys.vTex = tex[ vertexIndex ];
  20403. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  20404. return Varys;
  20405. }
  20406. `;
  20407. const mipmapFragmentSource = `
  20408. @group( 0 ) @binding( 0 )
  20409. var imgSampler : sampler;
  20410. @group( 0 ) @binding( 1 )
  20411. var img : texture_2d<f32>;
  20412. @fragment
  20413. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  20414. return textureSample( img, imgSampler, vTex );
  20415. }
  20416. `;
  20417. const flipYFragmentSource = `
  20418. @group( 0 ) @binding( 0 )
  20419. var imgSampler : sampler;
  20420. @group( 0 ) @binding( 1 )
  20421. var img : texture_2d<f32>;
  20422. @fragment
  20423. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  20424. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  20425. }
  20426. `;
  20427. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  20428. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  20429. // We'll need a new pipeline for every texture format used.
  20430. this.transferPipelines = {};
  20431. this.flipYPipelines = {};
  20432. this.mipmapVertexShaderModule = device.createShaderModule( {
  20433. label: 'mipmapVertex',
  20434. code: mipmapVertexSource
  20435. } );
  20436. this.mipmapFragmentShaderModule = device.createShaderModule( {
  20437. label: 'mipmapFragment',
  20438. code: mipmapFragmentSource
  20439. } );
  20440. this.flipYFragmentShaderModule = device.createShaderModule( {
  20441. label: 'flipYFragment',
  20442. code: flipYFragmentSource
  20443. } );
  20444. }
  20445. getTransferPipeline( format ) {
  20446. let pipeline = this.transferPipelines[ format ];
  20447. if ( pipeline === undefined ) {
  20448. pipeline = this.device.createRenderPipeline( {
  20449. label: `mipmap-${ format }`,
  20450. vertex: {
  20451. module: this.mipmapVertexShaderModule,
  20452. entryPoint: 'main'
  20453. },
  20454. fragment: {
  20455. module: this.mipmapFragmentShaderModule,
  20456. entryPoint: 'main',
  20457. targets: [ { format } ]
  20458. },
  20459. primitive: {
  20460. topology: GPUPrimitiveTopology.TriangleStrip,
  20461. stripIndexFormat: GPUIndexFormat.Uint32
  20462. },
  20463. layout: 'auto'
  20464. } );
  20465. this.transferPipelines[ format ] = pipeline;
  20466. }
  20467. return pipeline;
  20468. }
  20469. getFlipYPipeline( format ) {
  20470. let pipeline = this.flipYPipelines[ format ];
  20471. if ( pipeline === undefined ) {
  20472. pipeline = this.device.createRenderPipeline( {
  20473. label: `flipY-${ format }`,
  20474. vertex: {
  20475. module: this.mipmapVertexShaderModule,
  20476. entryPoint: 'main'
  20477. },
  20478. fragment: {
  20479. module: this.flipYFragmentShaderModule,
  20480. entryPoint: 'main',
  20481. targets: [ { format } ]
  20482. },
  20483. primitive: {
  20484. topology: GPUPrimitiveTopology.TriangleStrip,
  20485. stripIndexFormat: GPUIndexFormat.Uint32
  20486. },
  20487. layout: 'auto'
  20488. } );
  20489. this.flipYPipelines[ format ] = pipeline;
  20490. }
  20491. return pipeline;
  20492. }
  20493. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  20494. const format = textureGPUDescriptor.format;
  20495. const { width, height } = textureGPUDescriptor.size;
  20496. const transferPipeline = this.getTransferPipeline( format );
  20497. const flipYPipeline = this.getFlipYPipeline( format );
  20498. const tempTexture = this.device.createTexture( {
  20499. size: { width, height, depthOrArrayLayers: 1 },
  20500. format,
  20501. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  20502. } );
  20503. const srcView = textureGPU.createView( {
  20504. baseMipLevel: 0,
  20505. mipLevelCount: 1,
  20506. dimension: GPUTextureViewDimension.TwoD,
  20507. baseArrayLayer
  20508. } );
  20509. const dstView = tempTexture.createView( {
  20510. baseMipLevel: 0,
  20511. mipLevelCount: 1,
  20512. dimension: GPUTextureViewDimension.TwoD,
  20513. baseArrayLayer: 0
  20514. } );
  20515. const commandEncoder = this.device.createCommandEncoder( {} );
  20516. const pass = ( pipeline, sourceView, destinationView ) => {
  20517. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  20518. const bindGroup = this.device.createBindGroup( {
  20519. layout: bindGroupLayout,
  20520. entries: [ {
  20521. binding: 0,
  20522. resource: this.flipYSampler
  20523. }, {
  20524. binding: 1,
  20525. resource: sourceView
  20526. } ]
  20527. } );
  20528. const passEncoder = commandEncoder.beginRenderPass( {
  20529. colorAttachments: [ {
  20530. view: destinationView,
  20531. loadOp: GPULoadOp.Clear,
  20532. storeOp: GPUStoreOp.Store,
  20533. clearValue: [ 0, 0, 0, 0 ]
  20534. } ]
  20535. } );
  20536. passEncoder.setPipeline( pipeline );
  20537. passEncoder.setBindGroup( 0, bindGroup );
  20538. passEncoder.draw( 4, 1, 0, 0 );
  20539. passEncoder.end();
  20540. };
  20541. pass( transferPipeline, srcView, dstView );
  20542. pass( flipYPipeline, dstView, srcView );
  20543. this.device.queue.submit( [ commandEncoder.finish() ] );
  20544. tempTexture.destroy();
  20545. }
  20546. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  20547. const textureData = this.get( textureGPU );
  20548. if ( textureData.useCount === undefined ) {
  20549. textureData.useCount = 0;
  20550. textureData.layers = [];
  20551. }
  20552. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  20553. const commandEncoder = this.device.createCommandEncoder( {} );
  20554. this._mipmapRunBundles( commandEncoder, passes );
  20555. this.device.queue.submit( [ commandEncoder.finish() ] );
  20556. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  20557. textureData.useCount ++;
  20558. }
  20559. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  20560. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  20561. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  20562. let srcView = textureGPU.createView( {
  20563. baseMipLevel: 0,
  20564. mipLevelCount: 1,
  20565. dimension: GPUTextureViewDimension.TwoD,
  20566. baseArrayLayer
  20567. } );
  20568. const passes = [];
  20569. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  20570. const bindGroup = this.device.createBindGroup( {
  20571. layout: bindGroupLayout,
  20572. entries: [ {
  20573. binding: 0,
  20574. resource: this.mipmapSampler
  20575. }, {
  20576. binding: 1,
  20577. resource: srcView
  20578. } ]
  20579. } );
  20580. const dstView = textureGPU.createView( {
  20581. baseMipLevel: i,
  20582. mipLevelCount: 1,
  20583. dimension: GPUTextureViewDimension.TwoD,
  20584. baseArrayLayer
  20585. } );
  20586. const passDescriptor = {
  20587. colorAttachments: [ {
  20588. view: dstView,
  20589. loadOp: GPULoadOp.Clear,
  20590. storeOp: GPUStoreOp.Store,
  20591. clearValue: [ 0, 0, 0, 0 ]
  20592. } ]
  20593. };
  20594. const passEncoder = this.device.createRenderBundleEncoder( {
  20595. colorFormats: [ textureGPUDescriptor.format ]
  20596. } );
  20597. passEncoder.setPipeline( pipeline );
  20598. passEncoder.setBindGroup( 0, bindGroup );
  20599. passEncoder.draw( 4, 1, 0, 0 );
  20600. passes.push( {
  20601. renderBundles: [ passEncoder.finish() ],
  20602. passDescriptor
  20603. } );
  20604. srcView = dstView;
  20605. }
  20606. return passes;
  20607. }
  20608. _mipmapRunBundles( commandEncoder, passes ) {
  20609. const levels = passes.length;
  20610. for ( let i = 0; i < levels; i ++ ) {
  20611. const pass = passes[ i ];
  20612. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  20613. passEncoder.executeBundles( pass.renderBundles );
  20614. passEncoder.end();
  20615. }
  20616. }
  20617. }
  20618. const _compareToWebGPU = {
  20619. [ NeverCompare ]: 'never',
  20620. [ LessCompare ]: 'less',
  20621. [ EqualCompare ]: 'equal',
  20622. [ LessEqualCompare ]: 'less-equal',
  20623. [ GreaterCompare ]: 'greater',
  20624. [ GreaterEqualCompare ]: 'greater-equal',
  20625. [ AlwaysCompare ]: 'always',
  20626. [ NotEqualCompare ]: 'not-equal'
  20627. };
  20628. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  20629. class WebGPUTextureUtils {
  20630. constructor( backend ) {
  20631. this.backend = backend;
  20632. this._passUtils = null;
  20633. this.defaultTexture = {};
  20634. this.defaultCubeTexture = {};
  20635. this.defaultVideoFrame = null;
  20636. this.colorBuffer = null;
  20637. this.depthTexture = new DepthTexture();
  20638. this.depthTexture.name = 'depthBuffer';
  20639. }
  20640. createSampler( texture ) {
  20641. const backend = this.backend;
  20642. const device = backend.device;
  20643. const textureGPU = backend.get( texture );
  20644. const samplerDescriptorGPU = {
  20645. addressModeU: this._convertAddressMode( texture.wrapS ),
  20646. addressModeV: this._convertAddressMode( texture.wrapT ),
  20647. addressModeW: this._convertAddressMode( texture.wrapR ),
  20648. magFilter: this._convertFilterMode( texture.magFilter ),
  20649. minFilter: this._convertFilterMode( texture.minFilter ),
  20650. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  20651. maxAnisotropy: 1
  20652. };
  20653. // anisotropy can only be used when all filter modes are set to linear.
  20654. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  20655. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  20656. }
  20657. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  20658. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  20659. }
  20660. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  20661. }
  20662. createDefaultTexture( texture ) {
  20663. let textureGPU;
  20664. const format = getFormat( texture );
  20665. if ( texture.isCubeTexture ) {
  20666. textureGPU = this._getDefaultCubeTextureGPU( format );
  20667. } else if ( texture.isVideoTexture ) {
  20668. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  20669. } else {
  20670. textureGPU = this._getDefaultTextureGPU( format );
  20671. }
  20672. this.backend.get( texture ).texture = textureGPU;
  20673. }
  20674. createTexture( texture, options = {} ) {
  20675. const backend = this.backend;
  20676. const textureData = backend.get( texture );
  20677. if ( textureData.initialized ) {
  20678. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  20679. }
  20680. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  20681. if ( options.levels === undefined ) options.levels = 1;
  20682. if ( options.depth === undefined ) options.depth = 1;
  20683. const { width, height, depth, levels } = options;
  20684. if ( texture.isFramebufferTexture ) {
  20685. if ( options.renderTarget ) {
  20686. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  20687. } else {
  20688. options.format = this.backend.utils.getPreferredCanvasFormat();
  20689. }
  20690. }
  20691. const dimension = this._getDimension( texture );
  20692. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  20693. textureData.format = format;
  20694. let sampleCount = options.sampleCount !== undefined ? options.sampleCount : 1;
  20695. sampleCount = backend.utils.getSampleCount( sampleCount );
  20696. const primarySampleCount = texture.isRenderTargetTexture && ! texture.isMultisampleRenderTargetTexture ? 1 : sampleCount;
  20697. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  20698. if ( texture.isStorageTexture === true ) {
  20699. usage |= GPUTextureUsage.STORAGE_BINDING;
  20700. }
  20701. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  20702. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  20703. }
  20704. const textureDescriptorGPU = {
  20705. label: texture.name,
  20706. size: {
  20707. width: width,
  20708. height: height,
  20709. depthOrArrayLayers: depth,
  20710. },
  20711. mipLevelCount: levels,
  20712. sampleCount: primarySampleCount,
  20713. dimension: dimension,
  20714. format: format,
  20715. usage: usage
  20716. };
  20717. // texture creation
  20718. if ( texture.isVideoTexture ) {
  20719. const video = texture.source.data;
  20720. const videoFrame = new VideoFrame( video );
  20721. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  20722. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  20723. videoFrame.close();
  20724. textureData.externalTexture = video;
  20725. } else {
  20726. if ( format === undefined ) {
  20727. console.warn( 'WebGPURenderer: Texture format not supported.' );
  20728. return this.createDefaultTexture( texture );
  20729. }
  20730. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  20731. }
  20732. if ( texture.isRenderTargetTexture && sampleCount > 1 && ! texture.isMultisampleRenderTargetTexture ) {
  20733. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  20734. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  20735. msaaTextureDescriptorGPU.sampleCount = sampleCount;
  20736. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  20737. }
  20738. textureData.initialized = true;
  20739. textureData.textureDescriptorGPU = textureDescriptorGPU;
  20740. }
  20741. destroyTexture( texture ) {
  20742. const backend = this.backend;
  20743. const textureData = backend.get( texture );
  20744. textureData.texture.destroy();
  20745. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  20746. backend.delete( texture );
  20747. }
  20748. destroySampler( texture ) {
  20749. const backend = this.backend;
  20750. const textureData = backend.get( texture );
  20751. delete textureData.sampler;
  20752. }
  20753. generateMipmaps( texture ) {
  20754. const textureData = this.backend.get( texture );
  20755. if ( texture.isCubeTexture ) {
  20756. for ( let i = 0; i < 6; i ++ ) {
  20757. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  20758. }
  20759. } else {
  20760. const depth = texture.image.depth || 1;
  20761. for ( let i = 0; i < depth; i ++ ) {
  20762. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  20763. }
  20764. }
  20765. }
  20766. getColorBuffer() {
  20767. if ( this.colorBuffer ) this.colorBuffer.destroy();
  20768. const backend = this.backend;
  20769. const { width, height } = backend.getDrawingBufferSize();
  20770. this.colorBuffer = backend.device.createTexture( {
  20771. label: 'colorBuffer',
  20772. size: {
  20773. width: width,
  20774. height: height,
  20775. depthOrArrayLayers: 1
  20776. },
  20777. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  20778. format: backend.utils.getPreferredCanvasFormat(),
  20779. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  20780. } );
  20781. return this.colorBuffer;
  20782. }
  20783. getDepthBuffer( depth = true, stencil = false ) {
  20784. const backend = this.backend;
  20785. const { width, height } = backend.getDrawingBufferSize();
  20786. const depthTexture = this.depthTexture;
  20787. const depthTextureGPU = backend.get( depthTexture ).texture;
  20788. let format, type;
  20789. if ( stencil ) {
  20790. format = DepthStencilFormat;
  20791. type = UnsignedInt248Type;
  20792. } else if ( depth ) {
  20793. format = DepthFormat;
  20794. type = UnsignedIntType;
  20795. }
  20796. if ( depthTextureGPU !== undefined ) {
  20797. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  20798. return depthTextureGPU;
  20799. }
  20800. this.destroyTexture( depthTexture );
  20801. }
  20802. depthTexture.name = 'depthBuffer';
  20803. depthTexture.format = format;
  20804. depthTexture.type = type;
  20805. depthTexture.image.width = width;
  20806. depthTexture.image.height = height;
  20807. this.createTexture( depthTexture, { sampleCount: backend.utils.getSampleCount( backend.renderer.samples ), width, height } );
  20808. return backend.get( depthTexture ).texture;
  20809. }
  20810. updateTexture( texture, options ) {
  20811. const textureData = this.backend.get( texture );
  20812. const { textureDescriptorGPU } = textureData;
  20813. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  20814. return;
  20815. // transfer texture data
  20816. if ( texture.isDataTexture ) {
  20817. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  20818. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  20819. for ( let i = 0; i < options.image.depth; i ++ ) {
  20820. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  20821. }
  20822. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  20823. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  20824. } else if ( texture.isCubeTexture ) {
  20825. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  20826. } else if ( texture.isVideoTexture ) {
  20827. const video = texture.source.data;
  20828. textureData.externalTexture = video;
  20829. } else {
  20830. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  20831. }
  20832. //
  20833. textureData.version = texture.version;
  20834. if ( texture.onUpdate ) texture.onUpdate( texture );
  20835. }
  20836. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  20837. const device = this.backend.device;
  20838. const textureData = this.backend.get( texture );
  20839. const textureGPU = textureData.texture;
  20840. const format = textureData.textureDescriptorGPU.format;
  20841. const bytesPerTexel = this._getBytesPerTexel( format );
  20842. let bytesPerRow = width * bytesPerTexel;
  20843. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  20844. const readBuffer = device.createBuffer(
  20845. {
  20846. size: width * height * bytesPerTexel,
  20847. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  20848. }
  20849. );
  20850. const encoder = device.createCommandEncoder();
  20851. encoder.copyTextureToBuffer(
  20852. {
  20853. texture: textureGPU,
  20854. origin: { x, y, z: faceIndex },
  20855. },
  20856. {
  20857. buffer: readBuffer,
  20858. bytesPerRow: bytesPerRow
  20859. },
  20860. {
  20861. width: width,
  20862. height: height
  20863. }
  20864. );
  20865. const typedArrayType = this._getTypedArrayType( format );
  20866. device.queue.submit( [ encoder.finish() ] );
  20867. await readBuffer.mapAsync( GPUMapMode.READ );
  20868. const buffer = readBuffer.getMappedRange();
  20869. return new typedArrayType( buffer );
  20870. }
  20871. _isEnvironmentTexture( texture ) {
  20872. const mapping = texture.mapping;
  20873. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  20874. }
  20875. _getDefaultTextureGPU( format ) {
  20876. let defaultTexture = this.defaultTexture[ format ];
  20877. if ( defaultTexture === undefined ) {
  20878. const texture = new Texture();
  20879. texture.minFilter = NearestFilter;
  20880. texture.magFilter = NearestFilter;
  20881. this.createTexture( texture, { width: 1, height: 1, format } );
  20882. this.defaultTexture[ format ] = defaultTexture = texture;
  20883. }
  20884. return this.backend.get( defaultTexture ).texture;
  20885. }
  20886. _getDefaultCubeTextureGPU( format ) {
  20887. let defaultCubeTexture = this.defaultTexture[ format ];
  20888. if ( defaultCubeTexture === undefined ) {
  20889. const texture = new CubeTexture();
  20890. texture.minFilter = NearestFilter;
  20891. texture.magFilter = NearestFilter;
  20892. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  20893. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  20894. }
  20895. return this.backend.get( defaultCubeTexture ).texture;
  20896. }
  20897. _getDefaultVideoFrame() {
  20898. let defaultVideoFrame = this.defaultVideoFrame;
  20899. if ( defaultVideoFrame === null ) {
  20900. const init = {
  20901. timestamp: 0,
  20902. codedWidth: 1,
  20903. codedHeight: 1,
  20904. format: 'RGBA',
  20905. };
  20906. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  20907. }
  20908. return defaultVideoFrame;
  20909. }
  20910. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  20911. for ( let i = 0; i < 6; i ++ ) {
  20912. const image = images[ i ];
  20913. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  20914. if ( image.isDataTexture ) {
  20915. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  20916. } else {
  20917. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  20918. }
  20919. }
  20920. }
  20921. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  20922. const device = this.backend.device;
  20923. device.queue.copyExternalImageToTexture(
  20924. {
  20925. source: image
  20926. }, {
  20927. texture: textureGPU,
  20928. mipLevel: 0,
  20929. origin: { x: 0, y: 0, z: originDepth }
  20930. }, {
  20931. width: image.width,
  20932. height: image.height,
  20933. depthOrArrayLayers: 1
  20934. }
  20935. );
  20936. if ( flipY === true ) {
  20937. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  20938. }
  20939. }
  20940. _getPassUtils() {
  20941. let passUtils = this._passUtils;
  20942. if ( passUtils === null ) {
  20943. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  20944. }
  20945. return passUtils;
  20946. }
  20947. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  20948. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  20949. }
  20950. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  20951. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  20952. }
  20953. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  20954. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  20955. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  20956. const device = this.backend.device;
  20957. const data = image.data;
  20958. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  20959. const bytesPerRow = image.width * bytesPerTexel;
  20960. device.queue.writeTexture(
  20961. {
  20962. texture: textureGPU,
  20963. mipLevel: 0,
  20964. origin: { x: 0, y: 0, z: originDepth }
  20965. },
  20966. data,
  20967. {
  20968. offset: image.width * image.height * bytesPerTexel * depth,
  20969. bytesPerRow
  20970. },
  20971. {
  20972. width: image.width,
  20973. height: image.height,
  20974. depthOrArrayLayers: 1
  20975. } );
  20976. if ( flipY === true ) {
  20977. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  20978. }
  20979. }
  20980. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  20981. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  20982. const device = this.backend.device;
  20983. const blockData = this._getBlockData( textureDescriptorGPU.format );
  20984. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  20985. for ( let i = 0; i < mipmaps.length; i ++ ) {
  20986. const mipmap = mipmaps[ i ];
  20987. const width = mipmap.width;
  20988. const height = mipmap.height;
  20989. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  20990. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  20991. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  20992. for ( let j = 0; j < depth; j ++ ) {
  20993. device.queue.writeTexture(
  20994. {
  20995. texture: textureGPU,
  20996. mipLevel: i,
  20997. origin: { x: 0, y: 0, z: j }
  20998. },
  20999. mipmap.data,
  21000. {
  21001. offset: j * bytesPerImage,
  21002. bytesPerRow,
  21003. rowsPerImage: Math.ceil( height / blockData.height )
  21004. },
  21005. {
  21006. width: Math.ceil( width / blockData.width ) * blockData.width,
  21007. height: Math.ceil( height / blockData.height ) * blockData.height,
  21008. depthOrArrayLayers: 1
  21009. }
  21010. );
  21011. }
  21012. }
  21013. }
  21014. _getBlockData( format ) {
  21015. // this method is only relevant for compressed texture formats
  21016. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  21017. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  21018. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  21019. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  21020. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  21021. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  21022. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  21023. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  21024. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  21025. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  21026. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  21027. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  21028. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  21029. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  21030. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  21031. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  21032. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  21033. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  21034. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  21035. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  21036. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  21037. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  21038. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  21039. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  21040. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  21041. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  21042. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  21043. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  21044. }
  21045. _convertAddressMode( value ) {
  21046. let addressMode = GPUAddressMode.ClampToEdge;
  21047. if ( value === RepeatWrapping ) {
  21048. addressMode = GPUAddressMode.Repeat;
  21049. } else if ( value === MirroredRepeatWrapping ) {
  21050. addressMode = GPUAddressMode.MirrorRepeat;
  21051. }
  21052. return addressMode;
  21053. }
  21054. _convertFilterMode( value ) {
  21055. let filterMode = GPUFilterMode.Linear;
  21056. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  21057. filterMode = GPUFilterMode.Nearest;
  21058. }
  21059. return filterMode;
  21060. }
  21061. _getBytesPerTexel( format ) {
  21062. // 8-bit formats
  21063. if ( format === GPUTextureFormat.R8Unorm ||
  21064. format === GPUTextureFormat.R8Snorm ||
  21065. format === GPUTextureFormat.R8Uint ||
  21066. format === GPUTextureFormat.R8Sint ) return 1;
  21067. // 16-bit formats
  21068. if ( format === GPUTextureFormat.R16Uint ||
  21069. format === GPUTextureFormat.R16Sint ||
  21070. format === GPUTextureFormat.R16Float ||
  21071. format === GPUTextureFormat.RG8Unorm ||
  21072. format === GPUTextureFormat.RG8Snorm ||
  21073. format === GPUTextureFormat.RG8Uint ||
  21074. format === GPUTextureFormat.RG8Sint ) return 2;
  21075. // 32-bit formats
  21076. if ( format === GPUTextureFormat.R32Uint ||
  21077. format === GPUTextureFormat.R32Sint ||
  21078. format === GPUTextureFormat.R32Float ||
  21079. format === GPUTextureFormat.RG16Uint ||
  21080. format === GPUTextureFormat.RG16Sint ||
  21081. format === GPUTextureFormat.RG16Float ||
  21082. format === GPUTextureFormat.RGBA8Unorm ||
  21083. format === GPUTextureFormat.RGBA8UnormSRGB ||
  21084. format === GPUTextureFormat.RGBA8Snorm ||
  21085. format === GPUTextureFormat.RGBA8Uint ||
  21086. format === GPUTextureFormat.RGBA8Sint ||
  21087. format === GPUTextureFormat.BGRA8Unorm ||
  21088. format === GPUTextureFormat.BGRA8UnormSRGB ||
  21089. // Packed 32-bit formats
  21090. format === GPUTextureFormat.RGB9E5UFloat ||
  21091. format === GPUTextureFormat.RGB10A2Unorm ||
  21092. format === GPUTextureFormat.RG11B10UFloat ||
  21093. format === GPUTextureFormat.Depth32Float ||
  21094. format === GPUTextureFormat.Depth24Plus ||
  21095. format === GPUTextureFormat.Depth24PlusStencil8 ||
  21096. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  21097. // 64-bit formats
  21098. if ( format === GPUTextureFormat.RG32Uint ||
  21099. format === GPUTextureFormat.RG32Sint ||
  21100. format === GPUTextureFormat.RG32Float ||
  21101. format === GPUTextureFormat.RGBA16Uint ||
  21102. format === GPUTextureFormat.RGBA16Sint ||
  21103. format === GPUTextureFormat.RGBA16Float ) return 8;
  21104. // 128-bit formats
  21105. if ( format === GPUTextureFormat.RGBA32Uint ||
  21106. format === GPUTextureFormat.RGBA32Sint ||
  21107. format === GPUTextureFormat.RGBA32Float ) return 16;
  21108. }
  21109. _getTypedArrayType( format ) {
  21110. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  21111. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  21112. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  21113. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  21114. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  21115. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  21116. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  21117. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  21118. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  21119. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  21120. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  21121. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  21122. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  21123. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  21124. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  21125. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  21126. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  21127. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  21128. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  21129. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  21130. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  21131. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  21132. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  21133. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  21134. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  21135. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  21136. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  21137. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  21138. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  21139. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  21140. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  21141. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  21142. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  21143. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  21144. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  21145. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  21146. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  21147. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  21148. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  21149. }
  21150. _getDimension( texture ) {
  21151. let dimension;
  21152. if ( texture.isData3DTexture ) {
  21153. dimension = GPUTextureDimension.ThreeD;
  21154. } else {
  21155. dimension = GPUTextureDimension.TwoD;
  21156. }
  21157. return dimension;
  21158. }
  21159. }
  21160. function getFormat( texture, device = null ) {
  21161. const format = texture.format;
  21162. const type = texture.type;
  21163. const colorSpace = texture.colorSpace;
  21164. let formatGPU;
  21165. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  21166. switch ( format ) {
  21167. case RGBA_S3TC_DXT1_Format:
  21168. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  21169. break;
  21170. case RGBA_S3TC_DXT3_Format:
  21171. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  21172. break;
  21173. case RGBA_S3TC_DXT5_Format:
  21174. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  21175. break;
  21176. case RGB_ETC2_Format:
  21177. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  21178. break;
  21179. case RGBA_ETC2_EAC_Format:
  21180. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  21181. break;
  21182. case RGBA_ASTC_4x4_Format:
  21183. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  21184. break;
  21185. case RGBA_ASTC_5x4_Format:
  21186. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  21187. break;
  21188. case RGBA_ASTC_5x5_Format:
  21189. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  21190. break;
  21191. case RGBA_ASTC_6x5_Format:
  21192. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  21193. break;
  21194. case RGBA_ASTC_6x6_Format:
  21195. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  21196. break;
  21197. case RGBA_ASTC_8x5_Format:
  21198. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  21199. break;
  21200. case RGBA_ASTC_8x6_Format:
  21201. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  21202. break;
  21203. case RGBA_ASTC_8x8_Format:
  21204. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  21205. break;
  21206. case RGBA_ASTC_10x5_Format:
  21207. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  21208. break;
  21209. case RGBA_ASTC_10x6_Format:
  21210. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  21211. break;
  21212. case RGBA_ASTC_10x8_Format:
  21213. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  21214. break;
  21215. case RGBA_ASTC_10x10_Format:
  21216. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  21217. break;
  21218. case RGBA_ASTC_12x10_Format:
  21219. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  21220. break;
  21221. case RGBA_ASTC_12x12_Format:
  21222. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  21223. break;
  21224. case RGBAFormat:
  21225. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  21226. break;
  21227. default:
  21228. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  21229. }
  21230. } else {
  21231. switch ( format ) {
  21232. case RGBAFormat:
  21233. switch ( type ) {
  21234. case ByteType:
  21235. formatGPU = GPUTextureFormat.RGBA8Snorm;
  21236. break;
  21237. case ShortType:
  21238. formatGPU = GPUTextureFormat.RGBA16Sint;
  21239. break;
  21240. case UnsignedShortType:
  21241. formatGPU = GPUTextureFormat.RGBA16Uint;
  21242. break;
  21243. case UnsignedIntType:
  21244. formatGPU = GPUTextureFormat.RGBA32Uint;
  21245. break;
  21246. case IntType:
  21247. formatGPU = GPUTextureFormat.RGBA32Sint;
  21248. break;
  21249. case UnsignedByteType:
  21250. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  21251. break;
  21252. case HalfFloatType:
  21253. formatGPU = GPUTextureFormat.RGBA16Float;
  21254. break;
  21255. case FloatType:
  21256. formatGPU = GPUTextureFormat.RGBA32Float;
  21257. break;
  21258. default:
  21259. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  21260. }
  21261. break;
  21262. case RGBFormat:
  21263. switch ( type ) {
  21264. case UnsignedInt5999Type:
  21265. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  21266. break;
  21267. default:
  21268. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  21269. }
  21270. break;
  21271. case RedFormat:
  21272. switch ( type ) {
  21273. case ByteType:
  21274. formatGPU = GPUTextureFormat.R8Snorm;
  21275. break;
  21276. case ShortType:
  21277. formatGPU = GPUTextureFormat.R16Sint;
  21278. break;
  21279. case UnsignedShortType:
  21280. formatGPU = GPUTextureFormat.R16Uint;
  21281. break;
  21282. case UnsignedIntType:
  21283. formatGPU = GPUTextureFormat.R32Uint;
  21284. break;
  21285. case IntType:
  21286. formatGPU = GPUTextureFormat.R32Sint;
  21287. break;
  21288. case UnsignedByteType:
  21289. formatGPU = GPUTextureFormat.R8Unorm;
  21290. break;
  21291. case HalfFloatType:
  21292. formatGPU = GPUTextureFormat.R16Float;
  21293. break;
  21294. case FloatType:
  21295. formatGPU = GPUTextureFormat.R32Float;
  21296. break;
  21297. default:
  21298. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  21299. }
  21300. break;
  21301. case RGFormat:
  21302. switch ( type ) {
  21303. case ByteType:
  21304. formatGPU = GPUTextureFormat.RG8Snorm;
  21305. break;
  21306. case ShortType:
  21307. formatGPU = GPUTextureFormat.RG16Sint;
  21308. break;
  21309. case UnsignedShortType:
  21310. formatGPU = GPUTextureFormat.RG16Uint;
  21311. break;
  21312. case UnsignedIntType:
  21313. formatGPU = GPUTextureFormat.RG32Uint;
  21314. break;
  21315. case IntType:
  21316. formatGPU = GPUTextureFormat.RG32Sint;
  21317. break;
  21318. case UnsignedByteType:
  21319. formatGPU = GPUTextureFormat.RG8Unorm;
  21320. break;
  21321. case HalfFloatType:
  21322. formatGPU = GPUTextureFormat.RG16Float;
  21323. break;
  21324. case FloatType:
  21325. formatGPU = GPUTextureFormat.RG32Float;
  21326. break;
  21327. default:
  21328. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  21329. }
  21330. break;
  21331. case DepthFormat:
  21332. switch ( type ) {
  21333. case UnsignedShortType:
  21334. formatGPU = GPUTextureFormat.Depth16Unorm;
  21335. break;
  21336. case UnsignedIntType:
  21337. formatGPU = GPUTextureFormat.Depth24Plus;
  21338. break;
  21339. case FloatType:
  21340. formatGPU = GPUTextureFormat.Depth32Float;
  21341. break;
  21342. default:
  21343. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  21344. }
  21345. break;
  21346. case DepthStencilFormat:
  21347. switch ( type ) {
  21348. case UnsignedInt248Type:
  21349. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  21350. break;
  21351. case FloatType:
  21352. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  21353. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  21354. }
  21355. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  21356. break;
  21357. default:
  21358. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  21359. }
  21360. break;
  21361. case RedIntegerFormat:
  21362. switch ( type ) {
  21363. case IntType:
  21364. formatGPU = GPUTextureFormat.R32Sint;
  21365. break;
  21366. case UnsignedIntType:
  21367. formatGPU = GPUTextureFormat.R32Uint;
  21368. break;
  21369. default:
  21370. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  21371. }
  21372. break;
  21373. case RGIntegerFormat:
  21374. switch ( type ) {
  21375. case IntType:
  21376. formatGPU = GPUTextureFormat.RG32Sint;
  21377. break;
  21378. case UnsignedIntType:
  21379. formatGPU = GPUTextureFormat.RG32Uint;
  21380. break;
  21381. default:
  21382. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  21383. }
  21384. break;
  21385. case RGBAIntegerFormat:
  21386. switch ( type ) {
  21387. case IntType:
  21388. formatGPU = GPUTextureFormat.RGBA32Sint;
  21389. break;
  21390. case UnsignedIntType:
  21391. formatGPU = GPUTextureFormat.RGBA32Uint;
  21392. break;
  21393. default:
  21394. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  21395. }
  21396. break;
  21397. default:
  21398. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  21399. }
  21400. }
  21401. return formatGPU;
  21402. }
  21403. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  21404. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  21405. const wgslTypeLib$1 = {
  21406. 'f32': 'float',
  21407. 'i32': 'int',
  21408. 'u32': 'uint',
  21409. 'bool': 'bool',
  21410. 'vec2<f32>': 'vec2',
  21411. 'vec2<i32>': 'ivec2',
  21412. 'vec2<u32>': 'uvec2',
  21413. 'vec2<bool>': 'bvec2',
  21414. 'vec2f': 'vec2',
  21415. 'vec2i': 'ivec2',
  21416. 'vec2u': 'uvec2',
  21417. 'vec2b': 'bvec2',
  21418. 'vec3<f32>': 'vec3',
  21419. 'vec3<i32>': 'ivec3',
  21420. 'vec3<u32>': 'uvec3',
  21421. 'vec3<bool>': 'bvec3',
  21422. 'vec3f': 'vec3',
  21423. 'vec3i': 'ivec3',
  21424. 'vec3u': 'uvec3',
  21425. 'vec3b': 'bvec3',
  21426. 'vec4<f32>': 'vec4',
  21427. 'vec4<i32>': 'ivec4',
  21428. 'vec4<u32>': 'uvec4',
  21429. 'vec4<bool>': 'bvec4',
  21430. 'vec4f': 'vec4',
  21431. 'vec4i': 'ivec4',
  21432. 'vec4u': 'uvec4',
  21433. 'vec4b': 'bvec4',
  21434. 'mat2x2<f32>': 'mat2',
  21435. 'mat2x2f': 'mat2',
  21436. 'mat3x3<f32>': 'mat3',
  21437. 'mat3x3f': 'mat3',
  21438. 'mat4x4<f32>': 'mat4',
  21439. 'mat4x4f': 'mat4',
  21440. 'sampler': 'sampler',
  21441. 'texture_1d': 'texture',
  21442. 'texture_2d': 'texture',
  21443. 'texture_2d_array': 'texture',
  21444. 'texture_multisampled_2d': 'cubeTexture',
  21445. 'texture_depth_2d': 'depthTexture',
  21446. 'texture_3d': 'texture3D',
  21447. 'texture_cube': 'cubeTexture',
  21448. 'texture_cube_array': 'cubeTexture',
  21449. 'texture_storage_1d': 'storageTexture',
  21450. 'texture_storage_2d': 'storageTexture',
  21451. 'texture_storage_2d_array': 'storageTexture',
  21452. 'texture_storage_3d': 'storageTexture'
  21453. };
  21454. const parse = ( source ) => {
  21455. source = source.trim();
  21456. const declaration = source.match( declarationRegexp );
  21457. if ( declaration !== null && declaration.length === 4 ) {
  21458. const inputsCode = declaration[ 2 ];
  21459. const propsMatches = [];
  21460. let match = null;
  21461. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  21462. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  21463. }
  21464. // Process matches to correctly pair names and types
  21465. const inputs = [];
  21466. for ( let i = 0; i < propsMatches.length; i ++ ) {
  21467. const { name, type } = propsMatches[ i ];
  21468. let resolvedType = type;
  21469. if ( resolvedType.startsWith( 'ptr' ) ) {
  21470. resolvedType = 'pointer';
  21471. } else {
  21472. if ( resolvedType.startsWith( 'texture' ) ) {
  21473. resolvedType = type.split( '<' )[ 0 ];
  21474. }
  21475. resolvedType = wgslTypeLib$1[ resolvedType ];
  21476. }
  21477. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  21478. }
  21479. const blockCode = source.substring( declaration[ 0 ].length );
  21480. const outputType = declaration[ 3 ] || 'void';
  21481. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  21482. const type = wgslTypeLib$1[ outputType ] || outputType;
  21483. return {
  21484. type,
  21485. inputs,
  21486. name,
  21487. inputsCode,
  21488. blockCode,
  21489. outputType
  21490. };
  21491. } else {
  21492. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  21493. }
  21494. };
  21495. class WGSLNodeFunction extends NodeFunction {
  21496. constructor( source ) {
  21497. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  21498. super( type, inputs, name );
  21499. this.inputsCode = inputsCode;
  21500. this.blockCode = blockCode;
  21501. this.outputType = outputType;
  21502. }
  21503. getCode( name = this.name ) {
  21504. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  21505. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  21506. }
  21507. }
  21508. class WGSLNodeParser extends NodeParser {
  21509. parseFunction( source ) {
  21510. return new WGSLNodeFunction( source );
  21511. }
  21512. }
  21513. // GPUShaderStage is not defined in browsers not supporting WebGPU
  21514. const GPUShaderStage = self.GPUShaderStage;
  21515. const wrapNames = {
  21516. [ RepeatWrapping ]: 'repeat',
  21517. [ ClampToEdgeWrapping ]: 'clamp',
  21518. [ MirroredRepeatWrapping ]: 'mirror'
  21519. };
  21520. const gpuShaderStageLib = {
  21521. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  21522. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  21523. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  21524. };
  21525. const supports = {
  21526. instance: true,
  21527. swizzleAssign: false,
  21528. storageBuffer: true
  21529. };
  21530. const wgslFnOpLib = {
  21531. '^^': 'tsl_xor'
  21532. };
  21533. const wgslTypeLib = {
  21534. float: 'f32',
  21535. int: 'i32',
  21536. uint: 'u32',
  21537. bool: 'bool',
  21538. color: 'vec3<f32>',
  21539. vec2: 'vec2<f32>',
  21540. ivec2: 'vec2<i32>',
  21541. uvec2: 'vec2<u32>',
  21542. bvec2: 'vec2<bool>',
  21543. vec3: 'vec3<f32>',
  21544. ivec3: 'vec3<i32>',
  21545. uvec3: 'vec3<u32>',
  21546. bvec3: 'vec3<bool>',
  21547. vec4: 'vec4<f32>',
  21548. ivec4: 'vec4<i32>',
  21549. uvec4: 'vec4<u32>',
  21550. bvec4: 'vec4<bool>',
  21551. mat2: 'mat2x2<f32>',
  21552. mat3: 'mat3x3<f32>',
  21553. mat4: 'mat4x4<f32>'
  21554. };
  21555. const wgslCodeCache = {};
  21556. const wgslPolyfill = {
  21557. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  21558. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  21559. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  21560. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  21561. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  21562. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  21563. 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 ); }' ),
  21564. 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 ); }' ),
  21565. 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 ); }' ),
  21566. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  21567. 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 ); }' ),
  21568. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  21569. biquadraticTexture: new CodeNode( /* wgsl */`
  21570. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  21571. let res = vec2f( iRes );
  21572. let uvScaled = coord * res;
  21573. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  21574. // https://www.shadertoy.com/view/WtyXRy
  21575. let uv = uvWrapping - 0.5;
  21576. let iuv = floor( uv );
  21577. let f = fract( uv );
  21578. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  21579. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  21580. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  21581. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  21582. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  21583. }
  21584. ` )
  21585. };
  21586. const wgslMethods = {
  21587. dFdx: 'dpdx',
  21588. dFdy: '- dpdy',
  21589. mod_float: 'tsl_mod_float',
  21590. mod_vec2: 'tsl_mod_vec2',
  21591. mod_vec3: 'tsl_mod_vec3',
  21592. mod_vec4: 'tsl_mod_vec4',
  21593. equals_bool: 'tsl_equals_bool',
  21594. equals_bvec2: 'tsl_equals_bvec2',
  21595. equals_bvec3: 'tsl_equals_bvec3',
  21596. equals_bvec4: 'tsl_equals_bvec4',
  21597. inversesqrt: 'inverseSqrt',
  21598. bitcast: 'bitcast<f32>'
  21599. };
  21600. // WebGPU issue: does not support pow() with negative base on Windows
  21601. if ( /Windows/g.test( navigator.userAgent ) ) {
  21602. 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 ); }' );
  21603. 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 ] );
  21604. 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 ] );
  21605. 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 ] );
  21606. wgslMethods.pow_float = 'tsl_pow_float';
  21607. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  21608. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  21609. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  21610. }
  21611. //
  21612. let diagnostics = '';
  21613. if ( /Firefox|Deno/g.test( navigator.userAgent ) !== true ) {
  21614. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  21615. }
  21616. //
  21617. class WGSLNodeBuilder extends NodeBuilder {
  21618. constructor( object, renderer ) {
  21619. super( object, renderer, new WGSLNodeParser() );
  21620. this.uniformGroups = {};
  21621. this.builtins = {};
  21622. this.directives = {};
  21623. this.scopedArrays = new Map();
  21624. }
  21625. needsToWorkingColorSpace( texture ) {
  21626. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  21627. }
  21628. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  21629. if ( shaderStage === 'fragment' ) {
  21630. if ( depthSnippet ) {
  21631. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  21632. } else {
  21633. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  21634. }
  21635. } else if ( this.isFilteredTexture( texture ) ) {
  21636. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  21637. } else {
  21638. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0' );
  21639. }
  21640. }
  21641. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  21642. if ( shaderStage === 'fragment' ) {
  21643. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  21644. } else {
  21645. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  21646. }
  21647. }
  21648. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  21649. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false ) {
  21650. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  21651. } else if ( this.isFilteredTexture( texture ) ) {
  21652. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  21653. } else {
  21654. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  21655. }
  21656. }
  21657. generateWrapFunction( texture ) {
  21658. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }T`;
  21659. let nodeCode = wgslCodeCache[ functionName ];
  21660. if ( nodeCode === undefined ) {
  21661. const includes = [];
  21662. let code = `fn ${ functionName }( coord : vec2f ) -> vec2f {\n\n\treturn vec2f(\n`;
  21663. const addWrapSnippet = ( wrap, axis ) => {
  21664. if ( wrap === RepeatWrapping ) {
  21665. includes.push( wgslPolyfill.repeatWrapping_float );
  21666. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  21667. } else if ( wrap === ClampToEdgeWrapping ) {
  21668. includes.push( wgslPolyfill.clampWrapping_float );
  21669. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  21670. } else if ( wrap === MirroredRepeatWrapping ) {
  21671. includes.push( wgslPolyfill.mirrorWrapping_float );
  21672. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  21673. } else {
  21674. code += `\t\tcoord.${ axis }`;
  21675. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  21676. }
  21677. };
  21678. addWrapSnippet( texture.wrapS, 'x' );
  21679. code += ',\n';
  21680. addWrapSnippet( texture.wrapT, 'y' );
  21681. code += '\n\t);\n\n}\n';
  21682. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  21683. }
  21684. nodeCode.build( this );
  21685. return functionName;
  21686. }
  21687. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  21688. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  21689. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  21690. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  21691. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  21692. let textureDimensionsParams;
  21693. if ( texture.isMultisampleRenderTargetTexture === true ) {
  21694. textureDimensionsParams = textureProperty;
  21695. } else {
  21696. textureDimensionsParams = `${ textureProperty }, u32( ${ levelSnippet } )`;
  21697. }
  21698. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, 'uvec2' ) );
  21699. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  21700. }
  21701. return textureDimensionNode.build( this );
  21702. }
  21703. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  21704. this._include( 'biquadraticTexture' );
  21705. const wrapFunction = this.generateWrapFunction( texture );
  21706. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  21707. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  21708. }
  21709. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  21710. const wrapFunction = this.generateWrapFunction( texture );
  21711. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  21712. const coordSnippet = `vec2u( ${ wrapFunction }( ${ uvSnippet } ) * vec2f( ${ textureDimension } ) )`;
  21713. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  21714. }
  21715. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  21716. if ( depthSnippet ) {
  21717. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  21718. } else {
  21719. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  21720. }
  21721. }
  21722. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  21723. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  21724. }
  21725. isSampleCompare( texture ) {
  21726. return texture.isDepthTexture === true && texture.compareFunction !== null;
  21727. }
  21728. isUnfilterable( texture ) {
  21729. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  21730. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  21731. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  21732. texture.isMultisampleRenderTargetTexture === true;
  21733. }
  21734. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  21735. let snippet = null;
  21736. if ( texture.isVideoTexture === true ) {
  21737. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  21738. } else if ( this.isUnfilterable( texture ) ) {
  21739. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  21740. } else {
  21741. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  21742. }
  21743. return snippet;
  21744. }
  21745. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  21746. if ( shaderStage === 'fragment' ) {
  21747. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  21748. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  21749. } else {
  21750. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  21751. }
  21752. }
  21753. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  21754. if ( shaderStage === 'fragment' ) {
  21755. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  21756. } else {
  21757. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  21758. }
  21759. }
  21760. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  21761. let snippet = null;
  21762. if ( texture.isVideoTexture === true ) {
  21763. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  21764. } else {
  21765. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  21766. }
  21767. return snippet;
  21768. }
  21769. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  21770. if ( shaderStage === 'fragment' ) {
  21771. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  21772. } else {
  21773. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  21774. }
  21775. }
  21776. getPropertyName( node, shaderStage = this.shaderStage ) {
  21777. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  21778. if ( shaderStage === 'vertex' ) {
  21779. return `varyings.${ node.name }`;
  21780. }
  21781. } else if ( node.isNodeUniform === true ) {
  21782. const name = node.name;
  21783. const type = node.type;
  21784. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  21785. return name;
  21786. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  21787. return `NodeBuffer_${ node.id }.${name}`;
  21788. } else {
  21789. return node.groupNode.name + '.' + name;
  21790. }
  21791. }
  21792. return super.getPropertyName( node );
  21793. }
  21794. getOutputStructName() {
  21795. return 'output';
  21796. }
  21797. _getUniformGroupCount( shaderStage ) {
  21798. return Object.keys( this.uniforms[ shaderStage ] ).length;
  21799. }
  21800. getFunctionOperator( op ) {
  21801. const fnOp = wgslFnOpLib[ op ];
  21802. if ( fnOp !== undefined ) {
  21803. this._include( fnOp );
  21804. return fnOp;
  21805. }
  21806. return null;
  21807. }
  21808. getStorageAccess( node ) {
  21809. if ( node.isStorageTextureNode ) {
  21810. switch ( node.access ) {
  21811. case GPUStorageTextureAccess.ReadOnly:
  21812. return 'read';
  21813. case GPUStorageTextureAccess.WriteOnly:
  21814. return 'write';
  21815. default:
  21816. return 'read_write';
  21817. }
  21818. } else {
  21819. switch ( node.access ) {
  21820. case GPUBufferBindingType.Storage:
  21821. return 'read_write';
  21822. case GPUBufferBindingType.ReadOnlyStorage:
  21823. return 'read';
  21824. default:
  21825. return 'write';
  21826. }
  21827. }
  21828. }
  21829. getUniformFromNode( node, type, shaderStage, name = null ) {
  21830. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  21831. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  21832. if ( nodeData.uniformGPU === undefined ) {
  21833. let uniformGPU;
  21834. const group = node.groupNode;
  21835. const groupName = group.name;
  21836. const bindings = this.getBindGroupArray( groupName, shaderStage );
  21837. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  21838. let texture = null;
  21839. if ( type === 'texture' || type === 'storageTexture' ) {
  21840. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  21841. } else if ( type === 'cubeTexture' ) {
  21842. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  21843. } else if ( type === 'texture3D' ) {
  21844. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  21845. }
  21846. texture.store = node.isStorageTextureNode === true;
  21847. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  21848. if ( shaderStage === 'fragment' && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  21849. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  21850. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  21851. bindings.push( sampler, texture );
  21852. uniformGPU = [ sampler, texture ];
  21853. } else {
  21854. bindings.push( texture );
  21855. uniformGPU = [ texture ];
  21856. }
  21857. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  21858. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  21859. const buffer = new bufferClass( node, group );
  21860. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  21861. bindings.push( buffer );
  21862. uniformGPU = buffer;
  21863. } else {
  21864. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  21865. let uniformsGroup = uniformsStage[ groupName ];
  21866. if ( uniformsGroup === undefined ) {
  21867. uniformsGroup = new NodeUniformsGroup( groupName, group );
  21868. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  21869. uniformsStage[ groupName ] = uniformsGroup;
  21870. bindings.push( uniformsGroup );
  21871. }
  21872. uniformGPU = this.getNodeUniform( uniformNode, type );
  21873. uniformsGroup.addUniform( uniformGPU );
  21874. }
  21875. nodeData.uniformGPU = uniformGPU;
  21876. }
  21877. return uniformNode;
  21878. }
  21879. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  21880. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  21881. if ( map.has( name ) === false ) {
  21882. map.set( name, {
  21883. name,
  21884. property,
  21885. type
  21886. } );
  21887. }
  21888. return property;
  21889. }
  21890. hasBuiltin( name, shaderStage = this.shaderStage ) {
  21891. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  21892. }
  21893. getVertexIndex() {
  21894. if ( this.shaderStage === 'vertex' ) {
  21895. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  21896. }
  21897. return 'vertexIndex';
  21898. }
  21899. buildFunctionCode( shaderNode ) {
  21900. const layout = shaderNode.layout;
  21901. const flowData = this.flowShaderNode( shaderNode );
  21902. const parameters = [];
  21903. for ( const input of layout.inputs ) {
  21904. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  21905. }
  21906. //
  21907. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  21908. ${ flowData.vars }
  21909. ${ flowData.code }
  21910. `;
  21911. if ( flowData.result ) {
  21912. code += `\treturn ${ flowData.result };\n`;
  21913. }
  21914. code += '\n}\n';
  21915. //
  21916. return code;
  21917. }
  21918. getInstanceIndex() {
  21919. if ( this.shaderStage === 'vertex' ) {
  21920. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  21921. }
  21922. return 'instanceIndex';
  21923. }
  21924. getInvocationLocalIndex() {
  21925. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  21926. }
  21927. getSubgroupSize() {
  21928. this.enableSubGroups();
  21929. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  21930. }
  21931. getInvocationSubgroupIndex() {
  21932. this.enableSubGroups();
  21933. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  21934. }
  21935. getSubgroupIndex() {
  21936. this.enableSubGroups();
  21937. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  21938. }
  21939. getDrawIndex() {
  21940. return null;
  21941. }
  21942. getFrontFacing() {
  21943. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  21944. }
  21945. getFragCoord() {
  21946. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  21947. }
  21948. getFragDepth() {
  21949. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  21950. }
  21951. getClipDistance() {
  21952. return 'varyings.hw_clip_distances';
  21953. }
  21954. isFlipY() {
  21955. return false;
  21956. }
  21957. enableDirective( name, shaderStage = this.shaderStage ) {
  21958. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  21959. stage.add( name );
  21960. }
  21961. getDirectives( shaderStage ) {
  21962. const snippets = [];
  21963. const directives = this.directives[ shaderStage ];
  21964. if ( directives !== undefined ) {
  21965. for ( const directive of directives ) {
  21966. snippets.push( `enable ${directive};` );
  21967. }
  21968. }
  21969. return snippets.join( '\n' );
  21970. }
  21971. enableSubGroups() {
  21972. this.enableDirective( 'subgroups' );
  21973. }
  21974. enableSubgroupsF16() {
  21975. this.enableDirective( 'subgroups-f16' );
  21976. }
  21977. enableClipDistances() {
  21978. this.enableDirective( 'clip_distances' );
  21979. }
  21980. enableShaderF16() {
  21981. this.enableDirective( 'f16' );
  21982. }
  21983. enableDualSourceBlending() {
  21984. this.enableDirective( 'dual_source_blending' );
  21985. }
  21986. enableHardwareClipping( planeCount ) {
  21987. this.enableClipDistances();
  21988. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  21989. }
  21990. getBuiltins( shaderStage ) {
  21991. const snippets = [];
  21992. const builtins = this.builtins[ shaderStage ];
  21993. if ( builtins !== undefined ) {
  21994. for ( const { name, property, type } of builtins.values() ) {
  21995. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  21996. }
  21997. }
  21998. return snippets.join( ',\n\t' );
  21999. }
  22000. getScopedArray( name, scope, bufferType, bufferCount ) {
  22001. if ( this.scopedArrays.has( name ) === false ) {
  22002. this.scopedArrays.set( name, {
  22003. name,
  22004. scope,
  22005. bufferType,
  22006. bufferCount
  22007. } );
  22008. }
  22009. return name;
  22010. }
  22011. getScopedArrays( shaderStage ) {
  22012. if ( shaderStage !== 'compute' ) {
  22013. return;
  22014. }
  22015. const snippets = [];
  22016. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  22017. const type = this.getType( bufferType );
  22018. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  22019. }
  22020. return snippets.join( '\n' );
  22021. }
  22022. getAttributes( shaderStage ) {
  22023. const snippets = [];
  22024. if ( shaderStage === 'compute' ) {
  22025. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  22026. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  22027. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  22028. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  22029. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  22030. this.enableDirective( 'subgroups', shaderStage );
  22031. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  22032. }
  22033. }
  22034. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  22035. const builtins = this.getBuiltins( 'attribute' );
  22036. if ( builtins ) snippets.push( builtins );
  22037. const attributes = this.getAttributesArray();
  22038. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  22039. const attribute = attributes[ index ];
  22040. const name = attribute.name;
  22041. const type = this.getType( attribute.type );
  22042. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  22043. }
  22044. }
  22045. return snippets.join( ',\n\t' );
  22046. }
  22047. getStructMembers( struct ) {
  22048. const snippets = [];
  22049. const members = struct.getMemberTypes();
  22050. for ( let i = 0; i < members.length; i ++ ) {
  22051. const member = members[ i ];
  22052. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  22053. }
  22054. const builtins = this.getBuiltins( 'output' );
  22055. if ( builtins ) snippets.push( '\t' + builtins );
  22056. return snippets.join( ',\n' );
  22057. }
  22058. getStructs( shaderStage ) {
  22059. const snippets = [];
  22060. const structs = this.structs[ shaderStage ];
  22061. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  22062. const struct = structs[ index ];
  22063. const name = struct.name;
  22064. let snippet = `\struct ${ name } {\n`;
  22065. snippet += this.getStructMembers( struct );
  22066. snippet += '\n}';
  22067. snippets.push( snippet );
  22068. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  22069. }
  22070. return snippets.join( '\n\n' );
  22071. }
  22072. getVar( type, name ) {
  22073. return `var ${ name } : ${ this.getType( type ) }`;
  22074. }
  22075. getVars( shaderStage ) {
  22076. const snippets = [];
  22077. const vars = this.vars[ shaderStage ];
  22078. if ( vars !== undefined ) {
  22079. for ( const variable of vars ) {
  22080. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  22081. }
  22082. }
  22083. return `\n${ snippets.join( '\n' ) }\n`;
  22084. }
  22085. getVaryings( shaderStage ) {
  22086. const snippets = [];
  22087. if ( shaderStage === 'vertex' ) {
  22088. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  22089. }
  22090. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  22091. const varyings = this.varyings;
  22092. const vars = this.vars[ shaderStage ];
  22093. for ( let index = 0; index < varyings.length; index ++ ) {
  22094. const varying = varyings[ index ];
  22095. if ( varying.needsInterpolation ) {
  22096. let attributesSnippet = `@location( ${index} )`;
  22097. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  22098. attributesSnippet += ' @interpolate( flat )';
  22099. }
  22100. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  22101. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  22102. vars.push( varying );
  22103. }
  22104. }
  22105. }
  22106. const builtins = this.getBuiltins( shaderStage );
  22107. if ( builtins ) snippets.push( builtins );
  22108. const code = snippets.join( ',\n\t' );
  22109. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  22110. }
  22111. getUniforms( shaderStage ) {
  22112. const uniforms = this.uniforms[ shaderStage ];
  22113. const bindingSnippets = [];
  22114. const bufferSnippets = [];
  22115. const structSnippets = [];
  22116. const uniformGroups = {};
  22117. for ( const uniform of uniforms ) {
  22118. const groupName = uniform.groupNode.name;
  22119. const uniformIndexes = this.bindingsIndexes[ groupName ];
  22120. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  22121. const texture = uniform.node.value;
  22122. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  22123. if ( this.isSampleCompare( texture ) ) {
  22124. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  22125. } else {
  22126. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  22127. }
  22128. }
  22129. let textureType;
  22130. let multisampled = '';
  22131. if ( texture.isMultisampleRenderTargetTexture === true ) {
  22132. multisampled = '_multisampled';
  22133. }
  22134. if ( texture.isCubeTexture === true ) {
  22135. textureType = 'texture_cube<f32>';
  22136. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  22137. textureType = 'texture_2d_array<f32>';
  22138. } else if ( texture.isDepthTexture === true ) {
  22139. textureType = `texture_depth${multisampled}_2d`;
  22140. } else if ( texture.isVideoTexture === true ) {
  22141. textureType = 'texture_external';
  22142. } else if ( texture.isData3DTexture === true ) {
  22143. textureType = 'texture_3d<f32>';
  22144. } else if ( uniform.node.isStorageTextureNode === true ) {
  22145. const format = getFormat( texture );
  22146. const access = this.getStorageAccess( uniform.node );
  22147. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  22148. } else {
  22149. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  22150. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  22151. }
  22152. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  22153. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  22154. const bufferNode = uniform.node;
  22155. const bufferType = this.getType( bufferNode.bufferType );
  22156. const bufferCount = bufferNode.bufferCount;
  22157. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  22158. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${bufferType}>` : `${bufferType}`;
  22159. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >\n`;
  22160. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode ) }` : 'uniform';
  22161. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  22162. } else {
  22163. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  22164. const groupName = uniform.groupNode.name;
  22165. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  22166. index: uniformIndexes.binding ++,
  22167. id: uniformIndexes.group,
  22168. snippets: []
  22169. } );
  22170. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  22171. }
  22172. }
  22173. for ( const name in uniformGroups ) {
  22174. const group = uniformGroups[ name ];
  22175. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  22176. }
  22177. let code = bindingSnippets.join( '\n' );
  22178. code += bufferSnippets.join( '\n' );
  22179. code += structSnippets.join( '\n' );
  22180. return code;
  22181. }
  22182. buildCode() {
  22183. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  22184. this.sortBindingGroups();
  22185. for ( const shaderStage in shadersData ) {
  22186. const stageData = shadersData[ shaderStage ];
  22187. stageData.uniforms = this.getUniforms( shaderStage );
  22188. stageData.attributes = this.getAttributes( shaderStage );
  22189. stageData.varyings = this.getVaryings( shaderStage );
  22190. stageData.structs = this.getStructs( shaderStage );
  22191. stageData.vars = this.getVars( shaderStage );
  22192. stageData.codes = this.getCodes( shaderStage );
  22193. stageData.directives = this.getDirectives( shaderStage );
  22194. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  22195. //
  22196. let flow = '// code\n\n';
  22197. flow += this.flowCode[ shaderStage ];
  22198. const flowNodes = this.flowNodes[ shaderStage ];
  22199. const mainNode = flowNodes[ flowNodes.length - 1 ];
  22200. const outputNode = mainNode.outputNode;
  22201. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  22202. for ( const node of flowNodes ) {
  22203. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  22204. const slotName = node.name;
  22205. if ( slotName ) {
  22206. if ( flow.length > 0 ) flow += '\n';
  22207. flow += `\t// flow -> ${ slotName }\n\t`;
  22208. }
  22209. flow += `${ flowSlotData.code }\n\t`;
  22210. if ( node === mainNode && shaderStage !== 'compute' ) {
  22211. flow += '// result\n\n\t';
  22212. if ( shaderStage === 'vertex' ) {
  22213. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  22214. } else if ( shaderStage === 'fragment' ) {
  22215. if ( isOutputStruct ) {
  22216. stageData.returnType = outputNode.nodeType;
  22217. flow += `return ${ flowSlotData.result };`;
  22218. } else {
  22219. let structSnippet = '\t@location(0) color: vec4<f32>';
  22220. const builtins = this.getBuiltins( 'output' );
  22221. if ( builtins ) structSnippet += ',\n\t' + builtins;
  22222. stageData.returnType = 'OutputStruct';
  22223. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  22224. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  22225. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  22226. }
  22227. }
  22228. }
  22229. }
  22230. stageData.flow = flow;
  22231. }
  22232. if ( this.material !== null ) {
  22233. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  22234. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  22235. } else {
  22236. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  22237. }
  22238. }
  22239. getMethod( method, output = null ) {
  22240. let wgslMethod;
  22241. if ( output !== null ) {
  22242. wgslMethod = this._getWGSLMethod( method + '_' + output );
  22243. }
  22244. if ( wgslMethod === undefined ) {
  22245. wgslMethod = this._getWGSLMethod( method );
  22246. }
  22247. return wgslMethod || method;
  22248. }
  22249. getType( type ) {
  22250. return wgslTypeLib[ type ] || type;
  22251. }
  22252. isAvailable( name ) {
  22253. let result = supports[ name ];
  22254. if ( result === undefined ) {
  22255. if ( name === 'float32Filterable' ) {
  22256. result = this.renderer.hasFeature( 'float32-filterable' );
  22257. } else if ( name === 'clipDistance' ) {
  22258. result = this.renderer.hasFeature( 'clip-distances' );
  22259. }
  22260. supports[ name ] = result;
  22261. }
  22262. return result;
  22263. }
  22264. _getWGSLMethod( method ) {
  22265. if ( wgslPolyfill[ method ] !== undefined ) {
  22266. this._include( method );
  22267. }
  22268. return wgslMethods[ method ];
  22269. }
  22270. _include( name ) {
  22271. const codeNode = wgslPolyfill[ name ];
  22272. codeNode.build( this );
  22273. if ( this.currentFunctionNode !== null ) {
  22274. this.currentFunctionNode.includes.push( codeNode );
  22275. }
  22276. return codeNode;
  22277. }
  22278. _getWGSLVertexCode( shaderData ) {
  22279. return `${ this.getSignature() }
  22280. // directives
  22281. ${shaderData.directives}
  22282. // uniforms
  22283. ${shaderData.uniforms}
  22284. // varyings
  22285. ${shaderData.varyings}
  22286. var<private> varyings : VaryingsStruct;
  22287. // codes
  22288. ${shaderData.codes}
  22289. @vertex
  22290. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  22291. // vars
  22292. ${shaderData.vars}
  22293. // flow
  22294. ${shaderData.flow}
  22295. return varyings;
  22296. }
  22297. `;
  22298. }
  22299. _getWGSLFragmentCode( shaderData ) {
  22300. return `${ this.getSignature() }
  22301. // global
  22302. ${ diagnostics }
  22303. // uniforms
  22304. ${shaderData.uniforms}
  22305. // structs
  22306. ${shaderData.structs}
  22307. // codes
  22308. ${shaderData.codes}
  22309. @fragment
  22310. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  22311. // vars
  22312. ${shaderData.vars}
  22313. // flow
  22314. ${shaderData.flow}
  22315. }
  22316. `;
  22317. }
  22318. _getWGSLComputeCode( shaderData, workgroupSize ) {
  22319. return `${ this.getSignature() }
  22320. // directives
  22321. ${shaderData.directives}
  22322. // system
  22323. var<private> instanceIndex : u32;
  22324. // locals
  22325. ${shaderData.scopedArrays}
  22326. // uniforms
  22327. ${shaderData.uniforms}
  22328. // codes
  22329. ${shaderData.codes}
  22330. @compute @workgroup_size( ${workgroupSize} )
  22331. fn main( ${shaderData.attributes} ) {
  22332. // system
  22333. instanceIndex = id.x + id.y * numWorkgroups.x * u32(${workgroupSize}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  22334. // vars
  22335. ${shaderData.vars}
  22336. // flow
  22337. ${shaderData.flow}
  22338. }
  22339. `;
  22340. }
  22341. _getWGSLStruct( name, vars ) {
  22342. return `
  22343. struct ${name} {
  22344. ${vars}
  22345. };`;
  22346. }
  22347. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  22348. const structName = name + 'Struct';
  22349. const structSnippet = this._getWGSLStruct( structName, vars );
  22350. return `${structSnippet}
  22351. @binding( ${binding} ) @group( ${group} )
  22352. var<${access}> ${name} : ${structName};`;
  22353. }
  22354. }
  22355. class WebGPUUtils {
  22356. constructor( backend ) {
  22357. this.backend = backend;
  22358. }
  22359. getCurrentDepthStencilFormat( renderContext ) {
  22360. let format;
  22361. if ( renderContext.depthTexture !== null ) {
  22362. format = this.getTextureFormatGPU( renderContext.depthTexture );
  22363. } else if ( renderContext.depth && renderContext.stencil ) {
  22364. format = GPUTextureFormat.Depth24PlusStencil8;
  22365. } else if ( renderContext.depth ) {
  22366. format = GPUTextureFormat.Depth24Plus;
  22367. }
  22368. return format;
  22369. }
  22370. getTextureFormatGPU( texture ) {
  22371. return this.backend.get( texture ).format;
  22372. }
  22373. getCurrentColorFormat( renderContext ) {
  22374. let format;
  22375. if ( renderContext.textures !== null ) {
  22376. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  22377. } else {
  22378. format = this.getPreferredCanvasFormat(); // default context format
  22379. }
  22380. return format;
  22381. }
  22382. getCurrentColorSpace( renderContext ) {
  22383. if ( renderContext.textures !== null ) {
  22384. return renderContext.textures[ 0 ].colorSpace;
  22385. }
  22386. return this.backend.renderer.outputColorSpace;
  22387. }
  22388. getPrimitiveTopology( object, material ) {
  22389. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  22390. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  22391. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  22392. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  22393. }
  22394. getSampleCount( sampleCount ) {
  22395. let count = 1;
  22396. if ( sampleCount > 1 ) {
  22397. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  22398. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  22399. if ( count === 2 ) {
  22400. count = 4;
  22401. }
  22402. }
  22403. return count;
  22404. }
  22405. getSampleCountRenderContext( renderContext ) {
  22406. if ( renderContext.textures !== null ) {
  22407. return this.getSampleCount( renderContext.sampleCount );
  22408. }
  22409. return this.getSampleCount( this.backend.renderer.samples );
  22410. }
  22411. getPreferredCanvasFormat() {
  22412. // TODO: Remove this check when Quest 34.5 is out
  22413. // https://github.com/mrdoob/three.js/pull/29221/files#r1731833949
  22414. if ( navigator.userAgent.includes( 'Quest' ) ) {
  22415. return GPUTextureFormat.BGRA8Unorm;
  22416. } else {
  22417. return navigator.gpu.getPreferredCanvasFormat();
  22418. }
  22419. }
  22420. }
  22421. const typedArraysToVertexFormatPrefix = new Map( [
  22422. [ Int8Array, [ 'sint8', 'snorm8' ]],
  22423. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  22424. [ Int16Array, [ 'sint16', 'snorm16' ]],
  22425. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  22426. [ Int32Array, [ 'sint32', 'snorm32' ]],
  22427. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  22428. [ Float32Array, [ 'float32', ]],
  22429. ] );
  22430. const typedAttributeToVertexFormatPrefix = new Map( [
  22431. [ Float16BufferAttribute, [ 'float16', ]],
  22432. ] );
  22433. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  22434. [ Int32Array, 'sint32' ],
  22435. [ Int16Array, 'sint32' ], // patch for INT16
  22436. [ Uint32Array, 'uint32' ],
  22437. [ Uint16Array, 'uint32' ], // patch for UINT16
  22438. [ Float32Array, 'float32' ]
  22439. ] );
  22440. class WebGPUAttributeUtils {
  22441. constructor( backend ) {
  22442. this.backend = backend;
  22443. }
  22444. createAttribute( attribute, usage ) {
  22445. const bufferAttribute = this._getBufferAttribute( attribute );
  22446. const backend = this.backend;
  22447. const bufferData = backend.get( bufferAttribute );
  22448. let buffer = bufferData.buffer;
  22449. if ( buffer === undefined ) {
  22450. const device = backend.device;
  22451. let array = bufferAttribute.array;
  22452. // patch for INT16 and UINT16
  22453. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  22454. const tempArray = new Uint32Array( array.length );
  22455. for ( let i = 0; i < array.length; i ++ ) {
  22456. tempArray[ i ] = array[ i ];
  22457. }
  22458. array = tempArray;
  22459. }
  22460. bufferAttribute.array = array;
  22461. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  22462. array = new array.constructor( bufferAttribute.count * 4 );
  22463. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  22464. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  22465. }
  22466. // Update BufferAttribute
  22467. bufferAttribute.itemSize = 4;
  22468. bufferAttribute.array = array;
  22469. }
  22470. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  22471. buffer = device.createBuffer( {
  22472. label: bufferAttribute.name,
  22473. size: size,
  22474. usage: usage,
  22475. mappedAtCreation: true
  22476. } );
  22477. new array.constructor( buffer.getMappedRange() ).set( array );
  22478. buffer.unmap();
  22479. bufferData.buffer = buffer;
  22480. }
  22481. }
  22482. updateAttribute( attribute ) {
  22483. const bufferAttribute = this._getBufferAttribute( attribute );
  22484. const backend = this.backend;
  22485. const device = backend.device;
  22486. const buffer = backend.get( bufferAttribute ).buffer;
  22487. const array = bufferAttribute.array;
  22488. const updateRanges = bufferAttribute.updateRanges;
  22489. if ( updateRanges.length === 0 ) {
  22490. // Not using update ranges
  22491. device.queue.writeBuffer(
  22492. buffer,
  22493. 0,
  22494. array,
  22495. 0
  22496. );
  22497. } else {
  22498. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  22499. const range = updateRanges[ i ];
  22500. device.queue.writeBuffer(
  22501. buffer,
  22502. 0,
  22503. array,
  22504. range.start * array.BYTES_PER_ELEMENT,
  22505. range.count * array.BYTES_PER_ELEMENT
  22506. );
  22507. }
  22508. bufferAttribute.clearUpdateRanges();
  22509. }
  22510. }
  22511. createShaderVertexBuffers( renderObject ) {
  22512. const attributes = renderObject.getAttributes();
  22513. const vertexBuffers = new Map();
  22514. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  22515. const geometryAttribute = attributes[ slot ];
  22516. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  22517. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  22518. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  22519. if ( vertexBufferLayout === undefined ) {
  22520. let arrayStride, stepMode;
  22521. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  22522. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  22523. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  22524. } else {
  22525. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  22526. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  22527. }
  22528. // patch for INT16 and UINT16
  22529. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  22530. arrayStride = 4;
  22531. }
  22532. vertexBufferLayout = {
  22533. arrayStride,
  22534. attributes: [],
  22535. stepMode
  22536. };
  22537. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  22538. }
  22539. const format = this._getVertexFormat( geometryAttribute );
  22540. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  22541. vertexBufferLayout.attributes.push( {
  22542. shaderLocation: slot,
  22543. offset,
  22544. format
  22545. } );
  22546. }
  22547. return Array.from( vertexBuffers.values() );
  22548. }
  22549. destroyAttribute( attribute ) {
  22550. const backend = this.backend;
  22551. const data = backend.get( this._getBufferAttribute( attribute ) );
  22552. data.buffer.destroy();
  22553. backend.delete( attribute );
  22554. }
  22555. async getArrayBufferAsync( attribute ) {
  22556. const backend = this.backend;
  22557. const device = backend.device;
  22558. const data = backend.get( this._getBufferAttribute( attribute ) );
  22559. const bufferGPU = data.buffer;
  22560. const size = bufferGPU.size;
  22561. const readBufferGPU = device.createBuffer( {
  22562. label: attribute.name,
  22563. size,
  22564. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  22565. } );
  22566. const cmdEncoder = device.createCommandEncoder( {} );
  22567. cmdEncoder.copyBufferToBuffer(
  22568. bufferGPU,
  22569. 0,
  22570. readBufferGPU,
  22571. 0,
  22572. size
  22573. );
  22574. readBufferGPU.unmap();
  22575. const gpuCommands = cmdEncoder.finish();
  22576. device.queue.submit( [ gpuCommands ] );
  22577. await readBufferGPU.mapAsync( GPUMapMode.READ );
  22578. const arrayBuffer = readBufferGPU.getMappedRange();
  22579. return arrayBuffer;
  22580. }
  22581. _getVertexFormat( geometryAttribute ) {
  22582. const { itemSize, normalized } = geometryAttribute;
  22583. const ArrayType = geometryAttribute.array.constructor;
  22584. const AttributeType = geometryAttribute.constructor;
  22585. let format;
  22586. if ( itemSize == 1 ) {
  22587. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  22588. } else {
  22589. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  22590. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  22591. if ( prefix ) {
  22592. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  22593. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  22594. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  22595. if ( paddedItemSize % 1 ) {
  22596. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  22597. }
  22598. format = `${prefix}x${paddedItemSize}`;
  22599. }
  22600. }
  22601. if ( ! format ) {
  22602. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  22603. }
  22604. return format;
  22605. }
  22606. _getBufferAttribute( attribute ) {
  22607. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  22608. return attribute;
  22609. }
  22610. }
  22611. class WebGPUBindingUtils {
  22612. constructor( backend ) {
  22613. this.backend = backend;
  22614. this.bindGroupLayoutCache = new WeakMap();
  22615. }
  22616. createBindingsLayout( bindGroup ) {
  22617. const backend = this.backend;
  22618. const device = backend.device;
  22619. const entries = [];
  22620. let index = 0;
  22621. for ( const binding of bindGroup.bindings ) {
  22622. const bindingGPU = {
  22623. binding: index ++,
  22624. visibility: binding.visibility
  22625. };
  22626. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  22627. const buffer = {}; // GPUBufferBindingLayout
  22628. if ( binding.isStorageBuffer ) {
  22629. buffer.type = binding.access;
  22630. }
  22631. bindingGPU.buffer = buffer;
  22632. } else if ( binding.isSampler ) {
  22633. const sampler = {}; // GPUSamplerBindingLayout
  22634. if ( binding.texture.isDepthTexture ) {
  22635. if ( binding.texture.compareFunction !== null ) {
  22636. sampler.type = 'comparison';
  22637. }
  22638. }
  22639. bindingGPU.sampler = sampler;
  22640. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  22641. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  22642. } else if ( binding.isSampledTexture && binding.store ) {
  22643. const format = this.backend.get( binding.texture ).texture.format;
  22644. const access = binding.access;
  22645. bindingGPU.storageTexture = { format, access }; // GPUStorageTextureBindingLayout
  22646. } else if ( binding.isSampledTexture ) {
  22647. const texture = {}; // GPUTextureBindingLayout
  22648. if ( binding.texture.isMultisampleRenderTargetTexture === true ) {
  22649. texture.multisampled = true;
  22650. }
  22651. if ( binding.texture.isDepthTexture ) {
  22652. texture.sampleType = GPUTextureSampleType.Depth;
  22653. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  22654. const type = binding.texture.type;
  22655. if ( type === IntType ) {
  22656. texture.sampleType = GPUTextureSampleType.SInt;
  22657. } else if ( type === UnsignedIntType ) {
  22658. texture.sampleType = GPUTextureSampleType.UInt;
  22659. } else if ( type === FloatType ) {
  22660. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  22661. texture.sampleType = GPUTextureSampleType.Float;
  22662. } else {
  22663. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  22664. }
  22665. }
  22666. }
  22667. if ( binding.isSampledCubeTexture ) {
  22668. texture.viewDimension = GPUTextureViewDimension.Cube;
  22669. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  22670. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  22671. } else if ( binding.isSampledTexture3D ) {
  22672. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  22673. }
  22674. bindingGPU.texture = texture;
  22675. } else {
  22676. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  22677. }
  22678. entries.push( bindingGPU );
  22679. }
  22680. return device.createBindGroupLayout( { entries } );
  22681. }
  22682. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  22683. const { backend, bindGroupLayoutCache } = this;
  22684. const bindingsData = backend.get( bindGroup );
  22685. // setup (static) binding layout and (dynamic) binding group
  22686. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  22687. if ( bindLayoutGPU === undefined ) {
  22688. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  22689. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  22690. }
  22691. let bindGroupGPU;
  22692. if ( cacheIndex > 0 ) {
  22693. if ( bindingsData.groups === undefined ) {
  22694. bindingsData.groups = [];
  22695. bindingsData.versions = [];
  22696. }
  22697. if ( bindingsData.versions[ cacheIndex ] === version ) {
  22698. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  22699. }
  22700. }
  22701. if ( bindGroupGPU === undefined ) {
  22702. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  22703. if ( cacheIndex > 0 ) {
  22704. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  22705. bindingsData.versions[ cacheIndex ] = version;
  22706. }
  22707. }
  22708. bindingsData.group = bindGroupGPU;
  22709. bindingsData.layout = bindLayoutGPU;
  22710. }
  22711. updateBinding( binding ) {
  22712. const backend = this.backend;
  22713. const device = backend.device;
  22714. const buffer = binding.buffer;
  22715. const bufferGPU = backend.get( binding ).buffer;
  22716. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  22717. }
  22718. createBindGroup( bindGroup, layoutGPU ) {
  22719. const backend = this.backend;
  22720. const device = backend.device;
  22721. let bindingPoint = 0;
  22722. const entriesGPU = [];
  22723. for ( const binding of bindGroup.bindings ) {
  22724. if ( binding.isUniformBuffer ) {
  22725. const bindingData = backend.get( binding );
  22726. if ( bindingData.buffer === undefined ) {
  22727. const byteLength = binding.byteLength;
  22728. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  22729. const bufferGPU = device.createBuffer( {
  22730. label: 'bindingBuffer_' + binding.name,
  22731. size: byteLength,
  22732. usage: usage
  22733. } );
  22734. bindingData.buffer = bufferGPU;
  22735. }
  22736. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  22737. } else if ( binding.isStorageBuffer ) {
  22738. const bindingData = backend.get( binding );
  22739. if ( bindingData.buffer === undefined ) {
  22740. const attribute = binding.attribute;
  22741. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  22742. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  22743. bindingData.buffer = backend.get( attribute ).buffer;
  22744. }
  22745. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  22746. } else if ( binding.isSampler ) {
  22747. const textureGPU = backend.get( binding.texture );
  22748. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  22749. } else if ( binding.isSampledTexture ) {
  22750. const textureData = backend.get( binding.texture );
  22751. let resourceGPU;
  22752. if ( textureData.externalTexture !== undefined ) {
  22753. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  22754. } else {
  22755. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  22756. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  22757. resourceGPU = textureData[ propertyName ];
  22758. if ( resourceGPU === undefined ) {
  22759. const aspectGPU = GPUTextureAspect.All;
  22760. let dimensionViewGPU;
  22761. if ( binding.isSampledCubeTexture ) {
  22762. dimensionViewGPU = GPUTextureViewDimension.Cube;
  22763. } else if ( binding.isSampledTexture3D ) {
  22764. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  22765. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  22766. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  22767. } else {
  22768. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  22769. }
  22770. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  22771. }
  22772. }
  22773. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  22774. }
  22775. bindingPoint ++;
  22776. }
  22777. return device.createBindGroup( {
  22778. label: 'bindGroup_' + bindGroup.name,
  22779. layout: layoutGPU,
  22780. entries: entriesGPU
  22781. } );
  22782. }
  22783. }
  22784. class WebGPUPipelineUtils {
  22785. constructor( backend ) {
  22786. this.backend = backend;
  22787. }
  22788. _getSampleCount( renderObjectContext ) {
  22789. return this.backend.utils.getSampleCountRenderContext( renderObjectContext );
  22790. }
  22791. createRenderPipeline( renderObject, promises ) {
  22792. const { object, material, geometry, pipeline } = renderObject;
  22793. const { vertexProgram, fragmentProgram } = pipeline;
  22794. const backend = this.backend;
  22795. const device = backend.device;
  22796. const utils = backend.utils;
  22797. const pipelineData = backend.get( pipeline );
  22798. // bind group layouts
  22799. const bindGroupLayouts = [];
  22800. for ( const bindGroup of renderObject.getBindings() ) {
  22801. const bindingsData = backend.get( bindGroup );
  22802. bindGroupLayouts.push( bindingsData.layout );
  22803. }
  22804. // vertex buffers
  22805. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  22806. // blending
  22807. let blending;
  22808. if ( material.transparent === true && material.blending !== NoBlending ) {
  22809. blending = this._getBlending( material );
  22810. }
  22811. // stencil
  22812. let stencilFront = {};
  22813. if ( material.stencilWrite === true ) {
  22814. stencilFront = {
  22815. compare: this._getStencilCompare( material ),
  22816. failOp: this._getStencilOperation( material.stencilFail ),
  22817. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  22818. passOp: this._getStencilOperation( material.stencilZPass )
  22819. };
  22820. }
  22821. const colorWriteMask = this._getColorWriteMask( material );
  22822. const targets = [];
  22823. if ( renderObject.context.textures !== null ) {
  22824. const textures = renderObject.context.textures;
  22825. for ( let i = 0; i < textures.length; i ++ ) {
  22826. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  22827. targets.push( {
  22828. format: colorFormat,
  22829. blend: blending,
  22830. writeMask: colorWriteMask
  22831. } );
  22832. }
  22833. } else {
  22834. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  22835. targets.push( {
  22836. format: colorFormat,
  22837. blend: blending,
  22838. writeMask: colorWriteMask
  22839. } );
  22840. }
  22841. const vertexModule = backend.get( vertexProgram ).module;
  22842. const fragmentModule = backend.get( fragmentProgram ).module;
  22843. const primitiveState = this._getPrimitiveState( object, geometry, material );
  22844. const depthCompare = this._getDepthCompare( material );
  22845. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  22846. const sampleCount = this._getSampleCount( renderObject.context );
  22847. const pipelineDescriptor = {
  22848. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  22849. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  22850. fragment: Object.assign( {}, fragmentModule, { targets } ),
  22851. primitive: primitiveState,
  22852. multisample: {
  22853. count: sampleCount,
  22854. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  22855. },
  22856. layout: device.createPipelineLayout( {
  22857. bindGroupLayouts
  22858. } )
  22859. };
  22860. const depthStencil = {};
  22861. const renderDepth = renderObject.context.depth;
  22862. const renderStencil = renderObject.context.stencil;
  22863. if ( renderDepth === true || renderStencil === true ) {
  22864. if ( renderDepth === true ) {
  22865. depthStencil.format = depthStencilFormat;
  22866. depthStencil.depthWriteEnabled = material.depthWrite;
  22867. depthStencil.depthCompare = depthCompare;
  22868. }
  22869. if ( renderStencil === true ) {
  22870. depthStencil.stencilFront = stencilFront;
  22871. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  22872. depthStencil.stencilReadMask = material.stencilFuncMask;
  22873. depthStencil.stencilWriteMask = material.stencilWriteMask;
  22874. }
  22875. pipelineDescriptor.depthStencil = depthStencil;
  22876. }
  22877. if ( promises === null ) {
  22878. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  22879. } else {
  22880. const p = new Promise( ( resolve /*, reject*/ ) => {
  22881. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  22882. pipelineData.pipeline = pipeline;
  22883. resolve();
  22884. } );
  22885. } );
  22886. promises.push( p );
  22887. }
  22888. }
  22889. createBundleEncoder( renderContext ) {
  22890. const backend = this.backend;
  22891. const { utils, device } = backend;
  22892. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  22893. const colorFormat = utils.getCurrentColorFormat( renderContext );
  22894. const sampleCount = this._getSampleCount( renderContext );
  22895. const descriptor = {
  22896. label: 'renderBundleEncoder',
  22897. colorFormats: [ colorFormat ],
  22898. depthStencilFormat,
  22899. sampleCount
  22900. };
  22901. return device.createRenderBundleEncoder( descriptor );
  22902. }
  22903. createComputePipeline( pipeline, bindings ) {
  22904. const backend = this.backend;
  22905. const device = backend.device;
  22906. const computeProgram = backend.get( pipeline.computeProgram ).module;
  22907. const pipelineGPU = backend.get( pipeline );
  22908. // bind group layouts
  22909. const bindGroupLayouts = [];
  22910. for ( const bindingsGroup of bindings ) {
  22911. const bindingsData = backend.get( bindingsGroup );
  22912. bindGroupLayouts.push( bindingsData.layout );
  22913. }
  22914. pipelineGPU.pipeline = device.createComputePipeline( {
  22915. compute: computeProgram,
  22916. layout: device.createPipelineLayout( {
  22917. bindGroupLayouts
  22918. } )
  22919. } );
  22920. }
  22921. _getBlending( material ) {
  22922. let color, alpha;
  22923. const blending = material.blending;
  22924. const blendSrc = material.blendSrc;
  22925. const blendDst = material.blendDst;
  22926. const blendEquation = material.blendEquation;
  22927. if ( blending === CustomBlending ) {
  22928. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  22929. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  22930. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  22931. color = {
  22932. srcFactor: this._getBlendFactor( blendSrc ),
  22933. dstFactor: this._getBlendFactor( blendDst ),
  22934. operation: this._getBlendOperation( blendEquation )
  22935. };
  22936. alpha = {
  22937. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  22938. dstFactor: this._getBlendFactor( blendDstAlpha ),
  22939. operation: this._getBlendOperation( blendEquationAlpha )
  22940. };
  22941. } else {
  22942. const premultipliedAlpha = material.premultipliedAlpha;
  22943. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  22944. color = {
  22945. srcFactor: srcRGB,
  22946. dstFactor: dstRGB,
  22947. operation: GPUBlendOperation.Add
  22948. };
  22949. alpha = {
  22950. srcFactor: srcAlpha,
  22951. dstFactor: dstAlpha,
  22952. operation: GPUBlendOperation.Add
  22953. };
  22954. };
  22955. if ( premultipliedAlpha ) {
  22956. switch ( blending ) {
  22957. case NormalBlending:
  22958. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  22959. break;
  22960. case AdditiveBlending:
  22961. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  22962. break;
  22963. case SubtractiveBlending:
  22964. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  22965. break;
  22966. case MultiplyBlending:
  22967. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  22968. break;
  22969. }
  22970. } else {
  22971. switch ( blending ) {
  22972. case NormalBlending:
  22973. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  22974. break;
  22975. case AdditiveBlending:
  22976. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  22977. break;
  22978. case SubtractiveBlending:
  22979. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  22980. break;
  22981. case MultiplyBlending:
  22982. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  22983. break;
  22984. }
  22985. }
  22986. }
  22987. if ( color !== undefined && alpha !== undefined ) {
  22988. return { color, alpha };
  22989. } else {
  22990. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  22991. }
  22992. }
  22993. _getBlendFactor( blend ) {
  22994. let blendFactor;
  22995. switch ( blend ) {
  22996. case ZeroFactor:
  22997. blendFactor = GPUBlendFactor.Zero;
  22998. break;
  22999. case OneFactor:
  23000. blendFactor = GPUBlendFactor.One;
  23001. break;
  23002. case SrcColorFactor:
  23003. blendFactor = GPUBlendFactor.Src;
  23004. break;
  23005. case OneMinusSrcColorFactor:
  23006. blendFactor = GPUBlendFactor.OneMinusSrc;
  23007. break;
  23008. case SrcAlphaFactor:
  23009. blendFactor = GPUBlendFactor.SrcAlpha;
  23010. break;
  23011. case OneMinusSrcAlphaFactor:
  23012. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  23013. break;
  23014. case DstColorFactor:
  23015. blendFactor = GPUBlendFactor.Dst;
  23016. break;
  23017. case OneMinusDstColorFactor:
  23018. blendFactor = GPUBlendFactor.OneMinusDstColor;
  23019. break;
  23020. case DstAlphaFactor:
  23021. blendFactor = GPUBlendFactor.DstAlpha;
  23022. break;
  23023. case OneMinusDstAlphaFactor:
  23024. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  23025. break;
  23026. case SrcAlphaSaturateFactor:
  23027. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  23028. break;
  23029. case BlendColorFactor:
  23030. blendFactor = GPUBlendFactor.Constant;
  23031. break;
  23032. case OneMinusBlendColorFactor:
  23033. blendFactor = GPUBlendFactor.OneMinusConstant;
  23034. break;
  23035. default:
  23036. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  23037. }
  23038. return blendFactor;
  23039. }
  23040. _getStencilCompare( material ) {
  23041. let stencilCompare;
  23042. const stencilFunc = material.stencilFunc;
  23043. switch ( stencilFunc ) {
  23044. case NeverStencilFunc:
  23045. stencilCompare = GPUCompareFunction.Never;
  23046. break;
  23047. case AlwaysStencilFunc:
  23048. stencilCompare = GPUCompareFunction.Always;
  23049. break;
  23050. case LessStencilFunc:
  23051. stencilCompare = GPUCompareFunction.Less;
  23052. break;
  23053. case LessEqualStencilFunc:
  23054. stencilCompare = GPUCompareFunction.LessEqual;
  23055. break;
  23056. case EqualStencilFunc:
  23057. stencilCompare = GPUCompareFunction.Equal;
  23058. break;
  23059. case GreaterEqualStencilFunc:
  23060. stencilCompare = GPUCompareFunction.GreaterEqual;
  23061. break;
  23062. case GreaterStencilFunc:
  23063. stencilCompare = GPUCompareFunction.Greater;
  23064. break;
  23065. case NotEqualStencilFunc:
  23066. stencilCompare = GPUCompareFunction.NotEqual;
  23067. break;
  23068. default:
  23069. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  23070. }
  23071. return stencilCompare;
  23072. }
  23073. _getStencilOperation( op ) {
  23074. let stencilOperation;
  23075. switch ( op ) {
  23076. case KeepStencilOp:
  23077. stencilOperation = GPUStencilOperation.Keep;
  23078. break;
  23079. case ZeroStencilOp:
  23080. stencilOperation = GPUStencilOperation.Zero;
  23081. break;
  23082. case ReplaceStencilOp:
  23083. stencilOperation = GPUStencilOperation.Replace;
  23084. break;
  23085. case InvertStencilOp:
  23086. stencilOperation = GPUStencilOperation.Invert;
  23087. break;
  23088. case IncrementStencilOp:
  23089. stencilOperation = GPUStencilOperation.IncrementClamp;
  23090. break;
  23091. case DecrementStencilOp:
  23092. stencilOperation = GPUStencilOperation.DecrementClamp;
  23093. break;
  23094. case IncrementWrapStencilOp:
  23095. stencilOperation = GPUStencilOperation.IncrementWrap;
  23096. break;
  23097. case DecrementWrapStencilOp:
  23098. stencilOperation = GPUStencilOperation.DecrementWrap;
  23099. break;
  23100. default:
  23101. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  23102. }
  23103. return stencilOperation;
  23104. }
  23105. _getBlendOperation( blendEquation ) {
  23106. let blendOperation;
  23107. switch ( blendEquation ) {
  23108. case AddEquation:
  23109. blendOperation = GPUBlendOperation.Add;
  23110. break;
  23111. case SubtractEquation:
  23112. blendOperation = GPUBlendOperation.Subtract;
  23113. break;
  23114. case ReverseSubtractEquation:
  23115. blendOperation = GPUBlendOperation.ReverseSubtract;
  23116. break;
  23117. case MinEquation:
  23118. blendOperation = GPUBlendOperation.Min;
  23119. break;
  23120. case MaxEquation:
  23121. blendOperation = GPUBlendOperation.Max;
  23122. break;
  23123. default:
  23124. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  23125. }
  23126. return blendOperation;
  23127. }
  23128. _getPrimitiveState( object, geometry, material ) {
  23129. const descriptor = {};
  23130. const utils = this.backend.utils;
  23131. descriptor.topology = utils.getPrimitiveTopology( object, material );
  23132. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  23133. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  23134. }
  23135. switch ( material.side ) {
  23136. case FrontSide:
  23137. descriptor.frontFace = GPUFrontFace.CCW;
  23138. descriptor.cullMode = GPUCullMode.Back;
  23139. break;
  23140. case BackSide:
  23141. descriptor.frontFace = GPUFrontFace.CCW;
  23142. descriptor.cullMode = GPUCullMode.Front;
  23143. break;
  23144. case DoubleSide:
  23145. descriptor.frontFace = GPUFrontFace.CCW;
  23146. descriptor.cullMode = GPUCullMode.None;
  23147. break;
  23148. default:
  23149. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  23150. break;
  23151. }
  23152. return descriptor;
  23153. }
  23154. _getColorWriteMask( material ) {
  23155. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  23156. }
  23157. _getDepthCompare( material ) {
  23158. let depthCompare;
  23159. if ( material.depthTest === false ) {
  23160. depthCompare = GPUCompareFunction.Always;
  23161. } else {
  23162. const depthFunc = material.depthFunc;
  23163. switch ( depthFunc ) {
  23164. case NeverDepth:
  23165. depthCompare = GPUCompareFunction.Never;
  23166. break;
  23167. case AlwaysDepth:
  23168. depthCompare = GPUCompareFunction.Always;
  23169. break;
  23170. case LessDepth:
  23171. depthCompare = GPUCompareFunction.Less;
  23172. break;
  23173. case LessEqualDepth:
  23174. depthCompare = GPUCompareFunction.LessEqual;
  23175. break;
  23176. case EqualDepth:
  23177. depthCompare = GPUCompareFunction.Equal;
  23178. break;
  23179. case GreaterEqualDepth:
  23180. depthCompare = GPUCompareFunction.GreaterEqual;
  23181. break;
  23182. case GreaterDepth:
  23183. depthCompare = GPUCompareFunction.Greater;
  23184. break;
  23185. case NotEqualDepth:
  23186. depthCompare = GPUCompareFunction.NotEqual;
  23187. break;
  23188. default:
  23189. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  23190. }
  23191. }
  23192. return depthCompare;
  23193. }
  23194. }
  23195. /*// debugger tools
  23196. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  23197. //*/
  23198. //
  23199. class WebGPUBackend extends Backend {
  23200. constructor( parameters = {} ) {
  23201. super( parameters );
  23202. this.isWebGPUBackend = true;
  23203. // some parameters require default values other than "undefined"
  23204. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  23205. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  23206. this.trackTimestamp = ( parameters.trackTimestamp === true );
  23207. this.device = null;
  23208. this.context = null;
  23209. this.colorBuffer = null;
  23210. this.defaultRenderPassdescriptor = null;
  23211. this.utils = new WebGPUUtils( this );
  23212. this.attributeUtils = new WebGPUAttributeUtils( this );
  23213. this.bindingUtils = new WebGPUBindingUtils( this );
  23214. this.pipelineUtils = new WebGPUPipelineUtils( this );
  23215. this.textureUtils = new WebGPUTextureUtils( this );
  23216. this.occludedResolveCache = new Map();
  23217. }
  23218. async init( renderer ) {
  23219. await super.init( renderer );
  23220. //
  23221. const parameters = this.parameters;
  23222. // create the device if it is not passed with parameters
  23223. let device;
  23224. if ( parameters.device === undefined ) {
  23225. const adapterOptions = {
  23226. powerPreference: parameters.powerPreference
  23227. };
  23228. const adapter = await navigator.gpu.requestAdapter( adapterOptions );
  23229. if ( adapter === null ) {
  23230. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  23231. }
  23232. // feature support
  23233. const features = Object.values( GPUFeatureName );
  23234. const supportedFeatures = [];
  23235. for ( const name of features ) {
  23236. if ( adapter.features.has( name ) ) {
  23237. supportedFeatures.push( name );
  23238. }
  23239. }
  23240. const deviceDescriptor = {
  23241. requiredFeatures: supportedFeatures,
  23242. requiredLimits: parameters.requiredLimits
  23243. };
  23244. device = await adapter.requestDevice( deviceDescriptor );
  23245. } else {
  23246. device = parameters.device;
  23247. }
  23248. device.lost.then( ( info ) => {
  23249. const deviceLossInfo = {
  23250. api: 'WebGPU',
  23251. message: info.message || 'Unknown reason',
  23252. reason: info.reason || null,
  23253. originalEvent: info
  23254. };
  23255. renderer.onDeviceLost( deviceLossInfo );
  23256. } );
  23257. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  23258. this.device = device;
  23259. this.context = context;
  23260. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  23261. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  23262. this.context.configure( {
  23263. device: this.device,
  23264. format: this.utils.getPreferredCanvasFormat(),
  23265. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  23266. alphaMode: alphaMode
  23267. } );
  23268. this.updateSize();
  23269. }
  23270. get coordinateSystem() {
  23271. return WebGPUCoordinateSystem;
  23272. }
  23273. async getArrayBufferAsync( attribute ) {
  23274. return await this.attributeUtils.getArrayBufferAsync( attribute );
  23275. }
  23276. getContext() {
  23277. return this.context;
  23278. }
  23279. _getDefaultRenderPassDescriptor() {
  23280. let descriptor = this.defaultRenderPassdescriptor;
  23281. if ( descriptor === null ) {
  23282. const renderer = this.renderer;
  23283. descriptor = {
  23284. colorAttachments: [ {
  23285. view: null
  23286. } ],
  23287. };
  23288. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  23289. descriptor.depthStencilAttachment = {
  23290. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  23291. };
  23292. }
  23293. const colorAttachment = descriptor.colorAttachments[ 0 ];
  23294. if ( this.renderer.samples > 0 ) {
  23295. colorAttachment.view = this.colorBuffer.createView();
  23296. } else {
  23297. colorAttachment.resolveTarget = undefined;
  23298. }
  23299. this.defaultRenderPassdescriptor = descriptor;
  23300. }
  23301. const colorAttachment = descriptor.colorAttachments[ 0 ];
  23302. if ( this.renderer.samples > 0 ) {
  23303. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  23304. } else {
  23305. colorAttachment.view = this.context.getCurrentTexture().createView();
  23306. }
  23307. return descriptor;
  23308. }
  23309. _getRenderPassDescriptor( renderContext ) {
  23310. const renderTarget = renderContext.renderTarget;
  23311. const renderTargetData = this.get( renderTarget );
  23312. let descriptors = renderTargetData.descriptors;
  23313. if ( descriptors === undefined ||
  23314. renderTargetData.width !== renderTarget.width ||
  23315. renderTargetData.height !== renderTarget.height ||
  23316. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  23317. renderTargetData.samples !== renderTarget.samples
  23318. ) {
  23319. descriptors = {};
  23320. renderTargetData.descriptors = descriptors;
  23321. // dispose
  23322. const onDispose = () => {
  23323. renderTarget.removeEventListener( 'dispose', onDispose );
  23324. this.delete( renderTarget );
  23325. };
  23326. renderTarget.addEventListener( 'dispose', onDispose );
  23327. }
  23328. const cacheKey = renderContext.getCacheKey();
  23329. let descriptor = descriptors[ cacheKey ];
  23330. if ( descriptor === undefined ) {
  23331. const textures = renderContext.textures;
  23332. const colorAttachments = [];
  23333. for ( let i = 0; i < textures.length; i ++ ) {
  23334. const textureData = this.get( textures[ i ] );
  23335. const textureView = textureData.texture.createView( {
  23336. baseMipLevel: renderContext.activeMipmapLevel,
  23337. mipLevelCount: 1,
  23338. baseArrayLayer: renderContext.activeCubeFace,
  23339. dimension: GPUTextureViewDimension.TwoD
  23340. } );
  23341. let view, resolveTarget;
  23342. if ( textureData.msaaTexture !== undefined ) {
  23343. view = textureData.msaaTexture.createView();
  23344. resolveTarget = textureView;
  23345. } else {
  23346. view = textureView;
  23347. resolveTarget = undefined;
  23348. }
  23349. colorAttachments.push( {
  23350. view,
  23351. resolveTarget,
  23352. loadOp: GPULoadOp.Load,
  23353. storeOp: GPUStoreOp.Store
  23354. } );
  23355. }
  23356. descriptor = {
  23357. colorAttachments,
  23358. };
  23359. if ( renderContext.depth ) {
  23360. const depthTextureData = this.get( renderContext.depthTexture );
  23361. const depthStencilAttachment = {
  23362. view: depthTextureData.texture.createView()
  23363. };
  23364. descriptor.depthStencilAttachment = depthStencilAttachment;
  23365. }
  23366. descriptors[ cacheKey ] = descriptor;
  23367. renderTargetData.width = renderTarget.width;
  23368. renderTargetData.height = renderTarget.height;
  23369. renderTargetData.samples = renderTarget.samples;
  23370. renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel;
  23371. }
  23372. return descriptor;
  23373. }
  23374. beginRender( renderContext ) {
  23375. const renderContextData = this.get( renderContext );
  23376. const device = this.device;
  23377. const occlusionQueryCount = renderContext.occlusionQueryCount;
  23378. let occlusionQuerySet;
  23379. if ( occlusionQueryCount > 0 ) {
  23380. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  23381. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  23382. // Get a reference to the array of objects with queries. The renderContextData property
  23383. // can be changed by another render pass before the buffer.mapAsyc() completes.
  23384. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  23385. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  23386. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  23387. //
  23388. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  23389. renderContextData.occlusionQuerySet = occlusionQuerySet;
  23390. renderContextData.occlusionQueryIndex = 0;
  23391. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  23392. renderContextData.lastOcclusionObject = null;
  23393. }
  23394. let descriptor;
  23395. if ( renderContext.textures === null ) {
  23396. descriptor = this._getDefaultRenderPassDescriptor();
  23397. } else {
  23398. descriptor = this._getRenderPassDescriptor( renderContext );
  23399. }
  23400. this.initTimestampQuery( renderContext, descriptor );
  23401. descriptor.occlusionQuerySet = occlusionQuerySet;
  23402. const depthStencilAttachment = descriptor.depthStencilAttachment;
  23403. if ( renderContext.textures !== null ) {
  23404. const colorAttachments = descriptor.colorAttachments;
  23405. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  23406. const colorAttachment = colorAttachments[ i ];
  23407. if ( renderContext.clearColor ) {
  23408. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  23409. colorAttachment.loadOp = GPULoadOp.Clear;
  23410. colorAttachment.storeOp = GPUStoreOp.Store;
  23411. } else {
  23412. colorAttachment.loadOp = GPULoadOp.Load;
  23413. colorAttachment.storeOp = GPUStoreOp.Store;
  23414. }
  23415. }
  23416. } else {
  23417. const colorAttachment = descriptor.colorAttachments[ 0 ];
  23418. if ( renderContext.clearColor ) {
  23419. colorAttachment.clearValue = renderContext.clearColorValue;
  23420. colorAttachment.loadOp = GPULoadOp.Clear;
  23421. colorAttachment.storeOp = GPUStoreOp.Store;
  23422. } else {
  23423. colorAttachment.loadOp = GPULoadOp.Load;
  23424. colorAttachment.storeOp = GPUStoreOp.Store;
  23425. }
  23426. }
  23427. //
  23428. if ( renderContext.depth ) {
  23429. if ( renderContext.clearDepth ) {
  23430. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  23431. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  23432. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  23433. } else {
  23434. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  23435. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  23436. }
  23437. }
  23438. if ( renderContext.stencil ) {
  23439. if ( renderContext.clearStencil ) {
  23440. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  23441. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  23442. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  23443. } else {
  23444. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  23445. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  23446. }
  23447. }
  23448. //
  23449. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  23450. const currentPass = encoder.beginRenderPass( descriptor );
  23451. //
  23452. renderContextData.descriptor = descriptor;
  23453. renderContextData.encoder = encoder;
  23454. renderContextData.currentPass = currentPass;
  23455. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  23456. renderContextData.renderBundles = [];
  23457. //
  23458. if ( renderContext.viewport ) {
  23459. this.updateViewport( renderContext );
  23460. }
  23461. if ( renderContext.scissor ) {
  23462. const { x, y, width, height } = renderContext.scissorValue;
  23463. currentPass.setScissorRect( x, y, width, height );
  23464. }
  23465. }
  23466. finishRender( renderContext ) {
  23467. const renderContextData = this.get( renderContext );
  23468. const occlusionQueryCount = renderContext.occlusionQueryCount;
  23469. if ( renderContextData.renderBundles.length > 0 ) {
  23470. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  23471. }
  23472. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  23473. renderContextData.currentPass.endOcclusionQuery();
  23474. }
  23475. renderContextData.currentPass.end();
  23476. if ( occlusionQueryCount > 0 ) {
  23477. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  23478. //
  23479. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  23480. if ( queryResolveBuffer === undefined ) {
  23481. queryResolveBuffer = this.device.createBuffer(
  23482. {
  23483. size: bufferSize,
  23484. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  23485. }
  23486. );
  23487. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  23488. }
  23489. //
  23490. const readBuffer = this.device.createBuffer(
  23491. {
  23492. size: bufferSize,
  23493. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  23494. }
  23495. );
  23496. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  23497. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  23498. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  23499. renderContextData.occlusionQueryBuffer = readBuffer;
  23500. //
  23501. this.resolveOccludedAsync( renderContext );
  23502. }
  23503. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  23504. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  23505. //
  23506. if ( renderContext.textures !== null ) {
  23507. const textures = renderContext.textures;
  23508. for ( let i = 0; i < textures.length; i ++ ) {
  23509. const texture = textures[ i ];
  23510. if ( texture.generateMipmaps === true ) {
  23511. this.textureUtils.generateMipmaps( texture );
  23512. }
  23513. }
  23514. }
  23515. }
  23516. isOccluded( renderContext, object ) {
  23517. const renderContextData = this.get( renderContext );
  23518. return renderContextData.occluded && renderContextData.occluded.has( object );
  23519. }
  23520. async resolveOccludedAsync( renderContext ) {
  23521. const renderContextData = this.get( renderContext );
  23522. // handle occlusion query results
  23523. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  23524. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  23525. const occluded = new WeakSet();
  23526. renderContextData.currentOcclusionQueryObjects = null;
  23527. renderContextData.currentOcclusionQueryBuffer = null;
  23528. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  23529. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  23530. const results = new BigUint64Array( buffer );
  23531. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  23532. if ( results[ i ] !== BigInt( 0 ) ) {
  23533. occluded.add( currentOcclusionQueryObjects[ i ] );
  23534. }
  23535. }
  23536. currentOcclusionQueryBuffer.destroy();
  23537. renderContextData.occluded = occluded;
  23538. }
  23539. }
  23540. updateViewport( renderContext ) {
  23541. const { currentPass } = this.get( renderContext );
  23542. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  23543. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  23544. }
  23545. clear( color, depth, stencil, renderTargetData = null ) {
  23546. const device = this.device;
  23547. const renderer = this.renderer;
  23548. let colorAttachments = [];
  23549. let depthStencilAttachment;
  23550. let clearValue;
  23551. let supportsDepth;
  23552. let supportsStencil;
  23553. if ( color ) {
  23554. const clearColor = this.getClearColor();
  23555. if ( this.renderer.alpha === true ) {
  23556. // premultiply alpha
  23557. const a = clearColor.a;
  23558. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  23559. } else {
  23560. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  23561. }
  23562. }
  23563. if ( renderTargetData === null ) {
  23564. supportsDepth = renderer.depth;
  23565. supportsStencil = renderer.stencil;
  23566. const descriptor = this._getDefaultRenderPassDescriptor();
  23567. if ( color ) {
  23568. colorAttachments = descriptor.colorAttachments;
  23569. const colorAttachment = colorAttachments[ 0 ];
  23570. colorAttachment.clearValue = clearValue;
  23571. colorAttachment.loadOp = GPULoadOp.Clear;
  23572. colorAttachment.storeOp = GPUStoreOp.Store;
  23573. }
  23574. if ( supportsDepth || supportsStencil ) {
  23575. depthStencilAttachment = descriptor.depthStencilAttachment;
  23576. }
  23577. } else {
  23578. supportsDepth = renderTargetData.depth;
  23579. supportsStencil = renderTargetData.stencil;
  23580. if ( color ) {
  23581. for ( const texture of renderTargetData.textures ) {
  23582. const textureData = this.get( texture );
  23583. const textureView = textureData.texture.createView();
  23584. let view, resolveTarget;
  23585. if ( textureData.msaaTexture !== undefined ) {
  23586. view = textureData.msaaTexture.createView();
  23587. resolveTarget = textureView;
  23588. } else {
  23589. view = textureView;
  23590. resolveTarget = undefined;
  23591. }
  23592. colorAttachments.push( {
  23593. view,
  23594. resolveTarget,
  23595. clearValue,
  23596. loadOp: GPULoadOp.Clear,
  23597. storeOp: GPUStoreOp.Store
  23598. } );
  23599. }
  23600. }
  23601. if ( supportsDepth || supportsStencil ) {
  23602. const depthTextureData = this.get( renderTargetData.depthTexture );
  23603. depthStencilAttachment = {
  23604. view: depthTextureData.texture.createView()
  23605. };
  23606. }
  23607. }
  23608. //
  23609. if ( supportsDepth ) {
  23610. if ( depth ) {
  23611. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  23612. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  23613. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  23614. } else {
  23615. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  23616. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  23617. }
  23618. }
  23619. //
  23620. if ( supportsStencil ) {
  23621. if ( stencil ) {
  23622. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  23623. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  23624. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  23625. } else {
  23626. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  23627. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  23628. }
  23629. }
  23630. //
  23631. const encoder = device.createCommandEncoder( {} );
  23632. const currentPass = encoder.beginRenderPass( {
  23633. colorAttachments,
  23634. depthStencilAttachment
  23635. } );
  23636. currentPass.end();
  23637. device.queue.submit( [ encoder.finish() ] );
  23638. }
  23639. // compute
  23640. beginCompute( computeGroup ) {
  23641. const groupGPU = this.get( computeGroup );
  23642. const descriptor = {};
  23643. this.initTimestampQuery( computeGroup, descriptor );
  23644. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  23645. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  23646. }
  23647. compute( computeGroup, computeNode, bindings, pipeline ) {
  23648. const { passEncoderGPU } = this.get( computeGroup );
  23649. // pipeline
  23650. const pipelineGPU = this.get( pipeline ).pipeline;
  23651. passEncoderGPU.setPipeline( pipelineGPU );
  23652. // bind groups
  23653. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  23654. const bindGroup = bindings[ i ];
  23655. const bindingsData = this.get( bindGroup );
  23656. passEncoderGPU.setBindGroup( i, bindingsData.group );
  23657. }
  23658. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  23659. const computeNodeData = this.get( computeNode );
  23660. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  23661. const { dispatchSize } = computeNodeData;
  23662. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  23663. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  23664. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  23665. } else {
  23666. dispatchSize.x = computeNode.dispatchCount;
  23667. }
  23668. passEncoderGPU.dispatchWorkgroups(
  23669. dispatchSize.x,
  23670. dispatchSize.y,
  23671. dispatchSize.z
  23672. );
  23673. }
  23674. finishCompute( computeGroup ) {
  23675. const groupData = this.get( computeGroup );
  23676. groupData.passEncoderGPU.end();
  23677. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  23678. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  23679. }
  23680. async waitForGPU() {
  23681. await this.device.queue.onSubmittedWorkDone();
  23682. }
  23683. // render object
  23684. draw( renderObject, info ) {
  23685. const { object, context, pipeline } = renderObject;
  23686. const bindings = renderObject.getBindings();
  23687. const renderContextData = this.get( context );
  23688. const pipelineGPU = this.get( pipeline ).pipeline;
  23689. const currentSets = renderContextData.currentSets;
  23690. const passEncoderGPU = renderContextData.currentPass;
  23691. const drawParams = renderObject.getDrawParameters();
  23692. if ( drawParams === null ) return;
  23693. // pipeline
  23694. if ( currentSets.pipeline !== pipelineGPU ) {
  23695. passEncoderGPU.setPipeline( pipelineGPU );
  23696. currentSets.pipeline = pipelineGPU;
  23697. }
  23698. // bind groups
  23699. const currentBindingGroups = currentSets.bindingGroups;
  23700. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  23701. const bindGroup = bindings[ i ];
  23702. const bindingsData = this.get( bindGroup );
  23703. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  23704. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  23705. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  23706. }
  23707. }
  23708. // attributes
  23709. const index = renderObject.getIndex();
  23710. const hasIndex = ( index !== null );
  23711. // index
  23712. if ( hasIndex === true ) {
  23713. if ( currentSets.index !== index ) {
  23714. const buffer = this.get( index ).buffer;
  23715. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  23716. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  23717. currentSets.index = index;
  23718. }
  23719. }
  23720. // vertex buffers
  23721. const vertexBuffers = renderObject.getVertexBuffers();
  23722. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  23723. const vertexBuffer = vertexBuffers[ i ];
  23724. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  23725. const buffer = this.get( vertexBuffer ).buffer;
  23726. passEncoderGPU.setVertexBuffer( i, buffer );
  23727. currentSets.attributes[ i ] = vertexBuffer;
  23728. }
  23729. }
  23730. // occlusion queries - handle multiple consecutive draw calls for an object
  23731. if ( renderContextData.occlusionQuerySet !== undefined ) {
  23732. const lastObject = renderContextData.lastOcclusionObject;
  23733. if ( lastObject !== object ) {
  23734. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  23735. passEncoderGPU.endOcclusionQuery();
  23736. renderContextData.occlusionQueryIndex ++;
  23737. }
  23738. if ( object.occlusionTest === true ) {
  23739. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  23740. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  23741. }
  23742. renderContextData.lastOcclusionObject = object;
  23743. }
  23744. }
  23745. // draw
  23746. if ( object.isBatchedMesh === true ) {
  23747. const starts = object._multiDrawStarts;
  23748. const counts = object._multiDrawCounts;
  23749. const drawCount = object._multiDrawCount;
  23750. const drawInstances = object._multiDrawInstances;
  23751. const bytesPerElement = hasIndex ? index.array.BYTES_PER_ELEMENT : 1;
  23752. for ( let i = 0; i < drawCount; i ++ ) {
  23753. const count = drawInstances ? drawInstances[ i ] : 1;
  23754. const firstInstance = count > 1 ? 0 : i;
  23755. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / bytesPerElement, 0, firstInstance );
  23756. }
  23757. } else if ( hasIndex === true ) {
  23758. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  23759. const indirect = renderObject.getIndirect();
  23760. if ( indirect !== null ) {
  23761. const buffer = this.get( indirect ).buffer;
  23762. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  23763. } else {
  23764. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  23765. }
  23766. info.update( object, indexCount, instanceCount );
  23767. } else {
  23768. const { vertexCount, instanceCount, firstVertex } = drawParams;
  23769. const indirect = renderObject.getIndirect();
  23770. if ( indirect !== null ) {
  23771. const buffer = this.get( indirect ).buffer;
  23772. passEncoderGPU.drawIndirect( buffer, 0 );
  23773. } else {
  23774. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  23775. }
  23776. info.update( object, vertexCount, instanceCount );
  23777. }
  23778. }
  23779. // cache key
  23780. needsRenderUpdate( renderObject ) {
  23781. const data = this.get( renderObject );
  23782. const { object, material } = renderObject;
  23783. const utils = this.utils;
  23784. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  23785. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  23786. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  23787. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  23788. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  23789. let needsUpdate = false;
  23790. if ( data.material !== material || data.materialVersion !== material.version ||
  23791. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  23792. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  23793. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  23794. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  23795. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  23796. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  23797. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  23798. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  23799. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  23800. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  23801. data.primitiveTopology !== primitiveTopology ||
  23802. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  23803. ) {
  23804. data.material = material; data.materialVersion = material.version;
  23805. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  23806. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  23807. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  23808. data.colorWrite = material.colorWrite;
  23809. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  23810. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  23811. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  23812. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  23813. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  23814. data.sampleCount = sampleCount;
  23815. data.colorSpace = colorSpace;
  23816. data.colorFormat = colorFormat;
  23817. data.depthStencilFormat = depthStencilFormat;
  23818. data.primitiveTopology = primitiveTopology;
  23819. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  23820. needsUpdate = true;
  23821. }
  23822. return needsUpdate;
  23823. }
  23824. getRenderCacheKey( renderObject ) {
  23825. const { object, material } = renderObject;
  23826. const utils = this.utils;
  23827. const renderContext = renderObject.context;
  23828. return [
  23829. material.transparent, material.blending, material.premultipliedAlpha,
  23830. material.blendSrc, material.blendDst, material.blendEquation,
  23831. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  23832. material.colorWrite,
  23833. material.depthWrite, material.depthTest, material.depthFunc,
  23834. material.stencilWrite, material.stencilFunc,
  23835. material.stencilFail, material.stencilZFail, material.stencilZPass,
  23836. material.stencilFuncMask, material.stencilWriteMask,
  23837. material.side,
  23838. utils.getSampleCountRenderContext( renderContext ),
  23839. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  23840. utils.getPrimitiveTopology( object, material ),
  23841. renderObject.getGeometryCacheKey(),
  23842. renderObject.clippingContextCacheKey
  23843. ].join();
  23844. }
  23845. // textures
  23846. createSampler( texture ) {
  23847. this.textureUtils.createSampler( texture );
  23848. }
  23849. destroySampler( texture ) {
  23850. this.textureUtils.destroySampler( texture );
  23851. }
  23852. createDefaultTexture( texture ) {
  23853. this.textureUtils.createDefaultTexture( texture );
  23854. }
  23855. createTexture( texture, options ) {
  23856. this.textureUtils.createTexture( texture, options );
  23857. }
  23858. updateTexture( texture, options ) {
  23859. this.textureUtils.updateTexture( texture, options );
  23860. }
  23861. generateMipmaps( texture ) {
  23862. this.textureUtils.generateMipmaps( texture );
  23863. }
  23864. destroyTexture( texture ) {
  23865. this.textureUtils.destroyTexture( texture );
  23866. }
  23867. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  23868. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  23869. }
  23870. async initTimestampQuery( renderContext, descriptor ) {
  23871. if ( ! this.trackTimestamp ) return;
  23872. const renderContextData = this.get( renderContext );
  23873. if ( ! renderContextData.timeStampQuerySet ) {
  23874. // Push an error scope to catch any errors during query set creation
  23875. this.device.pushErrorScope( 'out-of-memory' );
  23876. const timeStampQuerySet = await this.device.createQuerySet( { type: 'timestamp', count: 2, label: `timestamp_renderContext_${renderContext.id}` } );
  23877. // Pop the error scope and check for errors
  23878. const error = await this.device.popErrorScope();
  23879. if ( error ) {
  23880. if ( ! renderContextData.attemptingTimeStampQuerySetFailed ) {
  23881. console.error( `[GPUOutOfMemoryError][renderContext_${renderContext.id}]:\nFailed to create timestamp query set. This may be because timestamp queries are already running in other tabs.` );
  23882. renderContextData.attemptingTimeStampQuerySetFailed = true;
  23883. }
  23884. renderContextData.timeStampQuerySet = null; // Mark as unavailable
  23885. return;
  23886. }
  23887. const timestampWrites = {
  23888. querySet: timeStampQuerySet,
  23889. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  23890. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  23891. };
  23892. Object.assign( descriptor, { timestampWrites } );
  23893. renderContextData.timeStampQuerySet = timeStampQuerySet;
  23894. }
  23895. }
  23896. // timestamp utils
  23897. prepareTimestampBuffer( renderContext, encoder ) {
  23898. if ( ! this.trackTimestamp ) return;
  23899. const renderContextData = this.get( renderContext );
  23900. if ( ! renderContextData.timeStampQuerySet ) return;
  23901. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  23902. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  23903. renderContextData.currentTimestampQueryBuffers = {
  23904. resolveBuffer: this.device.createBuffer( {
  23905. label: 'timestamp resolve buffer',
  23906. size: size,
  23907. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  23908. } ),
  23909. resultBuffer: this.device.createBuffer( {
  23910. label: 'timestamp result buffer',
  23911. size: size,
  23912. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  23913. } ),
  23914. isMappingPending: false,
  23915. };
  23916. }
  23917. const { resolveBuffer, resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  23918. if ( isMappingPending === true ) return;
  23919. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  23920. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  23921. }
  23922. async resolveTimestampAsync( renderContext, type = 'render' ) {
  23923. if ( ! this.trackTimestamp ) return;
  23924. const renderContextData = this.get( renderContext );
  23925. if ( ! renderContextData.timeStampQuerySet ) return;
  23926. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  23927. const { resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  23928. if ( isMappingPending === true ) return;
  23929. renderContextData.currentTimestampQueryBuffers.isMappingPending = true;
  23930. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  23931. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  23932. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  23933. this.renderer.info.updateTimestamp( type, duration );
  23934. resultBuffer.unmap();
  23935. renderContextData.currentTimestampQueryBuffers.isMappingPending = false;
  23936. } );
  23937. }
  23938. // node builder
  23939. createNodeBuilder( object, renderer ) {
  23940. return new WGSLNodeBuilder( object, renderer );
  23941. }
  23942. // program
  23943. createProgram( program ) {
  23944. const programGPU = this.get( program );
  23945. programGPU.module = {
  23946. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  23947. entryPoint: 'main'
  23948. };
  23949. }
  23950. destroyProgram( program ) {
  23951. this.delete( program );
  23952. }
  23953. // pipelines
  23954. createRenderPipeline( renderObject, promises ) {
  23955. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  23956. }
  23957. createComputePipeline( computePipeline, bindings ) {
  23958. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  23959. }
  23960. beginBundle( renderContext ) {
  23961. const renderContextData = this.get( renderContext );
  23962. renderContextData._currentPass = renderContextData.currentPass;
  23963. renderContextData._currentSets = renderContextData.currentSets;
  23964. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  23965. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  23966. }
  23967. finishBundle( renderContext, bundle ) {
  23968. const renderContextData = this.get( renderContext );
  23969. const bundleEncoder = renderContextData.currentPass;
  23970. const bundleGPU = bundleEncoder.finish();
  23971. this.get( bundle ).bundleGPU = bundleGPU;
  23972. // restore render pass state
  23973. renderContextData.currentSets = renderContextData._currentSets;
  23974. renderContextData.currentPass = renderContextData._currentPass;
  23975. }
  23976. addBundle( renderContext, bundle ) {
  23977. const renderContextData = this.get( renderContext );
  23978. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  23979. }
  23980. // bindings
  23981. createBindings( bindGroup, bindings, cacheIndex, version ) {
  23982. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  23983. }
  23984. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  23985. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  23986. }
  23987. updateBinding( binding ) {
  23988. this.bindingUtils.updateBinding( binding );
  23989. }
  23990. // attributes
  23991. createIndexAttribute( attribute ) {
  23992. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  23993. }
  23994. createAttribute( attribute ) {
  23995. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  23996. }
  23997. createStorageAttribute( attribute ) {
  23998. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  23999. }
  24000. createIndirectStorageAttribute( attribute ) {
  24001. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  24002. }
  24003. updateAttribute( attribute ) {
  24004. this.attributeUtils.updateAttribute( attribute );
  24005. }
  24006. destroyAttribute( attribute ) {
  24007. this.attributeUtils.destroyAttribute( attribute );
  24008. }
  24009. // canvas
  24010. updateSize() {
  24011. this.colorBuffer = this.textureUtils.getColorBuffer();
  24012. this.defaultRenderPassdescriptor = null;
  24013. }
  24014. // utils public
  24015. getMaxAnisotropy() {
  24016. return 16;
  24017. }
  24018. hasFeature( name ) {
  24019. return this.device.features.has( name );
  24020. }
  24021. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  24022. let dstX = 0;
  24023. let dstY = 0;
  24024. let dstLayer = 0;
  24025. let srcX = 0;
  24026. let srcY = 0;
  24027. let srcLayer = 0;
  24028. let srcWidth = srcTexture.image.width;
  24029. let srcHeight = srcTexture.image.height;
  24030. if ( srcRegion !== null ) {
  24031. srcX = srcRegion.x;
  24032. srcY = srcRegion.y;
  24033. srcLayer = srcRegion.z || 0;
  24034. srcWidth = srcRegion.width;
  24035. srcHeight = srcRegion.height;
  24036. }
  24037. if ( dstPosition !== null ) {
  24038. dstX = dstPosition.x;
  24039. dstY = dstPosition.y;
  24040. dstLayer = dstPosition.z || 0;
  24041. }
  24042. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  24043. const sourceGPU = this.get( srcTexture ).texture;
  24044. const destinationGPU = this.get( dstTexture ).texture;
  24045. encoder.copyTextureToTexture(
  24046. {
  24047. texture: sourceGPU,
  24048. mipLevel: level,
  24049. origin: { x: srcX, y: srcY, z: srcLayer }
  24050. },
  24051. {
  24052. texture: destinationGPU,
  24053. mipLevel: level,
  24054. origin: { x: dstX, y: dstY, z: dstLayer }
  24055. },
  24056. [
  24057. srcWidth,
  24058. srcHeight,
  24059. 1
  24060. ]
  24061. );
  24062. this.device.queue.submit( [ encoder.finish() ] );
  24063. }
  24064. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  24065. const renderContextData = this.get( renderContext );
  24066. let sourceGPU = null;
  24067. if ( renderContext.renderTarget ) {
  24068. if ( texture.isDepthTexture ) {
  24069. sourceGPU = this.get( renderContext.depthTexture ).texture;
  24070. } else {
  24071. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  24072. }
  24073. } else {
  24074. if ( texture.isDepthTexture ) {
  24075. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  24076. } else {
  24077. sourceGPU = this.context.getCurrentTexture();
  24078. }
  24079. }
  24080. const destinationGPU = this.get( texture ).texture;
  24081. if ( sourceGPU.format !== destinationGPU.format ) {
  24082. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  24083. return;
  24084. }
  24085. let encoder;
  24086. if ( renderContextData.currentPass ) {
  24087. renderContextData.currentPass.end();
  24088. encoder = renderContextData.encoder;
  24089. } else {
  24090. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  24091. }
  24092. encoder.copyTextureToTexture(
  24093. {
  24094. texture: sourceGPU,
  24095. origin: { x: rectangle.x, y: rectangle.y, z: 0 }
  24096. },
  24097. {
  24098. texture: destinationGPU
  24099. },
  24100. [
  24101. rectangle.z,
  24102. rectangle.w
  24103. ]
  24104. );
  24105. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  24106. if ( renderContextData.currentPass ) {
  24107. const { descriptor } = renderContextData;
  24108. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  24109. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  24110. }
  24111. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  24112. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  24113. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  24114. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  24115. } else {
  24116. this.device.queue.submit( [ encoder.finish() ] );
  24117. }
  24118. }
  24119. }
  24120. class IESSpotLight extends SpotLight {
  24121. constructor( color, intensity, distance, angle, penumbra, decay ) {
  24122. super( color, intensity, distance, angle, penumbra, decay );
  24123. this.iesMap = null;
  24124. }
  24125. copy( source, recursive ) {
  24126. super.copy( source, recursive );
  24127. this.iesMap = source.iesMap;
  24128. return this;
  24129. }
  24130. }
  24131. class BasicNodeLibrary extends NodeLibrary {
  24132. constructor() {
  24133. super();
  24134. this.addLight( PointLightNode, PointLight );
  24135. this.addLight( DirectionalLightNode, DirectionalLight );
  24136. this.addLight( RectAreaLightNode, RectAreaLight );
  24137. this.addLight( SpotLightNode, SpotLight );
  24138. this.addLight( AmbientLightNode, AmbientLight );
  24139. this.addLight( HemisphereLightNode, HemisphereLight );
  24140. this.addLight( LightProbeNode, LightProbe );
  24141. this.addLight( IESSpotLightNode, IESSpotLight );
  24142. this.addToneMapping( linearToneMapping, LinearToneMapping );
  24143. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  24144. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  24145. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  24146. this.addToneMapping( agxToneMapping, AgXToneMapping );
  24147. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  24148. }
  24149. }
  24150. class WebGPURenderer extends Renderer {
  24151. constructor( parameters = {} ) {
  24152. let BackendClass;
  24153. if ( parameters.forceWebGL ) {
  24154. BackendClass = WebGLBackend;
  24155. } else {
  24156. BackendClass = WebGPUBackend;
  24157. parameters.getFallback = () => {
  24158. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  24159. return new WebGLBackend( parameters );
  24160. };
  24161. }
  24162. const backend = new BackendClass( parameters );
  24163. super( backend, parameters );
  24164. this.library = new BasicNodeLibrary();
  24165. this.isWebGPURenderer = true;
  24166. }
  24167. }
  24168. class BundleGroup extends Group {
  24169. constructor() {
  24170. super();
  24171. this.isBundleGroup = true;
  24172. this.type = 'BundleGroup';
  24173. this.static = true;
  24174. this.version = 0;
  24175. }
  24176. set needsUpdate( value ) {
  24177. if ( value === true ) this.version ++;
  24178. }
  24179. }
  24180. const _material = /*@__PURE__*/ new NodeMaterial();
  24181. const _quadMesh = /*@__PURE__*/ new QuadMesh( _material );
  24182. class PostProcessing {
  24183. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  24184. this.renderer = renderer;
  24185. this.outputNode = outputNode;
  24186. this.outputColorTransform = true;
  24187. this.needsUpdate = true;
  24188. _material.name = 'PostProcessing';
  24189. }
  24190. render() {
  24191. this.update();
  24192. const renderer = this.renderer;
  24193. const toneMapping = renderer.toneMapping;
  24194. const outputColorSpace = renderer.outputColorSpace;
  24195. renderer.toneMapping = NoToneMapping;
  24196. renderer.outputColorSpace = LinearSRGBColorSpace;
  24197. //
  24198. _quadMesh.render( renderer );
  24199. //
  24200. renderer.toneMapping = toneMapping;
  24201. renderer.outputColorSpace = outputColorSpace;
  24202. }
  24203. update() {
  24204. if ( this.needsUpdate === true ) {
  24205. const renderer = this.renderer;
  24206. const toneMapping = renderer.toneMapping;
  24207. const outputColorSpace = renderer.outputColorSpace;
  24208. _quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  24209. _quadMesh.material.needsUpdate = true;
  24210. this.needsUpdate = false;
  24211. }
  24212. }
  24213. async renderAsync() {
  24214. this.update();
  24215. const renderer = this.renderer;
  24216. const toneMapping = renderer.toneMapping;
  24217. const outputColorSpace = renderer.outputColorSpace;
  24218. renderer.toneMapping = NoToneMapping;
  24219. renderer.outputColorSpace = LinearSRGBColorSpace;
  24220. //
  24221. await _quadMesh.renderAsync( renderer );
  24222. //
  24223. renderer.toneMapping = toneMapping;
  24224. renderer.outputColorSpace = outputColorSpace;
  24225. }
  24226. }
  24227. // renderer state
  24228. function saveRendererState( renderer, state = {} ) {
  24229. state.toneMapping = renderer.toneMapping;
  24230. state.toneMappingExposure = renderer.toneMappingExposure;
  24231. state.outputColorSpace = renderer.outputColorSpace;
  24232. state.renderTarget = renderer.getRenderTarget();
  24233. state.activeCubeFace = renderer.getActiveCubeFace();
  24234. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  24235. state.renderObjectFunction = renderer.getRenderObjectFunction();
  24236. state.pixelRatio = renderer.getPixelRatio();
  24237. state.mrt = renderer.getMRT();
  24238. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  24239. state.clearAlpha = renderer.getClearAlpha();
  24240. state.autoClear = renderer.autoClear;
  24241. state.scissorTest = renderer.getScissorTest();
  24242. return state;
  24243. }
  24244. function resetRendererState( renderer, state ) {
  24245. state = saveRendererState( renderer, state );
  24246. renderer.setMRT( null );
  24247. renderer.setRenderObjectFunction( null );
  24248. renderer.setClearColor( 0x000000, 1 );
  24249. renderer.autoClear = true;
  24250. return state;
  24251. }
  24252. function restoreRendererState( renderer, state ) {
  24253. renderer.toneMapping = state.toneMapping;
  24254. renderer.toneMappingExposure = state.toneMappingExposure;
  24255. renderer.outputColorSpace = state.outputColorSpace;
  24256. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  24257. renderer.setRenderObjectFunction( state.renderObjectFunction );
  24258. renderer.setPixelRatio( state.pixelRatio );
  24259. renderer.setMRT( state.mrt );
  24260. renderer.setClearColor( state.clearColor, state.clearAlpha );
  24261. renderer.autoClear = state.autoClear;
  24262. renderer.setScissorTest( state.scissorTest );
  24263. }
  24264. // renderer and scene state
  24265. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  24266. state = saveRendererState( renderer, state );
  24267. state.background = scene.background;
  24268. state.backgroundNode = scene.backgroundNode;
  24269. state.overrideMaterial = scene.overrideMaterial;
  24270. return state;
  24271. }
  24272. function resetRendererAndSceneState( renderer, scene, state ) {
  24273. state = saveRendererAndSceneState( renderer, scene, state );
  24274. scene.background = null;
  24275. scene.backgroundNode = null;
  24276. scene.overrideMaterial = null;
  24277. return state;
  24278. }
  24279. function restoreRendererAndSceneState( renderer, scene, state ) {
  24280. restoreRendererState( renderer, state );
  24281. scene.background = state.background;
  24282. scene.backgroundNode = state.backgroundNode;
  24283. scene.overrideMaterial = state.overrideMaterial;
  24284. }
  24285. var PostProcessingUtils = /*#__PURE__*/Object.freeze({
  24286. __proto__: null,
  24287. resetRendererAndSceneState: resetRendererAndSceneState,
  24288. resetRendererState: resetRendererState,
  24289. restoreRendererAndSceneState: restoreRendererAndSceneState,
  24290. restoreRendererState: restoreRendererState,
  24291. saveRendererAndSceneState: saveRendererAndSceneState,
  24292. saveRendererState: saveRendererState
  24293. });
  24294. class StorageTexture extends Texture {
  24295. constructor( width = 1, height = 1 ) {
  24296. super();
  24297. this.image = { width, height };
  24298. this.magFilter = LinearFilter;
  24299. this.minFilter = LinearFilter;
  24300. this.isStorageTexture = true;
  24301. }
  24302. }
  24303. class StorageBufferAttribute extends BufferAttribute {
  24304. constructor( array, itemSize, typeClass = Float32Array ) {
  24305. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  24306. super( array, itemSize );
  24307. this.isStorageBufferAttribute = true;
  24308. }
  24309. }
  24310. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  24311. constructor( array, itemSize, typeClass = Float32Array ) {
  24312. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  24313. super( array, itemSize );
  24314. this.isStorageInstancedBufferAttribute = true;
  24315. }
  24316. }
  24317. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  24318. constructor( array, itemSize ) {
  24319. super( array, itemSize, Uint32Array );
  24320. this.isIndirectStorageBufferAttribute = true;
  24321. }
  24322. }
  24323. class NodeLoader extends Loader {
  24324. constructor( manager ) {
  24325. super( manager );
  24326. this.textures = {};
  24327. this.nodes = {};
  24328. }
  24329. load( url, onLoad, onProgress, onError ) {
  24330. const loader = new FileLoader( this.manager );
  24331. loader.setPath( this.path );
  24332. loader.setRequestHeader( this.requestHeader );
  24333. loader.setWithCredentials( this.withCredentials );
  24334. loader.load( url, ( text ) => {
  24335. try {
  24336. onLoad( this.parse( JSON.parse( text ) ) );
  24337. } catch ( e ) {
  24338. if ( onError ) {
  24339. onError( e );
  24340. } else {
  24341. console.error( e );
  24342. }
  24343. this.manager.itemError( url );
  24344. }
  24345. }, onProgress, onError );
  24346. }
  24347. parseNodes( json ) {
  24348. const nodes = {};
  24349. if ( json !== undefined ) {
  24350. for ( const nodeJSON of json ) {
  24351. const { uuid, type } = nodeJSON;
  24352. nodes[ uuid ] = this.createNodeFromType( type );
  24353. nodes[ uuid ].uuid = uuid;
  24354. }
  24355. const meta = { nodes, textures: this.textures };
  24356. for ( const nodeJSON of json ) {
  24357. nodeJSON.meta = meta;
  24358. const node = nodes[ nodeJSON.uuid ];
  24359. node.deserialize( nodeJSON );
  24360. delete nodeJSON.meta;
  24361. }
  24362. }
  24363. return nodes;
  24364. }
  24365. parse( json ) {
  24366. const node = this.createNodeFromType( json.type );
  24367. node.uuid = json.uuid;
  24368. const nodes = this.parseNodes( json.nodes );
  24369. const meta = { nodes, textures: this.textures };
  24370. json.meta = meta;
  24371. node.deserialize( json );
  24372. delete json.meta;
  24373. return node;
  24374. }
  24375. setTextures( value ) {
  24376. this.textures = value;
  24377. return this;
  24378. }
  24379. setNodes( value ) {
  24380. this.nodes = value;
  24381. return this;
  24382. }
  24383. createNodeFromType( type ) {
  24384. if ( this.nodes[ type ] === undefined ) {
  24385. console.error( 'THREE.NodeLoader: Node type not found:', type );
  24386. return float();
  24387. }
  24388. return nodeObject( new this.nodes[ type ]() );
  24389. }
  24390. }
  24391. class NodeMaterialLoader extends MaterialLoader {
  24392. constructor( manager ) {
  24393. super( manager );
  24394. this.nodes = {};
  24395. this.nodeMaterials = {};
  24396. }
  24397. parse( json ) {
  24398. const material = super.parse( json );
  24399. const nodes = this.nodes;
  24400. const inputNodes = json.inputNodes;
  24401. for ( const property in inputNodes ) {
  24402. const uuid = inputNodes[ property ];
  24403. material[ property ] = nodes[ uuid ];
  24404. }
  24405. return material;
  24406. }
  24407. setNodes( value ) {
  24408. this.nodes = value;
  24409. return this;
  24410. }
  24411. setNodeMaterials( value ) {
  24412. this.nodeMaterials = value;
  24413. return this;
  24414. }
  24415. createMaterialFromType( type ) {
  24416. const materialClass = this.nodeMaterials[ type ];
  24417. if ( materialClass !== undefined ) {
  24418. return new materialClass();
  24419. }
  24420. return super.createMaterialFromType( type );
  24421. }
  24422. }
  24423. class NodeObjectLoader extends ObjectLoader {
  24424. constructor( manager ) {
  24425. super( manager );
  24426. this.nodes = {};
  24427. this.nodeMaterials = {};
  24428. this._nodesJSON = null;
  24429. }
  24430. setNodes( value ) {
  24431. this.nodes = value;
  24432. return this;
  24433. }
  24434. setNodeMaterials( value ) {
  24435. this.nodeMaterials = value;
  24436. return this;
  24437. }
  24438. parse( json, onLoad ) {
  24439. this._nodesJSON = json.nodes;
  24440. const data = super.parse( json, onLoad );
  24441. this._nodesJSON = null; // dispose
  24442. return data;
  24443. }
  24444. parseNodes( json, textures ) {
  24445. if ( json !== undefined ) {
  24446. const loader = new NodeLoader();
  24447. loader.setNodes( this.nodes );
  24448. loader.setTextures( textures );
  24449. return loader.parseNodes( json );
  24450. }
  24451. return {};
  24452. }
  24453. parseMaterials( json, textures ) {
  24454. const materials = {};
  24455. if ( json !== undefined ) {
  24456. const nodes = this.parseNodes( this._nodesJSON, textures );
  24457. const loader = new NodeMaterialLoader();
  24458. loader.setTextures( textures );
  24459. loader.setNodes( nodes );
  24460. loader.setNodeMaterials( this.nodeMaterials );
  24461. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24462. const data = json[ i ];
  24463. materials[ data.uuid ] = loader.parse( data );
  24464. }
  24465. }
  24466. return materials;
  24467. }
  24468. }
  24469. class ClippingGroup extends Group {
  24470. constructor() {
  24471. super();
  24472. this.isClippingGroup = true;
  24473. this.clippingPlanes = [];
  24474. this.enabled = true;
  24475. this.clipIntersection = false;
  24476. this.clipShadows = false;
  24477. }
  24478. }
  24479. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayElementNode, AssignNode, AttributeNode, BRDF_GGX, BRDF_Lambert, BackSide, BasicEnvironmentNode, BatchNode, BoxGeometry, Break, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, CacheNode, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, CodeNode, Color, ColorManagement, ColorSpaceNode, ComputeNode, ConstNode, ContextNode, Continue, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, DFGApprox, D_GGX, DataArrayTexture, DataTexture, DecrementStencilOp, DecrementWrapStencilOp, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightNode, Discard, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EPSILON, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, F_Schlick, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fn, FogExp2Node, FogNode, FogRangeNode, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, Group, HalfFloatType, HemisphereLight, HemisphereLightNode, IESSpotLight, IESSpotLightNode, INFINITY, If, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InstanceNode, InstancedBufferAttribute, InstancedInterleavedBuffer, InstancedMeshNode, InstancedPointsNodeMaterial, IntType, InterleavedBuffer, InterleavedBufferAttribute, InvertStencilOp, IrradianceNode, JoinNode, KeepStencilOp, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, LightProbe, LightProbeNode, Lighting, LightingContextNode, LightingModel, LightingNode, LightsNode, Line2NodeMaterial, LineBasicMaterial, LineBasicNodeMaterial, LineDashedMaterial, LineDashedNodeMaterial, LinearFilter, LinearMipMapLinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, Loader, Loop, LoopNode, LuminanceAlphaFormat, LuminanceFormat, MRTNode, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, ModelViewProjectionNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap$1 as PCFShadowMap, PI, PI2, PMREMGenerator, PMREMNode, ParameterNode, PassNode, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PointLight, PointLightNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, PostProcessingUtils, PosterizeNode, PropertyNode, QuadMesh, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBFormat, RGBIntegerFormat, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RepeatWrapping, ReplaceStencilOp, Return, ReverseSubtractEquation, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, Schlick_to_F0, ScreenNode, ScriptableNode, ScriptableNodeResources, ScriptableValueNode, SetNode, ShaderNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, ShortType, SkinningNode, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticDrawUsage, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, SubtractEquation, SubtractiveBlending, TBNViewMatrix, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TriplanarTexturesNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, V_GGX_SmithCorrelated, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, ZeroFactor, ZeroStencilOp, abs, acesFilmicToneMapping, acos, add, addMethodChaining, addNodeElement, agxToneMapping, all, alphaT, and, anisotropy, anisotropyB, anisotropyT, any, append, arrayBuffer, asin, assign, atan, atan2, atomicAdd, atomicAnd, atomicFunc, atomicMax, atomicMin, atomicOr, atomicStore, atomicSub, atomicXor, attenuationColor, attenuationDistance, attribute, backgroundBlurriness, backgroundIntensity, backgroundRotation, batch, billboarding, bitAnd, bitNot, bitOr, bitXor, bitangentGeometry, bitangentLocal, bitangentView, bitangentWorld, bitcast, blendNormal, blur, bool, buffer, bufferAttribute, bumpMap, burn, bvec2, bvec3, bvec4, bypass, cache, call, cameraFar, cameraNear, cameraNormalMatrix, cameraPosition, cameraProjectionMatrix, cameraProjectionMatrixInverse, cameraViewMatrix, cameraWorldMatrix, cbrt, cdl, ceil, checker, cineonToneMapping, clamp, clearcoat, clearcoatRoughness, code, color, colorSpaceToWorking, colorToDirection, compute, cond, context, convert, convertColorSpace, convertToTexture, cos, createCanvasElement, cross, cubeTexture, dFdx, dFdy, dashSize, defaultBuildStages, defaultShaderStages, defined, degrees, deltaTime, densityFog, depth, depthPass, difference, diffuseColor, directPointLight, directionToColor, dispersion, distance, div, dodge, dot, drawIndex, dynamicBufferAttribute, element, emissive, equal, equals, equirectUV, exp, exp2, expression, faceDirection, faceForward, float, floor, fog, fract, frameGroup, frameId, frontFacing, fwidth, gain, gapSize, getConstNodeType, getCurrentStack, getDirection, getDistanceAttenuation, getGeometryRoughness, getNormalFromDepth, getParallaxCorrectNormal, getRoughness, getScreenPosition, getShIrradianceAt, getTextureIndex, getViewPosition, glsl, glslFn, grayscale, greaterThan, greaterThanEqual, hash, highPrecisionModelNormalViewMatrix, highPrecisionModelViewMatrix, hue, instance, instanceIndex, instancedBufferAttribute, instancedDynamicBufferAttribute, instancedMesh, int, inverseSqrt, invocationLocalIndex, invocationSubgroupIndex, ior, iridescence, iridescenceIOR, iridescenceThickness, ivec2, ivec3, ivec4, js, label, length, lengthSq, lessThan, lessThanEqual, lightPosition, lightTargetDirection, lightTargetPosition, lightViewPosition, lightingContext, lights, linearDepth, linearToneMapping, localId, log, log2, logarithmicDepthToViewZ, loop, luminance, mat2, mat3, mat4, matcapUV, materialAOMap, materialAlphaTest, materialAnisotropy, materialAnisotropyVector, materialAttenuationColor, materialAttenuationDistance, materialClearcoat, materialClearcoatNormal, materialClearcoatRoughness, materialColor, materialDispersion, materialEmissive, materialIOR, materialIridescence, materialIridescenceIOR, materialIridescenceThickness, materialLightMap, materialLineDashOffset, materialLineDashSize, materialLineGapSize, materialLineScale, materialLineWidth, materialMetalness, materialNormal, materialOpacity, materialPointWidth, materialReference, materialReflectivity, materialRefractionRatio, materialRotation, materialRoughness, materialSheen, materialSheenRoughness, materialShininess, materialSpecular, materialSpecularColor, materialSpecularIntensity, materialSpecularStrength, materialThickness, materialTransmission, max$1 as max, maxMipLevel, metalness, min$1 as min, mix, mixElement, mod, modInt, modelDirection, modelNormalMatrix, modelPosition, modelScale, modelViewMatrix, modelViewPosition, modelViewProjection, modelWorldMatrix, modelWorldMatrixInverse, morphReference, mrt, mul, mx_aastep, mx_cell_noise_float, mx_contrast, mx_fractal_noise_float, mx_fractal_noise_vec2, mx_fractal_noise_vec3, mx_fractal_noise_vec4, mx_hsvtorgb, mx_noise_float, mx_noise_vec3, mx_noise_vec4, mx_ramplr, mx_ramptb, mx_rgbtohsv, mx_safepower, mx_splitlr, mx_splittb, mx_srgb_texture_to_lin_rec709, mx_transform_uv, mx_worley_noise_float, mx_worley_noise_vec2, mx_worley_noise_vec3, negate, neutralToneMapping, nodeArray, nodeImmutable, nodeObject, nodeObjects, nodeProxy, normalFlat, normalGeometry, normalLocal, normalMap, normalView, normalWorld, normalize, not, notEqual, numWorkgroups, objectDirection, objectGroup, objectPosition, objectScale, objectViewPosition, objectWorldMatrix, oneMinus, or, orthographicDepthToViewZ, oscSawtooth, oscSine, oscSquare, oscTriangle, output, outputStruct, overlay, overloadingFn, parabola, parallaxDirection, parallaxUV, parameter, pass, passTexture, pcurve, perspectiveDepthToViewZ, pmremTexture, pointUV, pointWidth, positionGeometry, positionLocal, positionPrevious, positionView, positionViewDirection, positionWorld, positionWorldDirection, posterize, pow, pow2, pow3, pow4, property, radians, rand, range, rangeFog, reciprocal, reference, referenceBuffer, reflect, reflectVector, reflectView, reflector, refract, refractVector, refractView, reinhardToneMapping, remainder, remap, remapClamp, renderGroup, renderOutput, rendererReference, rotate, rotateUV, roughness, round, rtt, sRGBTransferEOTF, sRGBTransferOETF, sampler, saturate, saturation, screen, screenCoordinate, screenSize, screenUV, scriptable, scriptableValue, select, setCurrentStack, shaderStages, shadow, sharedUniformGroup, sheen, sheenRoughness, shiftLeft, shiftRight, shininess, sign, sin, sinc, skinning, skinningReference, smoothstep, smoothstepElement, specularColor, specularF90, spherizeUV, split, spritesheetUV, sqrt, stack, step, storage, storageBarrier, storageObject, storageTexture, string, sub, subgroupIndex, subgroupSize, tan, tangentGeometry, tangentLocal, tangentView, tangentWorld, temp, texture, texture3D, textureBarrier, textureBicubic, textureCubeUV, textureLoad, textureSize, textureStore, thickness, threshold, time, timerDelta, timerGlobal, timerLocal, toOutputColorSpace, toWorkingColorSpace, toneMapping, toneMappingExposure, toonOutlinePass, transformDirection, transformNormal, transformNormalToView, transformedBentNormalView, transformedBitangentView, transformedBitangentWorld, transformedClearcoatNormalView, transformedNormalView, transformedNormalWorld, transformedTangentView, transformedTangentWorld, transmission, transpose, tri, tri3, triNoise3D, triplanarTexture, triplanarTextures, trunc, tslFn, uint, uniform, uniformArray, uniformGroup, uniforms, userData, uv, uvec2, uvec3, uvec4, varying, varyingProperty, vec2, vec3, vec4, vectorComponents, velocity, vertexColor, vertexIndex, vibrance, viewZToLogarithmicDepth, viewZToOrthographicDepth, viewZToPerspectiveDepth, viewport, viewportBottomLeft, viewportCoordinate, viewportDepthTexture, viewportLinearDepth, viewportMipTexture, viewportResolution, viewportSafeUV, viewportSharedTexture, viewportSize, viewportTexture, viewportTopLeft, viewportUV, wgsl, wgslFn, workgroupArray, workgroupBarrier, workgroupId, workingToColorSpace, xor };
粤ICP备19079148号