three.webgpu.js 1.5 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664
  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, WebGLCoordinateSystem, WebGPUCoordinateSystem, ColorManagement, SRGBTransfer, NoToneMapping, StaticDrawUsage, InterleavedBuffer, DynamicDrawUsage, InterleavedBufferAttribute, NoColorSpace, UnsignedIntType, IntType, BackSide, CubeReflectionMapping, CubeRefractionMapping, TangentSpaceNormalMap, ObjectSpaceNormalMap, InstancedInterleavedBuffer, InstancedBufferAttribute, DataArrayTexture, FloatType, FramebufferTexture, LinearMipmapLinearFilter, DepthTexture, Material, NormalBlending, PointsMaterial, LineBasicMaterial, LineDashedMaterial, NoBlending, MeshNormalMaterial, WebGLCubeRenderTarget, BoxGeometry, Mesh, Scene, LinearFilter, CubeCamera, CubeTexture, EquirectangularReflectionMapping, EquirectangularRefractionMapping, AddOperation, MixOperation, MultiplyOperation, MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial, Texture, MeshStandardMaterial, MeshPhysicalMaterial, MeshToonMaterial, MeshMatcapMaterial, SpriteMaterial, ShadowMaterial, Uint32BufferAttribute, Uint16BufferAttribute, DoubleSide, DepthStencilFormat, DepthFormat, UnsignedInt248Type, UnsignedByteType, RenderTarget, Plane, Object3D, HalfFloatType, LinearMipMapLinearFilter, OrthographicCamera, BufferGeometry, Float32BufferAttribute, BufferAttribute, UVMapping, Euler, LinearSRGBColorSpace, LessCompare, VSMShadowMap, RGFormat, BasicShadowMap, SphereGeometry, CubeUVReflectionMapping, PerspectiveCamera, RGBAFormat, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, REVISION, SRGBColorSpace, PCFShadowMap, FrontSide, Frustum, DataTexture, RedIntegerFormat, RedFormat, RGIntegerFormat, RGBIntegerFormat, RGBFormat, RGBAIntegerFormat, UnsignedShortType, ByteType, ShortType, createCanvasElement, AddEquation, SubtractEquation, ReverseSubtractEquation, ZeroFactor, OneFactor, SrcColorFactor, SrcAlphaFactor, SrcAlphaSaturateFactor, DstColorFactor, DstAlphaFactor, OneMinusSrcColorFactor, OneMinusSrcAlphaFactor, OneMinusDstColorFactor, OneMinusDstAlphaFactor, CullFaceNone, CullFaceBack, CullFaceFront, CustomBlending, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt5999Type, AlphaFormat, LuminanceFormat, LuminanceAlphaFormat, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGBA_ETC2_EAC_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_10x10_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_BPTC_Format, RED_RGTC1_Format, SIGNED_RED_RGTC1_Format, RED_GREEN_RGTC2_Format, SIGNED_RED_GREEN_RGTC2_Format, RepeatWrapping, ClampToEdgeWrapping, MirroredRepeatWrapping, NearestFilter, NearestMipmapNearestFilter, NeverCompare, AlwaysCompare, LessEqualCompare, EqualCompare, GreaterEqualCompare, GreaterCompare, NotEqualCompare, warnOnce, NotEqualStencilFunc, GreaterStencilFunc, GreaterEqualStencilFunc, EqualStencilFunc, LessEqualStencilFunc, LessStencilFunc, AlwaysStencilFunc, NeverStencilFunc, DecrementWrapStencilOp, IncrementWrapStencilOp, DecrementStencilOp, IncrementStencilOp, InvertStencilOp, ReplaceStencilOp, ZeroStencilOp, KeepStencilOp, MaxEquation, MinEquation, SpotLight, PointLight, DirectionalLight, RectAreaLight, AmbientLight, HemisphereLight, LightProbe, LinearToneMapping, ReinhardToneMapping, CineonToneMapping, ACESFilmicToneMapping, AgXToneMapping, NeutralToneMapping, Group, Loader, FileLoader, MaterialLoader, ObjectLoader } from './three.core.js';
  7. export { AdditiveAnimationBlendMode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CircleGeometry, Clock, ColorKeyframeTrack, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeTextureLoader, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceFrontBack, Curve, CurvePath, CustomToneMapping, CylinderGeometry, Cylindrical, Data3DTexture, DataTextureLoader, DataUtils, DefaultLoadingManager, DetachedBindMode, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DynamicCopyUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, ExtrudeGeometry, Fog, FogExp2, GLBufferAttribute, GLSL1, GLSL3, GridHelper, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, InstancedBufferGeometry, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, KeyframeTrack, LOD, LatheGeometry, Layers, Light, Line, Line3, LineCurve, LineCurve3, LineLoop, LineSegments, LinearInterpolant, LinearMipMapNearestFilter, LinearTransfer, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, Matrix2, MeshDepthMaterial, MeshDistanceMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NormalAnimationBlendMode, NumberKeyframeTrack, OctahedronGeometry, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, PCFSoftShadowMap, Path, PlaneGeometry, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RenderTarget3D, RenderTargetArray, RingGeometry, ShaderMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, Spherical, SphericalHarmonics3, SplineCurve, SpotLightHelper, Sprite, StaticCopyUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureUtils, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLRenderTarget, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding } from './three.core.js';
  8. const refreshUniforms = [
  9. 'alphaMap',
  10. 'alphaTest',
  11. 'anisotropy',
  12. 'anisotropyMap',
  13. 'anisotropyRotation',
  14. 'aoMap',
  15. 'attenuationColor',
  16. 'attenuationDistance',
  17. 'bumpMap',
  18. 'clearcoat',
  19. 'clearcoatMap',
  20. 'clearcoatNormalMap',
  21. 'clearcoatNormalScale',
  22. 'clearcoatRoughness',
  23. 'color',
  24. 'dispersion',
  25. 'displacementMap',
  26. 'emissive',
  27. 'emissiveMap',
  28. 'envMap',
  29. 'gradientMap',
  30. 'ior',
  31. 'iridescence',
  32. 'iridescenceIOR',
  33. 'iridescenceMap',
  34. 'iridescenceThicknessMap',
  35. 'lightMap',
  36. 'map',
  37. 'matcap',
  38. 'metalness',
  39. 'metalnessMap',
  40. 'normalMap',
  41. 'normalScale',
  42. 'opacity',
  43. 'roughness',
  44. 'roughnessMap',
  45. 'sheen',
  46. 'sheenColor',
  47. 'sheenColorMap',
  48. 'sheenRoughnessMap',
  49. 'shininess',
  50. 'specular',
  51. 'specularColor',
  52. 'specularColorMap',
  53. 'specularIntensity',
  54. 'specularIntensityMap',
  55. 'specularMap',
  56. 'thickness',
  57. 'transmission',
  58. 'transmissionMap'
  59. ];
  60. /**
  61. * This class is used by {@link WebGPURenderer} as management component.
  62. * It's primary purpose is to determine whether render objects require a
  63. * refresh right before they are going to be rendered or not.
  64. */
  65. class NodeMaterialObserver {
  66. /**
  67. * Constructs a new node material observer.
  68. *
  69. * @param {NodeBuilder} builder - The node builder.
  70. */
  71. constructor( builder ) {
  72. /**
  73. * A node material can be used by more than one render object so the
  74. * monitor must maintain a list of render objects.
  75. *
  76. * @type {WeakMap<RenderObject,Object>}
  77. */
  78. this.renderObjects = new WeakMap();
  79. /**
  80. * Whether the material uses node objects or not.
  81. *
  82. * @type {Boolean}
  83. */
  84. this.hasNode = this.containsNode( builder );
  85. /**
  86. * Whether the node builder's 3D object is animated or not.
  87. *
  88. * @type {Boolean}
  89. */
  90. this.hasAnimation = builder.object.isSkinnedMesh === true;
  91. /**
  92. * A list of all possible material uniforms
  93. *
  94. * @type {Array<String>}
  95. */
  96. this.refreshUniforms = refreshUniforms;
  97. /**
  98. * Holds the current render ID from the node frame.
  99. *
  100. * @type {Number}
  101. * @default 0
  102. */
  103. this.renderId = 0;
  104. }
  105. /**
  106. * Returns `true` if the given render object is verified for the first time of this observer.
  107. *
  108. * @param {RenderObject} renderObject - The render object.
  109. * @return {Boolean} Whether the given render object is verified for the first time of this observer.
  110. */
  111. firstInitialization( renderObject ) {
  112. const hasInitialized = this.renderObjects.has( renderObject );
  113. if ( hasInitialized === false ) {
  114. this.getRenderObjectData( renderObject );
  115. return true;
  116. }
  117. return false;
  118. }
  119. /**
  120. * Returns monitoring data for the given render object.
  121. *
  122. * @param {RenderObject} renderObject - The render object.
  123. * @return {Object} The monitoring data.
  124. */
  125. getRenderObjectData( renderObject ) {
  126. let data = this.renderObjects.get( renderObject );
  127. if ( data === undefined ) {
  128. const { geometry, material, object } = renderObject;
  129. data = {
  130. material: this.getMaterialData( material ),
  131. geometry: {
  132. attributes: this.getAttributesData( geometry.attributes ),
  133. indexVersion: geometry.index ? geometry.index.version : null,
  134. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  135. },
  136. worldMatrix: object.matrixWorld.clone()
  137. };
  138. if ( object.center ) {
  139. data.center = object.center.clone();
  140. }
  141. if ( object.morphTargetInfluences ) {
  142. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  143. }
  144. if ( renderObject.bundle !== null ) {
  145. data.version = renderObject.bundle.version;
  146. }
  147. if ( data.material.transmission > 0 ) {
  148. const { width, height } = renderObject.context;
  149. data.bufferWidth = width;
  150. data.bufferHeight = height;
  151. }
  152. this.renderObjects.set( renderObject, data );
  153. }
  154. return data;
  155. }
  156. /**
  157. * Returns an attribute data structure holding the attributes versions for
  158. * monitoring.
  159. *
  160. * @param {Object} attributes - The geometry attributes.
  161. * @return {Object} An object for monitoring the versions of attributes.
  162. */
  163. getAttributesData( attributes ) {
  164. const attributesData = {};
  165. for ( const name in attributes ) {
  166. const attribute = attributes[ name ];
  167. attributesData[ name ] = {
  168. version: attribute.version
  169. };
  170. }
  171. return attributesData;
  172. }
  173. /**
  174. * Returns `true` if the node builder's material uses
  175. * node properties.
  176. *
  177. * @param {NodeBuilder} builder - The current node builder.
  178. * @return {Boolean} Whether the node builder's material uses node properties or not.
  179. */
  180. containsNode( builder ) {
  181. const material = builder.material;
  182. for ( const property in material ) {
  183. if ( material[ property ] && material[ property ].isNode )
  184. return true;
  185. }
  186. if ( builder.renderer.nodes.modelViewMatrix !== null || builder.renderer.nodes.modelNormalViewMatrix !== null )
  187. return true;
  188. return false;
  189. }
  190. /**
  191. * Returns a material data structure holding the material property values for
  192. * monitoring.
  193. *
  194. * @param {Material} material - The material.
  195. * @return {Object} An object for monitoring material properties.
  196. */
  197. getMaterialData( material ) {
  198. const data = {};
  199. for ( const property of this.refreshUniforms ) {
  200. const value = material[ property ];
  201. if ( value === null || value === undefined ) continue;
  202. if ( typeof value === 'object' && value.clone !== undefined ) {
  203. if ( value.isTexture === true ) {
  204. data[ property ] = { id: value.id, version: value.version };
  205. } else {
  206. data[ property ] = value.clone();
  207. }
  208. } else {
  209. data[ property ] = value;
  210. }
  211. }
  212. return data;
  213. }
  214. /**
  215. * Returns `true` if the given render object has not changed its state.
  216. *
  217. * @param {RenderObject} renderObject - The render object.
  218. * @return {Boolean} Whether the given render object has changed its state or not.
  219. */
  220. equals( renderObject ) {
  221. const { object, material, geometry } = renderObject;
  222. const renderObjectData = this.getRenderObjectData( renderObject );
  223. // world matrix
  224. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  225. renderObjectData.worldMatrix.copy( object.matrixWorld );
  226. return false;
  227. }
  228. // material
  229. const materialData = renderObjectData.material;
  230. for ( const property in materialData ) {
  231. const value = materialData[ property ];
  232. const mtlValue = material[ property ];
  233. if ( value.equals !== undefined ) {
  234. if ( value.equals( mtlValue ) === false ) {
  235. value.copy( mtlValue );
  236. return false;
  237. }
  238. } else if ( mtlValue.isTexture === true ) {
  239. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  240. value.id = mtlValue.id;
  241. value.version = mtlValue.version;
  242. return false;
  243. }
  244. } else if ( value !== mtlValue ) {
  245. materialData[ property ] = mtlValue;
  246. return false;
  247. }
  248. }
  249. if ( materialData.transmission > 0 ) {
  250. const { width, height } = renderObject.context;
  251. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  252. renderObjectData.bufferWidth = width;
  253. renderObjectData.bufferHeight = height;
  254. return false;
  255. }
  256. }
  257. // geometry
  258. const storedGeometryData = renderObjectData.geometry;
  259. const attributes = geometry.attributes;
  260. const storedAttributes = storedGeometryData.attributes;
  261. const storedAttributeNames = Object.keys( storedAttributes );
  262. const currentAttributeNames = Object.keys( attributes );
  263. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  264. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  265. return false;
  266. }
  267. // compare each attribute
  268. for ( const name of storedAttributeNames ) {
  269. const storedAttributeData = storedAttributes[ name ];
  270. const attribute = attributes[ name ];
  271. if ( attribute === undefined ) {
  272. // attribute was removed
  273. delete storedAttributes[ name ];
  274. return false;
  275. }
  276. if ( storedAttributeData.version !== attribute.version ) {
  277. storedAttributeData.version = attribute.version;
  278. return false;
  279. }
  280. }
  281. // check index
  282. const index = geometry.index;
  283. const storedIndexVersion = storedGeometryData.indexVersion;
  284. const currentIndexVersion = index ? index.version : null;
  285. if ( storedIndexVersion !== currentIndexVersion ) {
  286. storedGeometryData.indexVersion = currentIndexVersion;
  287. return false;
  288. }
  289. // check drawRange
  290. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  291. storedGeometryData.drawRange.start = geometry.drawRange.start;
  292. storedGeometryData.drawRange.count = geometry.drawRange.count;
  293. return false;
  294. }
  295. // morph targets
  296. if ( renderObjectData.morphTargetInfluences ) {
  297. let morphChanged = false;
  298. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  299. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  300. morphChanged = true;
  301. }
  302. }
  303. if ( morphChanged ) return true;
  304. }
  305. // center
  306. if ( renderObjectData.center ) {
  307. if ( renderObjectData.center.equals( object.center ) === false ) {
  308. renderObjectData.center.copy( object.center );
  309. return true;
  310. }
  311. }
  312. // bundle
  313. if ( renderObject.bundle !== null ) {
  314. renderObjectData.version = renderObject.bundle.version;
  315. }
  316. return true;
  317. }
  318. /**
  319. * Checks if the given render object requires a refresh.
  320. *
  321. * @param {RenderObject} renderObject - The render object.
  322. * @param {NodeFrame} nodeFrame - The current node frame.
  323. * @return {Boolean} Whether the given render object requires a refresh or not.
  324. */
  325. needsRefresh( renderObject, nodeFrame ) {
  326. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) )
  327. return true;
  328. const { renderId } = nodeFrame;
  329. if ( this.renderId !== renderId ) {
  330. this.renderId = renderId;
  331. return true;
  332. }
  333. const isStatic = renderObject.object.static === true;
  334. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  335. if ( isStatic || isBundle )
  336. return false;
  337. const notEqual = this.equals( renderObject ) !== true;
  338. return notEqual;
  339. }
  340. }
  341. /** @module NodeUtils **/
  342. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  343. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  344. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  345. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  346. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  347. function cyrb53( value, seed = 0 ) {
  348. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  349. if ( value instanceof Array ) {
  350. for ( let i = 0, val; i < value.length; i ++ ) {
  351. val = value[ i ];
  352. h1 = Math.imul( h1 ^ val, 2654435761 );
  353. h2 = Math.imul( h2 ^ val, 1597334677 );
  354. }
  355. } else {
  356. for ( let i = 0, ch; i < value.length; i ++ ) {
  357. ch = value.charCodeAt( i );
  358. h1 = Math.imul( h1 ^ ch, 2654435761 );
  359. h2 = Math.imul( h2 ^ ch, 1597334677 );
  360. }
  361. }
  362. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  363. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  364. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  365. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  366. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  367. }
  368. /**
  369. * Computes a hash for the given string.
  370. *
  371. * @method
  372. * @param {String} str - The string to be hashed.
  373. * @return {Number} The hash.
  374. */
  375. const hashString = ( str ) => cyrb53( str );
  376. /**
  377. * Computes a hash for the given array.
  378. *
  379. * @method
  380. * @param {Array<Number>} array - The array to be hashed.
  381. * @return {Number} The hash.
  382. */
  383. const hashArray = ( array ) => cyrb53( array );
  384. /**
  385. * Computes a hash for the given list of parameters.
  386. *
  387. * @method
  388. * @param {...Number} params - A list of parameters.
  389. * @return {Number} The hash.
  390. */
  391. const hash$1 = ( ...params ) => cyrb53( params );
  392. /**
  393. * Computes a cache key for the given node.
  394. *
  395. * @method
  396. * @param {Object} object - The object to be hashed.
  397. * @param {Boolean} [force=false] - Whether to force a cache key computation or not.
  398. * @return {Number} The hash.
  399. */
  400. function getCacheKey$1( object, force = false ) {
  401. const values = [];
  402. if ( object.isNode === true ) {
  403. values.push( object.id );
  404. object = object.getSelf();
  405. }
  406. for ( const { property, childNode } of getNodeChildren( object ) ) {
  407. values.push( values, cyrb53( property.slice( 0, - 4 ) ), childNode.getCacheKey( force ) );
  408. }
  409. return cyrb53( values );
  410. }
  411. /**
  412. * This generator function can be used to iterate over the node children
  413. * of the given object.
  414. *
  415. * @generator
  416. * @param {Object} node - The object to be hashed.
  417. * @param {Boolean} [toJSON=false] - Whether to return JSON or not.
  418. * @yields {Object} A result node holding the property, index (if available) and the child node.
  419. */
  420. function* getNodeChildren( node, toJSON = false ) {
  421. for ( const property in node ) {
  422. // Ignore private properties.
  423. if ( property.startsWith( '_' ) === true ) continue;
  424. const object = node[ property ];
  425. if ( Array.isArray( object ) === true ) {
  426. for ( let i = 0; i < object.length; i ++ ) {
  427. const child = object[ i ];
  428. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  429. yield { property, index: i, childNode: child };
  430. }
  431. }
  432. } else if ( object && object.isNode === true ) {
  433. yield { property, childNode: object };
  434. } else if ( typeof object === 'object' ) {
  435. for ( const subProperty in object ) {
  436. const child = object[ subProperty ];
  437. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  438. yield { property, index: subProperty, childNode: child };
  439. }
  440. }
  441. }
  442. }
  443. }
  444. const typeFromLength = /*@__PURE__*/ new Map( [
  445. [ 1, 'float' ],
  446. [ 2, 'vec2' ],
  447. [ 3, 'vec3' ],
  448. [ 4, 'vec4' ],
  449. [ 9, 'mat3' ],
  450. [ 16, 'mat4' ]
  451. ] );
  452. const dataFromObject = /*@__PURE__*/ new WeakMap();
  453. /**
  454. * Returns the data type for the given the length.
  455. *
  456. * @method
  457. * @param {Number} length - The length.
  458. * @return {String} The data type.
  459. */
  460. function getTypeFromLength( length ) {
  461. return typeFromLength.get( length );
  462. }
  463. /**
  464. * Returns the typed array for the given data type.
  465. *
  466. * @method
  467. * @param {String} type - The data type.
  468. * @return {TypedArray} The typed array.
  469. */
  470. function getTypedArrayFromType( type ) {
  471. // Handle component type for vectors and matrices
  472. if ( /[iu]?vec\d/.test( type ) ) {
  473. // Handle int vectors
  474. if ( type.startsWith( 'ivec' ) ) return Int32Array;
  475. // Handle uint vectors
  476. if ( type.startsWith( 'uvec' ) ) return Uint32Array;
  477. // Default to float vectors
  478. return Float32Array;
  479. }
  480. // Handle matrices (always float)
  481. if ( /mat\d/.test( type ) ) return Float32Array;
  482. // Basic types
  483. if ( /float/.test( type ) ) return Float32Array;
  484. if ( /uint/.test( type ) ) return Uint32Array;
  485. if ( /int/.test( type ) ) return Int32Array;
  486. throw new Error( `THREE.NodeUtils: Unsupported type: ${type}` );
  487. }
  488. /**
  489. * Returns the length for the given data type.
  490. *
  491. * @method
  492. * @param {String} type - The data type.
  493. * @return {Number} The length.
  494. */
  495. function getLengthFromType( type ) {
  496. if ( /float|int|uint/.test( type ) ) return 1;
  497. if ( /vec2/.test( type ) ) return 2;
  498. if ( /vec3/.test( type ) ) return 3;
  499. if ( /vec4/.test( type ) ) return 4;
  500. if ( /mat3/.test( type ) ) return 9;
  501. if ( /mat4/.test( type ) ) return 16;
  502. console.error( 'THREE.TSL: Unsupported type:', type );
  503. }
  504. /**
  505. * Returns the data type for the given value.
  506. *
  507. * @method
  508. * @param {Any} value - The value.
  509. * @return {String?} The data type.
  510. */
  511. function getValueType( value ) {
  512. if ( value === undefined || value === null ) return null;
  513. const typeOf = typeof value;
  514. if ( value.isNode === true ) {
  515. return 'node';
  516. } else if ( typeOf === 'number' ) {
  517. return 'float';
  518. } else if ( typeOf === 'boolean' ) {
  519. return 'bool';
  520. } else if ( typeOf === 'string' ) {
  521. return 'string';
  522. } else if ( typeOf === 'function' ) {
  523. return 'shader';
  524. } else if ( value.isVector2 === true ) {
  525. return 'vec2';
  526. } else if ( value.isVector3 === true ) {
  527. return 'vec3';
  528. } else if ( value.isVector4 === true ) {
  529. return 'vec4';
  530. } else if ( value.isMatrix3 === true ) {
  531. return 'mat3';
  532. } else if ( value.isMatrix4 === true ) {
  533. return 'mat4';
  534. } else if ( value.isColor === true ) {
  535. return 'color';
  536. } else if ( value instanceof ArrayBuffer ) {
  537. return 'ArrayBuffer';
  538. }
  539. return null;
  540. }
  541. /**
  542. * Returns the value/object for the given data type and parameters.
  543. *
  544. * @method
  545. * @param {String} type - The given type.
  546. * @param {...Any} params - A parameter list.
  547. * @return {Any} The value/object.
  548. */
  549. function getValueFromType( type, ...params ) {
  550. const last4 = type ? type.slice( - 4 ) : undefined;
  551. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  552. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  553. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  554. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  555. }
  556. if ( type === 'color' ) {
  557. return new Color( ...params );
  558. } else if ( last4 === 'vec2' ) {
  559. return new Vector2( ...params );
  560. } else if ( last4 === 'vec3' ) {
  561. return new Vector3( ...params );
  562. } else if ( last4 === 'vec4' ) {
  563. return new Vector4( ...params );
  564. } else if ( last4 === 'mat3' ) {
  565. return new Matrix3( ...params );
  566. } else if ( last4 === 'mat4' ) {
  567. return new Matrix4( ...params );
  568. } else if ( type === 'bool' ) {
  569. return params[ 0 ] || false;
  570. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  571. return params[ 0 ] || 0;
  572. } else if ( type === 'string' ) {
  573. return params[ 0 ] || '';
  574. } else if ( type === 'ArrayBuffer' ) {
  575. return base64ToArrayBuffer( params[ 0 ] );
  576. }
  577. return null;
  578. }
  579. /**
  580. * Gets the object data that can be shared between different rendering steps.
  581. *
  582. * @param {Object} object - The object to get the data for.
  583. * @return {Object} The object data.
  584. */
  585. function getDataFromObject( object ) {
  586. let data = dataFromObject.get( object );
  587. if ( data === undefined ) {
  588. data = {};
  589. dataFromObject.set( object, data );
  590. }
  591. return data;
  592. }
  593. /**
  594. * Converts the given array buffer to a Base64 string.
  595. *
  596. * @method
  597. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  598. * @return {String} The Base64 string.
  599. */
  600. function arrayBufferToBase64( arrayBuffer ) {
  601. let chars = '';
  602. const array = new Uint8Array( arrayBuffer );
  603. for ( let i = 0; i < array.length; i ++ ) {
  604. chars += String.fromCharCode( array[ i ] );
  605. }
  606. return btoa( chars );
  607. }
  608. /**
  609. * Converts the given Base64 string to an array buffer.
  610. *
  611. * @method
  612. * @param {String} base64 - The Base64 string.
  613. * @return {ArrayBuffer} The array buffer.
  614. */
  615. function base64ToArrayBuffer( base64 ) {
  616. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  617. }
  618. var NodeUtils = /*#__PURE__*/Object.freeze({
  619. __proto__: null,
  620. arrayBufferToBase64: arrayBufferToBase64,
  621. base64ToArrayBuffer: base64ToArrayBuffer,
  622. getCacheKey: getCacheKey$1,
  623. getDataFromObject: getDataFromObject,
  624. getLengthFromType: getLengthFromType,
  625. getNodeChildren: getNodeChildren,
  626. getTypeFromLength: getTypeFromLength,
  627. getTypedArrayFromType: getTypedArrayFromType,
  628. getValueFromType: getValueFromType,
  629. getValueType: getValueType,
  630. hash: hash$1,
  631. hashArray: hashArray,
  632. hashString: hashString
  633. });
  634. /** @module NodeConstants **/
  635. /**
  636. * Possible shader stages.
  637. *
  638. * @property {string} VERTEX The vertex shader stage.
  639. * @property {string} FRAGMENT The fragment shader stage.
  640. */
  641. const NodeShaderStage = {
  642. VERTEX: 'vertex',
  643. FRAGMENT: 'fragment'
  644. };
  645. /**
  646. * Update types of a node.
  647. *
  648. * @property {string} NONE The update method is not executed.
  649. * @property {string} FRAME The update method is executed per frame.
  650. * @property {string} RENDER The update method is executed per render. A frame might be produced by multiple render calls so this value allows more detailed updates than FRAME.
  651. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  652. */
  653. const NodeUpdateType = {
  654. NONE: 'none',
  655. FRAME: 'frame',
  656. RENDER: 'render',
  657. OBJECT: 'object'
  658. };
  659. /**
  660. * Data types of a node.
  661. *
  662. * @property {string} BOOLEAN Boolean type.
  663. * @property {string} INTEGER Integer type.
  664. * @property {string} FLOAT Float type.
  665. * @property {string} VECTOR2 Two-dimensional vector type.
  666. * @property {string} VECTOR3 Three-dimensional vector type.
  667. * @property {string} VECTOR4 Four-dimensional vector type.
  668. * @property {string} MATRIX2 2x2 matrix type.
  669. * @property {string} MATRIX3 3x3 matrix type.
  670. * @property {string} MATRIX4 4x4 matrix type.
  671. */
  672. const NodeType = {
  673. BOOLEAN: 'bool',
  674. INTEGER: 'int',
  675. FLOAT: 'float',
  676. VECTOR2: 'vec2',
  677. VECTOR3: 'vec3',
  678. VECTOR4: 'vec4',
  679. MATRIX2: 'mat2',
  680. MATRIX3: 'mat3',
  681. MATRIX4: 'mat4'
  682. };
  683. /**
  684. * Access types of a node. These are relevant for compute and storage usage.
  685. *
  686. * @property {string} READ_ONLY Read-only access
  687. * @property {string} WRITE_ONLY Write-only access.
  688. * @property {string} READ_WRITE Read and write access.
  689. */
  690. const NodeAccess = {
  691. READ_ONLY: 'readOnly',
  692. WRITE_ONLY: 'writeOnly',
  693. READ_WRITE: 'readWrite',
  694. };
  695. const defaultShaderStages = [ 'fragment', 'vertex' ];
  696. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  697. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  698. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  699. let _nodeId = 0;
  700. /**
  701. * Base class for all nodes.
  702. *
  703. * @augments EventDispatcher
  704. */
  705. class Node extends EventDispatcher {
  706. static get type() {
  707. return 'Node';
  708. }
  709. /**
  710. * Constructs a new node.
  711. *
  712. * @param {String?} nodeType - The node type.
  713. */
  714. constructor( nodeType = null ) {
  715. super();
  716. /**
  717. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  718. *
  719. * @type {String?}
  720. * @default null
  721. */
  722. this.nodeType = nodeType;
  723. /**
  724. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  725. *
  726. * @type {String}
  727. * @default 'none'
  728. */
  729. this.updateType = NodeUpdateType.NONE;
  730. /**
  731. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  732. *
  733. * @type {String}
  734. * @default 'none'
  735. */
  736. this.updateBeforeType = NodeUpdateType.NONE;
  737. /**
  738. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  739. *
  740. * @type {String}
  741. * @default 'none'
  742. */
  743. this.updateAfterType = NodeUpdateType.NONE;
  744. /**
  745. * The UUID of the node.
  746. *
  747. * @type {String}
  748. * @readonly
  749. */
  750. this.uuid = MathUtils.generateUUID();
  751. /**
  752. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  753. *
  754. * @type {Number}
  755. * @readonly
  756. * @default 0
  757. */
  758. this.version = 0;
  759. /**
  760. * Whether this node is global or not. This property is relevant for the internal
  761. * node caching system. All nodes which should be declared just once should
  762. * set this flag to `true` (a typical example is {@link AttributeNode}).
  763. *
  764. * @type {Boolean}
  765. * @default false
  766. */
  767. this.global = false;
  768. /**
  769. * This flag can be used for type testing.
  770. *
  771. * @type {Boolean}
  772. * @readonly
  773. * @default true
  774. */
  775. this.isNode = true;
  776. // private
  777. /**
  778. * The cache key of this node.
  779. *
  780. * @private
  781. * @type {Number?}
  782. * @default null
  783. */
  784. this._cacheKey = null;
  785. /**
  786. * The cache key 's version.
  787. *
  788. * @private
  789. * @type {Number}
  790. * @default 0
  791. */
  792. this._cacheKeyVersion = 0;
  793. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  794. }
  795. /**
  796. * Set this property to `true` when the node should be regenerated.
  797. *
  798. * @type {Boolean}
  799. * @default false
  800. * @param {boolean} value
  801. */
  802. set needsUpdate( value ) {
  803. if ( value === true ) {
  804. this.version ++;
  805. }
  806. }
  807. /**
  808. * The type of the class. The value is usually the constructor name.
  809. *
  810. * @type {String}
  811. * @readonly
  812. */
  813. get type() {
  814. return this.constructor.type;
  815. }
  816. /**
  817. * Convenient method for defining {@link Node#update}.
  818. *
  819. * @param {Function} callback - The update method.
  820. * @param {String} updateType - The update type.
  821. * @return {Node} A reference to this node.
  822. */
  823. onUpdate( callback, updateType ) {
  824. this.updateType = updateType;
  825. this.update = callback.bind( this.getSelf() );
  826. return this;
  827. }
  828. /**
  829. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  830. * this method automatically sets the update type to `FRAME`.
  831. *
  832. * @param {Function} callback - The update method.
  833. * @return {Node} A reference to this node.
  834. */
  835. onFrameUpdate( callback ) {
  836. return this.onUpdate( callback, NodeUpdateType.FRAME );
  837. }
  838. /**
  839. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  840. * this method automatically sets the update type to `RENDER`.
  841. *
  842. * @param {Function} callback - The update method.
  843. * @return {Node} A reference to this node.
  844. */
  845. onRenderUpdate( callback ) {
  846. return this.onUpdate( callback, NodeUpdateType.RENDER );
  847. }
  848. /**
  849. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  850. * this method automatically sets the update type to `OBJECT`.
  851. *
  852. * @param {Function} callback - The update method.
  853. * @return {Node} A reference to this node.
  854. */
  855. onObjectUpdate( callback ) {
  856. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  857. }
  858. /**
  859. * Convenient method for defining {@link Node#updateReference}.
  860. *
  861. * @param {Function} callback - The update method.
  862. * @return {Node} A reference to this node.
  863. */
  864. onReference( callback ) {
  865. this.updateReference = callback.bind( this.getSelf() );
  866. return this;
  867. }
  868. /**
  869. * The `this` reference might point to a Proxy so this method can be used
  870. * to get the reference to the actual node instance.
  871. *
  872. * @return {Node} A reference to the node.
  873. */
  874. getSelf() {
  875. // Returns non-node object.
  876. return this.self || this;
  877. }
  878. /**
  879. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  880. * to such objects based on a given state (e.g. the current node frame or builder).
  881. *
  882. * @param {Any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  883. * @return {Any} The updated reference.
  884. */
  885. updateReference( /*state*/ ) {
  886. return this;
  887. }
  888. /**
  889. * By default this method returns the value of the {@link Node#global} flag. This method
  890. * can be overwritten in derived classes if an analytical way is required to determine the
  891. * global status.
  892. *
  893. * @param {NodeBuilder} builder - The current node builder.
  894. * @return {Boolean} Whether this node is global or not.
  895. */
  896. isGlobal( /*builder*/ ) {
  897. return this.global;
  898. }
  899. /**
  900. * Generator function that can be used to iterate over the child nodes.
  901. *
  902. * @generator
  903. * @yields {Node} A child node.
  904. */
  905. * getChildren() {
  906. for ( const { childNode } of getNodeChildren( this ) ) {
  907. yield childNode;
  908. }
  909. }
  910. /**
  911. * Calling this method dispatches the `dispose` event. This event can be used
  912. * to register event listeners for clean up tasks.
  913. */
  914. dispose() {
  915. this.dispatchEvent( { type: 'dispose' } );
  916. }
  917. /**
  918. * Callback for {@link Node#traverse}.
  919. *
  920. * @callback traverseCallback
  921. * @param {Node} node - The current node.
  922. */
  923. /**
  924. * Can be used to traverse through the node's hierarchy.
  925. *
  926. * @param {traverseCallback} callback - A callback that is executed per node.
  927. */
  928. traverse( callback ) {
  929. callback( this );
  930. for ( const childNode of this.getChildren() ) {
  931. childNode.traverse( callback );
  932. }
  933. }
  934. /**
  935. * Returns the cache key for this node.
  936. *
  937. * @param {Boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  938. * @return {Number} The cache key of the node.
  939. */
  940. getCacheKey( force = false ) {
  941. force = force || this.version !== this._cacheKeyVersion;
  942. if ( force === true || this._cacheKey === null ) {
  943. this._cacheKey = hash$1( getCacheKey$1( this, force ), this.customCacheKey() );
  944. this._cacheKeyVersion = this.version;
  945. }
  946. return this._cacheKey;
  947. }
  948. /**
  949. * Generate a custom cache key for this node.
  950. *
  951. * @return {Number} The cache key of the node.
  952. */
  953. customCacheKey() {
  954. return 0;
  955. }
  956. /**
  957. * Returns the references to this node which is by default `this`.
  958. *
  959. * @return {Node} A reference to this node.
  960. */
  961. getScope() {
  962. return this;
  963. }
  964. /**
  965. * Returns the hash of the node which is used to identify the node. By default it's
  966. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  967. * depending on their implementation.
  968. *
  969. * @param {NodeBuilder} builder - The current node builder.
  970. * @return {String} The hash.
  971. */
  972. getHash( /*builder*/ ) {
  973. return this.uuid;
  974. }
  975. /**
  976. * Returns the update type of {@link Node#update}.
  977. *
  978. * @return {NodeUpdateType} The update type.
  979. */
  980. getUpdateType() {
  981. return this.updateType;
  982. }
  983. /**
  984. * Returns the update type of {@link Node#updateBefore}.
  985. *
  986. * @return {NodeUpdateType} The update type.
  987. */
  988. getUpdateBeforeType() {
  989. return this.updateBeforeType;
  990. }
  991. /**
  992. * Returns the update type of {@link Node#updateAfter}.
  993. *
  994. * @return {NodeUpdateType} The update type.
  995. */
  996. getUpdateAfterType() {
  997. return this.updateAfterType;
  998. }
  999. /**
  1000. * Certain types are composed of multiple elements. For example a `vec3`
  1001. * is composed of three `float` values. This method returns the type of
  1002. * these elements.
  1003. *
  1004. * @param {NodeBuilder} builder - The current node builder.
  1005. * @return {String} The type of the node.
  1006. */
  1007. getElementType( builder ) {
  1008. const type = this.getNodeType( builder );
  1009. const elementType = builder.getElementType( type );
  1010. return elementType;
  1011. }
  1012. /**
  1013. * Returns the node's type.
  1014. *
  1015. * @param {NodeBuilder} builder - The current node builder.
  1016. * @return {String} The type of the node.
  1017. */
  1018. getNodeType( builder ) {
  1019. const nodeProperties = builder.getNodeProperties( this );
  1020. if ( nodeProperties.outputNode ) {
  1021. return nodeProperties.outputNode.getNodeType( builder );
  1022. }
  1023. return this.nodeType;
  1024. }
  1025. /**
  1026. * This method is used during the build process of a node and ensures
  1027. * equal nodes are not built multiple times but just once. For example if
  1028. * `attribute( 'uv' )` is used multiple times by the user, the build
  1029. * process makes sure to process just the first node.
  1030. *
  1031. * @param {NodeBuilder} builder - The current node builder.
  1032. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1033. */
  1034. getShared( builder ) {
  1035. const hash = this.getHash( builder );
  1036. const nodeFromHash = builder.getNodeFromHash( hash );
  1037. return nodeFromHash || this;
  1038. }
  1039. /**
  1040. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1041. * This method is often overwritten in derived modules to prepare the node which is used as the output/result.
  1042. * The output node must be returned in the `return` statement.
  1043. *
  1044. * @param {NodeBuilder} builder - The current node builder.
  1045. * @return {Node?} The output node.
  1046. */
  1047. setup( builder ) {
  1048. const nodeProperties = builder.getNodeProperties( this );
  1049. let index = 0;
  1050. for ( const childNode of this.getChildren() ) {
  1051. nodeProperties[ 'node' + index ++ ] = childNode;
  1052. }
  1053. // return a outputNode if exists or null
  1054. return nodeProperties.outputNode || null;
  1055. }
  1056. /**
  1057. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1058. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1059. *
  1060. * @param {NodeBuilder} builder - The current node builder.
  1061. */
  1062. analyze( builder ) {
  1063. const usageCount = builder.increaseUsage( this );
  1064. if ( usageCount === 1 ) {
  1065. // node flow children
  1066. const nodeProperties = builder.getNodeProperties( this );
  1067. for ( const childNode of Object.values( nodeProperties ) ) {
  1068. if ( childNode && childNode.isNode === true ) {
  1069. childNode.build( builder );
  1070. }
  1071. }
  1072. }
  1073. }
  1074. /**
  1075. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1076. * This state builds the output node and returns the resulting shader string.
  1077. *
  1078. * @param {NodeBuilder} builder - The current node builder.
  1079. * @param {String?} output - Can be used to define the output type.
  1080. * @return {String?} The generated shader string.
  1081. */
  1082. generate( builder, output ) {
  1083. const { outputNode } = builder.getNodeProperties( this );
  1084. if ( outputNode && outputNode.isNode === true ) {
  1085. return outputNode.build( builder, output );
  1086. }
  1087. }
  1088. /**
  1089. * The method can be implemented to update the node's internal state before it is used to render an object.
  1090. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1091. *
  1092. * @abstract
  1093. * @param {NodeFrame} frame - A reference to the current node frame.
  1094. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1095. */
  1096. updateBefore( /*frame*/ ) {
  1097. console.warn( 'Abstract function.' );
  1098. }
  1099. /**
  1100. * The method can be implemented to update the node's internal state after it was used to render an object.
  1101. * The {@link Node#updateAfterType} property defines how often the update is executed.
  1102. *
  1103. * @abstract
  1104. * @param {NodeFrame} frame - A reference to the current node frame.
  1105. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1106. */
  1107. updateAfter( /*frame*/ ) {
  1108. console.warn( 'Abstract function.' );
  1109. }
  1110. /**
  1111. * The method can be implemented to update the node's internal state when it is used to render an object.
  1112. * The {@link Node#updateType} property defines how often the update is executed.
  1113. *
  1114. * @abstract
  1115. * @param {NodeFrame} frame - A reference to the current node frame.
  1116. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1117. */
  1118. update( /*frame*/ ) {
  1119. console.warn( 'Abstract function.' );
  1120. }
  1121. /**
  1122. * This method performs the build of a node. The behavior of this method as well as its return value depend
  1123. * on the current build stage (setup, analyze or generate).
  1124. *
  1125. * @param {NodeBuilder} builder - The current node builder.
  1126. * @param {String?} output - Can be used to define the output type.
  1127. * @return {String?} When this method is executed in the setup or analyze stage, `null` is returned. In the generate stage, the generated shader string.
  1128. */
  1129. build( builder, output = null ) {
  1130. const refNode = this.getShared( builder );
  1131. if ( this !== refNode ) {
  1132. return refNode.build( builder, output );
  1133. }
  1134. builder.addNode( this );
  1135. builder.addChain( this );
  1136. /* Build stages expected results:
  1137. - "setup" -> Node
  1138. - "analyze" -> null
  1139. - "generate" -> String
  1140. */
  1141. let result = null;
  1142. const buildStage = builder.getBuildStage();
  1143. if ( buildStage === 'setup' ) {
  1144. this.updateReference( builder );
  1145. const properties = builder.getNodeProperties( this );
  1146. if ( properties.initialized !== true ) {
  1147. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1148. properties.initialized = true;
  1149. const outputNode = this.setup( builder ); // return a node or null
  1150. const isNodeOutput = outputNode && outputNode.isNode === true;
  1151. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1152. // !! no outputNode !!
  1153. //outputNode = builder.stack;
  1154. }*/
  1155. for ( const childNode of Object.values( properties ) ) {
  1156. if ( childNode && childNode.isNode === true ) {
  1157. childNode.build( builder );
  1158. }
  1159. }
  1160. if ( isNodeOutput ) {
  1161. outputNode.build( builder );
  1162. }
  1163. properties.outputNode = outputNode;
  1164. }
  1165. } else if ( buildStage === 'analyze' ) {
  1166. this.analyze( builder );
  1167. } else if ( buildStage === 'generate' ) {
  1168. const isGenerateOnce = this.generate.length === 1;
  1169. if ( isGenerateOnce ) {
  1170. const type = this.getNodeType( builder );
  1171. const nodeData = builder.getDataFromNode( this );
  1172. result = nodeData.snippet;
  1173. if ( result === undefined ) {
  1174. result = this.generate( builder ) || '';
  1175. nodeData.snippet = result;
  1176. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1177. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1178. }
  1179. result = builder.format( result, type, output );
  1180. } else {
  1181. result = this.generate( builder, output ) || '';
  1182. }
  1183. }
  1184. builder.removeChain( this );
  1185. builder.addSequentialNode( this );
  1186. return result;
  1187. }
  1188. /**
  1189. * Returns the child nodes as a JSON object.
  1190. *
  1191. * @return {Object} The serialized child objects as JSON.
  1192. */
  1193. getSerializeChildren() {
  1194. return getNodeChildren( this );
  1195. }
  1196. /**
  1197. * Serializes the node to JSON.
  1198. *
  1199. * @param {Object} json - The output JSON object.
  1200. */
  1201. serialize( json ) {
  1202. const nodeChildren = this.getSerializeChildren();
  1203. const inputNodes = {};
  1204. for ( const { property, index, childNode } of nodeChildren ) {
  1205. if ( index !== undefined ) {
  1206. if ( inputNodes[ property ] === undefined ) {
  1207. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1208. }
  1209. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1210. } else {
  1211. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1212. }
  1213. }
  1214. if ( Object.keys( inputNodes ).length > 0 ) {
  1215. json.inputNodes = inputNodes;
  1216. }
  1217. }
  1218. /**
  1219. * Deserializes the node from the given JSON.
  1220. *
  1221. * @param {Object} json - The JSON object.
  1222. */
  1223. deserialize( json ) {
  1224. if ( json.inputNodes !== undefined ) {
  1225. const nodes = json.meta.nodes;
  1226. for ( const property in json.inputNodes ) {
  1227. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1228. const inputArray = [];
  1229. for ( const uuid of json.inputNodes[ property ] ) {
  1230. inputArray.push( nodes[ uuid ] );
  1231. }
  1232. this[ property ] = inputArray;
  1233. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1234. const inputObject = {};
  1235. for ( const subProperty in json.inputNodes[ property ] ) {
  1236. const uuid = json.inputNodes[ property ][ subProperty ];
  1237. inputObject[ subProperty ] = nodes[ uuid ];
  1238. }
  1239. this[ property ] = inputObject;
  1240. } else {
  1241. const uuid = json.inputNodes[ property ];
  1242. this[ property ] = nodes[ uuid ];
  1243. }
  1244. }
  1245. }
  1246. }
  1247. /**
  1248. * Serializes the node into the three.js JSON Object/Scene format.
  1249. *
  1250. * @param {Object?} meta - An optional JSON object that already holds serialized data from other scene objects.
  1251. * @return {Object} The serialized node.
  1252. */
  1253. toJSON( meta ) {
  1254. const { uuid, type } = this;
  1255. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1256. if ( isRoot ) {
  1257. meta = {
  1258. textures: {},
  1259. images: {},
  1260. nodes: {}
  1261. };
  1262. }
  1263. // serialize
  1264. let data = meta.nodes[ uuid ];
  1265. if ( data === undefined ) {
  1266. data = {
  1267. uuid,
  1268. type,
  1269. meta,
  1270. metadata: {
  1271. version: 4.6,
  1272. type: 'Node',
  1273. generator: 'Node.toJSON'
  1274. }
  1275. };
  1276. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1277. this.serialize( data );
  1278. delete data.meta;
  1279. }
  1280. // TODO: Copied from Object3D.toJSON
  1281. function extractFromCache( cache ) {
  1282. const values = [];
  1283. for ( const key in cache ) {
  1284. const data = cache[ key ];
  1285. delete data.metadata;
  1286. values.push( data );
  1287. }
  1288. return values;
  1289. }
  1290. if ( isRoot ) {
  1291. const textures = extractFromCache( meta.textures );
  1292. const images = extractFromCache( meta.images );
  1293. const nodes = extractFromCache( meta.nodes );
  1294. if ( textures.length > 0 ) data.textures = textures;
  1295. if ( images.length > 0 ) data.images = images;
  1296. if ( nodes.length > 0 ) data.nodes = nodes;
  1297. }
  1298. return data;
  1299. }
  1300. }
  1301. /**
  1302. * Base class for representing element access on an array-like
  1303. * node data structures.
  1304. *
  1305. * @augments Node
  1306. */
  1307. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1308. static get type() {
  1309. return 'ArrayElementNode';
  1310. }
  1311. /**
  1312. * Constructs an array element node.
  1313. *
  1314. * @param {Node} node - The array-like node.
  1315. * @param {Node} indexNode - The index node that defines the element access.
  1316. */
  1317. constructor( node, indexNode ) {
  1318. super();
  1319. /**
  1320. * The array-like node.
  1321. *
  1322. * @type {Node}
  1323. */
  1324. this.node = node;
  1325. /**
  1326. * The index node that defines the element access.
  1327. *
  1328. * @type {Node}
  1329. */
  1330. this.indexNode = indexNode;
  1331. /**
  1332. * This flag can be used for type testing.
  1333. *
  1334. * @type {Boolean}
  1335. * @readonly
  1336. * @default true
  1337. */
  1338. this.isArrayElementNode = true;
  1339. }
  1340. /**
  1341. * This method is overwritten since the node type is inferred from the array-like node.
  1342. *
  1343. * @param {NodeBuilder} builder - The current node builder.
  1344. * @return {String} The node type.
  1345. */
  1346. getNodeType( builder ) {
  1347. return this.node.getElementType( builder );
  1348. }
  1349. generate( builder ) {
  1350. const nodeSnippet = this.node.build( builder );
  1351. const indexSnippet = this.indexNode.build( builder, 'uint' );
  1352. return `${nodeSnippet}[ ${indexSnippet} ]`;
  1353. }
  1354. }
  1355. /**
  1356. * This module is part of the TSL core and usually not used in app level code.
  1357. * It represents a convert operation during the shader generation process
  1358. * meaning it converts the data type of a node to a target data type.
  1359. *
  1360. * @augments Node
  1361. */
  1362. class ConvertNode extends Node {
  1363. static get type() {
  1364. return 'ConvertNode';
  1365. }
  1366. /**
  1367. * Constructs a new convert node.
  1368. *
  1369. * @param {Node} node - The node which type should be converted.
  1370. * @param {String} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1371. */
  1372. constructor( node, convertTo ) {
  1373. super();
  1374. /**
  1375. * The node which type should be converted.
  1376. *
  1377. * @type {Node}
  1378. */
  1379. this.node = node;
  1380. /**
  1381. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1382. *
  1383. * @type {String}
  1384. */
  1385. this.convertTo = convertTo;
  1386. }
  1387. /**
  1388. * This method is overwritten since the implementation tries to infer the best
  1389. * matching type from the {@link ConvertNode#convertTo} property.
  1390. *
  1391. * @param {NodeBuilder} builder - The current node builder.
  1392. * @return {String} The node type.
  1393. */
  1394. getNodeType( builder ) {
  1395. const requestType = this.node.getNodeType( builder );
  1396. let convertTo = null;
  1397. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1398. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1399. convertTo = overloadingType;
  1400. }
  1401. }
  1402. return convertTo;
  1403. }
  1404. serialize( data ) {
  1405. super.serialize( data );
  1406. data.convertTo = this.convertTo;
  1407. }
  1408. deserialize( data ) {
  1409. super.deserialize( data );
  1410. this.convertTo = data.convertTo;
  1411. }
  1412. generate( builder, output ) {
  1413. const node = this.node;
  1414. const type = this.getNodeType( builder );
  1415. const snippet = node.build( builder, type );
  1416. return builder.format( snippet, type, output );
  1417. }
  1418. }
  1419. /**
  1420. * This module uses cache management to create temporary variables
  1421. * if the node is used more than once to prevent duplicate calculations.
  1422. *
  1423. * The class acts as a base class for many other nodes types.
  1424. *
  1425. * @augments Node
  1426. */
  1427. class TempNode extends Node {
  1428. static get type() {
  1429. return 'TempNode';
  1430. }
  1431. /**
  1432. * Constructs a temp node.
  1433. *
  1434. * @param {String?} nodeType - The node type.
  1435. */
  1436. constructor( nodeType = null ) {
  1437. super( nodeType );
  1438. /**
  1439. * This flag can be used for type testing.
  1440. *
  1441. * @type {Boolean}
  1442. * @readonly
  1443. * @default true
  1444. */
  1445. this.isTempNode = true;
  1446. }
  1447. /**
  1448. * Whether this node is used more than once in context of other nodes.
  1449. *
  1450. * @param {NodeBuilder} builder - The node builder.
  1451. * @return {Boolean} A flag that indicates if there is more than one dependency to other nodes.
  1452. */
  1453. hasDependencies( builder ) {
  1454. return builder.getDataFromNode( this ).usageCount > 1;
  1455. }
  1456. build( builder, output ) {
  1457. const buildStage = builder.getBuildStage();
  1458. if ( buildStage === 'generate' ) {
  1459. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1460. const nodeData = builder.getDataFromNode( this );
  1461. if ( nodeData.propertyName !== undefined ) {
  1462. return builder.format( nodeData.propertyName, type, output );
  1463. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1464. const snippet = super.build( builder, type );
  1465. const nodeVar = builder.getVarFromNode( this, null, type );
  1466. const propertyName = builder.getPropertyName( nodeVar );
  1467. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  1468. nodeData.snippet = snippet;
  1469. nodeData.propertyName = propertyName;
  1470. return builder.format( nodeData.propertyName, type, output );
  1471. }
  1472. }
  1473. return super.build( builder, output );
  1474. }
  1475. }
  1476. /**
  1477. * This module is part of the TSL core and usually not used in app level code.
  1478. * It represents a join operation during the shader generation process.
  1479. * For example in can compose/join two single floats into a `vec2` type.
  1480. *
  1481. * @augments TempNode
  1482. */
  1483. class JoinNode extends TempNode {
  1484. static get type() {
  1485. return 'JoinNode';
  1486. }
  1487. /**
  1488. * Constructs a new join node.
  1489. *
  1490. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1491. * @param {String?} [nodeType=null] - The node type.
  1492. */
  1493. constructor( nodes = [], nodeType = null ) {
  1494. super( nodeType );
  1495. /**
  1496. * An array of nodes that should be joined.
  1497. *
  1498. * @type {Array<Node>}
  1499. */
  1500. this.nodes = nodes;
  1501. }
  1502. /**
  1503. * This method is overwritten since the node type must be inferred from the
  1504. * joined data length if not explicitly defined.
  1505. *
  1506. * @param {NodeBuilder} builder - The current node builder.
  1507. * @return {String} The node type.
  1508. */
  1509. getNodeType( builder ) {
  1510. if ( this.nodeType !== null ) {
  1511. return builder.getVectorType( this.nodeType );
  1512. }
  1513. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1514. }
  1515. generate( builder, output ) {
  1516. const type = this.getNodeType( builder );
  1517. const nodes = this.nodes;
  1518. const primitiveType = builder.getComponentType( type );
  1519. const snippetValues = [];
  1520. for ( const input of nodes ) {
  1521. let inputSnippet = input.build( builder );
  1522. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  1523. if ( inputPrimitiveType !== primitiveType ) {
  1524. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  1525. }
  1526. snippetValues.push( inputSnippet );
  1527. }
  1528. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1529. return builder.format( snippet, type, output );
  1530. }
  1531. }
  1532. const _stringVectorComponents = vectorComponents.join( '' );
  1533. /**
  1534. * This module is part of the TSL core and usually not used in app level code.
  1535. * `SplitNode` represents a property access operation which means it is
  1536. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1537. * For example:
  1538. * ```js
  1539. * const redValue = color.r;
  1540. * ```
  1541. *
  1542. * @augments Node
  1543. */
  1544. class SplitNode extends Node {
  1545. static get type() {
  1546. return 'SplitNode';
  1547. }
  1548. /**
  1549. * Constructs a new split node.
  1550. *
  1551. * @param {Node} node - The node that should be accessed.
  1552. * @param {String} [components='x'] - The components that should be accessed.
  1553. */
  1554. constructor( node, components = 'x' ) {
  1555. super();
  1556. /**
  1557. * The node that should be accessed.
  1558. *
  1559. * @type {Node}
  1560. */
  1561. this.node = node;
  1562. /**
  1563. * The components that should be accessed.
  1564. *
  1565. * @type {string}
  1566. */
  1567. this.components = components;
  1568. /**
  1569. * This flag can be used for type testing.
  1570. *
  1571. * @type {Boolean}
  1572. * @readonly
  1573. * @default true
  1574. */
  1575. this.isSplitNode = true;
  1576. }
  1577. /**
  1578. * Returns the vector length which is computed based on the requested components.
  1579. *
  1580. * @return {Number} The vector length.
  1581. */
  1582. getVectorLength() {
  1583. let vectorLength = this.components.length;
  1584. for ( const c of this.components ) {
  1585. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1586. }
  1587. return vectorLength;
  1588. }
  1589. /**
  1590. * Returns the component type of the node's type.
  1591. *
  1592. * @param {NodeBuilder} builder - The current node builder.
  1593. * @return {String} The component type.
  1594. */
  1595. getComponentType( builder ) {
  1596. return builder.getComponentType( this.node.getNodeType( builder ) );
  1597. }
  1598. /**
  1599. * This method is overwritten since the node type is inferred from requested components.
  1600. *
  1601. * @param {NodeBuilder} builder - The current node builder.
  1602. * @return {String} The node type.
  1603. */
  1604. getNodeType( builder ) {
  1605. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1606. }
  1607. generate( builder, output ) {
  1608. const node = this.node;
  1609. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1610. let snippet = null;
  1611. if ( nodeTypeLength > 1 ) {
  1612. let type = null;
  1613. const componentsLength = this.getVectorLength();
  1614. if ( componentsLength >= nodeTypeLength ) {
  1615. // needed expand the input node
  1616. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1617. }
  1618. const nodeSnippet = node.build( builder, type );
  1619. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1620. // unnecessary swizzle
  1621. snippet = builder.format( nodeSnippet, type, output );
  1622. } else {
  1623. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1624. }
  1625. } else {
  1626. // ignore .components if .node returns float/integer
  1627. snippet = node.build( builder, output );
  1628. }
  1629. return snippet;
  1630. }
  1631. serialize( data ) {
  1632. super.serialize( data );
  1633. data.components = this.components;
  1634. }
  1635. deserialize( data ) {
  1636. super.deserialize( data );
  1637. this.components = data.components;
  1638. }
  1639. }
  1640. /**
  1641. * This module is part of the TSL core and usually not used in app level code.
  1642. * `SetNode` represents a set operation which means it is used to implement any
  1643. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1644. * For example:
  1645. * ```js
  1646. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1647. * ```
  1648. *
  1649. * @augments TempNode
  1650. */
  1651. class SetNode extends TempNode {
  1652. static get type() {
  1653. return 'SetNode';
  1654. }
  1655. /**
  1656. * Constructs a new set node.
  1657. *
  1658. * @param {Node} sourceNode - The node that should be updated.
  1659. * @param {String} components - The components that should be updated.
  1660. * @param {Node} targetNode - The value node.
  1661. */
  1662. constructor( sourceNode, components, targetNode ) {
  1663. super();
  1664. /**
  1665. * The node that should be updated.
  1666. *
  1667. * @type {Node}
  1668. */
  1669. this.sourceNode = sourceNode;
  1670. /**
  1671. * The components that should be updated.
  1672. *
  1673. * @type {String}
  1674. */
  1675. this.components = components;
  1676. /**
  1677. * The value node.
  1678. *
  1679. * @type {Node}
  1680. */
  1681. this.targetNode = targetNode;
  1682. }
  1683. /**
  1684. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1685. *
  1686. * @param {NodeBuilder} builder - The current node builder.
  1687. * @return {String} The node type.
  1688. */
  1689. getNodeType( builder ) {
  1690. return this.sourceNode.getNodeType( builder );
  1691. }
  1692. generate( builder ) {
  1693. const { sourceNode, components, targetNode } = this;
  1694. const sourceType = this.getNodeType( builder );
  1695. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1696. const targetType = builder.getTypeFromLength( components.length, componentType );
  1697. const targetSnippet = targetNode.build( builder, targetType );
  1698. const sourceSnippet = sourceNode.build( builder, sourceType );
  1699. const length = builder.getTypeLength( sourceType );
  1700. const snippetValues = [];
  1701. for ( let i = 0; i < length; i ++ ) {
  1702. const component = vectorComponents[ i ];
  1703. if ( component === components[ 0 ] ) {
  1704. snippetValues.push( targetSnippet );
  1705. i += components.length - 1;
  1706. } else {
  1707. snippetValues.push( sourceSnippet + '.' + component );
  1708. }
  1709. }
  1710. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1711. }
  1712. }
  1713. /**
  1714. * This module is part of the TSL core and usually not used in app level code.
  1715. * It represents a flip operation during the shader generation process
  1716. * meaning it flips normalized values with the following formula:
  1717. * ```
  1718. * x = 1 - x;
  1719. * ```
  1720. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1721. * `flipSTPQ()` method invocations on node objects. For example:
  1722. * ```js
  1723. * uvNode = uvNode.flipY();
  1724. * ```
  1725. *
  1726. * @augments TempNode
  1727. */
  1728. class FlipNode extends TempNode {
  1729. static get type() {
  1730. return 'FlipNode';
  1731. }
  1732. /**
  1733. * Constructs a new flip node.
  1734. *
  1735. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1736. * @param {String} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1737. */
  1738. constructor( sourceNode, components ) {
  1739. super();
  1740. /**
  1741. * The node which component(s) should be flipped.
  1742. *
  1743. * @type {Node}
  1744. */
  1745. this.sourceNode = sourceNode;
  1746. /**
  1747. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1748. *
  1749. * @type {String}
  1750. */
  1751. this.components = components;
  1752. }
  1753. /**
  1754. * This method is overwritten since the node type is inferred from the source node.
  1755. *
  1756. * @param {NodeBuilder} builder - The current node builder.
  1757. * @return {String} The node type.
  1758. */
  1759. getNodeType( builder ) {
  1760. return this.sourceNode.getNodeType( builder );
  1761. }
  1762. generate( builder ) {
  1763. const { components, sourceNode } = this;
  1764. const sourceType = this.getNodeType( builder );
  1765. const sourceSnippet = sourceNode.build( builder );
  1766. const sourceCache = builder.getVarFromNode( this );
  1767. const sourceProperty = builder.getPropertyName( sourceCache );
  1768. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1769. const length = builder.getTypeLength( sourceType );
  1770. const snippetValues = [];
  1771. let componentIndex = 0;
  1772. for ( let i = 0; i < length; i ++ ) {
  1773. const component = vectorComponents[ i ];
  1774. if ( component === components[ componentIndex ] ) {
  1775. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1776. componentIndex ++;
  1777. } else {
  1778. snippetValues.push( sourceProperty + '.' + component );
  1779. }
  1780. }
  1781. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1782. }
  1783. }
  1784. /**
  1785. * Base class for representing data input nodes.
  1786. *
  1787. * @augments Node
  1788. */
  1789. class InputNode extends Node {
  1790. static get type() {
  1791. return 'InputNode';
  1792. }
  1793. /**
  1794. * Constructs a new input node.
  1795. *
  1796. * @param {Any} value - The value of this node. This can be a any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1797. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1798. */
  1799. constructor( value, nodeType = null ) {
  1800. super( nodeType );
  1801. /**
  1802. * This flag can be used for type testing.
  1803. *
  1804. * @type {Boolean}
  1805. * @readonly
  1806. * @default true
  1807. */
  1808. this.isInputNode = true;
  1809. /**
  1810. * The value of this node. This can be a any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1811. *
  1812. * @type {Any}
  1813. */
  1814. this.value = value;
  1815. /**
  1816. * The precision of the value in the shader.
  1817. *
  1818. * @type {('low'|'medium'|'high')?}
  1819. * @default null
  1820. */
  1821. this.precision = null;
  1822. }
  1823. getNodeType( /*builder*/ ) {
  1824. if ( this.nodeType === null ) {
  1825. return getValueType( this.value );
  1826. }
  1827. return this.nodeType;
  1828. }
  1829. /**
  1830. * Returns the input type of the node which is by default the node type. Derived modules
  1831. * might overwrite this method and use a fixed type or compute one analytically.
  1832. *
  1833. * A typical example for different input and node types are textures. The input type of a
  1834. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  1835. *
  1836. * @param {NodeBuilder} builder - The current node builder.
  1837. * @return {String} The input type.
  1838. */
  1839. getInputType( builder ) {
  1840. return this.getNodeType( builder );
  1841. }
  1842. /**
  1843. * Sets the precision to the given value. The method can be
  1844. * overwritten in derived classes if the final precision must be computed
  1845. * analytically.
  1846. *
  1847. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  1848. * @return {InputNode} A reference to this node.
  1849. */
  1850. setPrecision( precision ) {
  1851. this.precision = precision;
  1852. return this;
  1853. }
  1854. serialize( data ) {
  1855. super.serialize( data );
  1856. data.value = this.value;
  1857. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  1858. data.valueType = getValueType( this.value );
  1859. data.nodeType = this.nodeType;
  1860. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  1861. data.precision = this.precision;
  1862. }
  1863. deserialize( data ) {
  1864. super.deserialize( data );
  1865. this.nodeType = data.nodeType;
  1866. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  1867. this.precision = data.precision || null;
  1868. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  1869. }
  1870. generate( /*builder, output*/ ) {
  1871. console.warn( 'Abstract function.' );
  1872. }
  1873. }
  1874. /**
  1875. * Class for representing a constant value in the shader.
  1876. *
  1877. * @augments InputNode
  1878. */
  1879. class ConstNode extends InputNode {
  1880. static get type() {
  1881. return 'ConstNode';
  1882. }
  1883. /**
  1884. * Constructs a new input node.
  1885. *
  1886. * @param {Any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  1887. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1888. */
  1889. constructor( value, nodeType = null ) {
  1890. super( value, nodeType );
  1891. /**
  1892. * This flag can be used for type testing.
  1893. *
  1894. * @type {Boolean}
  1895. * @readonly
  1896. * @default true
  1897. */
  1898. this.isConstNode = true;
  1899. }
  1900. /**
  1901. * Generates the shader string of the value with the current node builder.
  1902. *
  1903. * @param {NodeBuilder} builder - The current node builder.
  1904. * @return {String} The generated value as a shader string.
  1905. */
  1906. generateConst( builder ) {
  1907. return builder.generateConst( this.getNodeType( builder ), this.value );
  1908. }
  1909. generate( builder, output ) {
  1910. const type = this.getNodeType( builder );
  1911. return builder.format( this.generateConst( builder ), type, output );
  1912. }
  1913. }
  1914. //
  1915. let currentStack = null;
  1916. const NodeElements = new Map();
  1917. function addMethodChaining( name, nodeElement ) {
  1918. if ( NodeElements.has( name ) ) {
  1919. console.warn( `Redefinition of method chaining ${ name }` );
  1920. return;
  1921. }
  1922. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  1923. NodeElements.set( name, nodeElement );
  1924. }
  1925. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  1926. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  1927. const shaderNodeHandler = {
  1928. setup( NodeClosure, params ) {
  1929. const inputs = params.shift();
  1930. return NodeClosure( nodeObjects( inputs ), ...params );
  1931. },
  1932. get( node, prop, nodeObj ) {
  1933. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1934. if ( node.isStackNode !== true && prop === 'assign' ) {
  1935. return ( ...params ) => {
  1936. currentStack.assign( nodeObj, ...params );
  1937. return nodeObj;
  1938. };
  1939. } else if ( NodeElements.has( prop ) ) {
  1940. const nodeElement = NodeElements.get( prop );
  1941. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  1942. } else if ( prop === 'self' ) {
  1943. return node;
  1944. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  1945. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  1946. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  1947. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  1948. // accessing properties ( swizzle )
  1949. prop = parseSwizzle( prop );
  1950. return nodeObject( new SplitNode( nodeObj, prop ) );
  1951. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1952. // set properties ( swizzle ) and sort to xyzw sequence
  1953. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  1954. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  1955. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1956. // set properties ( swizzle ) and sort to xyzw sequence
  1957. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  1958. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  1959. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  1960. // accessing property
  1961. if ( prop === 'width' ) prop = 'x';
  1962. else if ( prop === 'height' ) prop = 'y';
  1963. else if ( prop === 'depth' ) prop = 'z';
  1964. return nodeObject( new SplitNode( node, prop ) );
  1965. } else if ( /^\d+$/.test( prop ) === true ) {
  1966. // accessing array
  1967. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  1968. }
  1969. }
  1970. return Reflect.get( node, prop, nodeObj );
  1971. },
  1972. set( node, prop, value, nodeObj ) {
  1973. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1974. // setting properties
  1975. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  1976. nodeObj[ prop ].assign( value );
  1977. return true;
  1978. }
  1979. }
  1980. return Reflect.set( node, prop, value, nodeObj );
  1981. }
  1982. };
  1983. const nodeObjectsCacheMap = new WeakMap();
  1984. const nodeBuilderFunctionsCacheMap = new WeakMap();
  1985. const ShaderNodeObject = function ( obj, altType = null ) {
  1986. const type = getValueType( obj );
  1987. if ( type === 'node' ) {
  1988. let nodeObject = nodeObjectsCacheMap.get( obj );
  1989. if ( nodeObject === undefined ) {
  1990. nodeObject = new Proxy( obj, shaderNodeHandler );
  1991. nodeObjectsCacheMap.set( obj, nodeObject );
  1992. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  1993. }
  1994. return nodeObject;
  1995. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  1996. return nodeObject( getConstNode( obj, altType ) );
  1997. } else if ( type === 'shader' ) {
  1998. return Fn( obj );
  1999. }
  2000. return obj;
  2001. };
  2002. const ShaderNodeObjects = function ( objects, altType = null ) {
  2003. for ( const name in objects ) {
  2004. objects[ name ] = nodeObject( objects[ name ], altType );
  2005. }
  2006. return objects;
  2007. };
  2008. const ShaderNodeArray = function ( array, altType = null ) {
  2009. const len = array.length;
  2010. for ( let i = 0; i < len; i ++ ) {
  2011. array[ i ] = nodeObject( array[ i ], altType );
  2012. }
  2013. return array;
  2014. };
  2015. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2016. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  2017. if ( scope === null ) {
  2018. return ( ...params ) => {
  2019. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  2020. };
  2021. } else if ( factor !== null ) {
  2022. factor = nodeObject( factor );
  2023. return ( ...params ) => {
  2024. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  2025. };
  2026. } else {
  2027. return ( ...params ) => {
  2028. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  2029. };
  2030. }
  2031. };
  2032. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2033. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  2034. };
  2035. class ShaderCallNodeInternal extends Node {
  2036. constructor( shaderNode, inputNodes ) {
  2037. super();
  2038. this.shaderNode = shaderNode;
  2039. this.inputNodes = inputNodes;
  2040. }
  2041. getNodeType( builder ) {
  2042. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2043. }
  2044. call( builder ) {
  2045. const { shaderNode, inputNodes } = this;
  2046. const properties = builder.getNodeProperties( shaderNode );
  2047. if ( properties.onceOutput ) return properties.onceOutput;
  2048. //
  2049. let result = null;
  2050. if ( shaderNode.layout ) {
  2051. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2052. if ( functionNodesCacheMap === undefined ) {
  2053. functionNodesCacheMap = new WeakMap();
  2054. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2055. }
  2056. let functionNode = functionNodesCacheMap.get( shaderNode );
  2057. if ( functionNode === undefined ) {
  2058. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2059. functionNodesCacheMap.set( shaderNode, functionNode );
  2060. }
  2061. if ( builder.currentFunctionNode !== null ) {
  2062. builder.currentFunctionNode.includes.push( functionNode );
  2063. }
  2064. result = nodeObject( functionNode.call( inputNodes ) );
  2065. } else {
  2066. const jsFunc = shaderNode.jsFunc;
  2067. const outputNode = inputNodes !== null ? jsFunc( inputNodes, builder ) : jsFunc( builder );
  2068. result = nodeObject( outputNode );
  2069. }
  2070. if ( shaderNode.once ) {
  2071. properties.onceOutput = result;
  2072. }
  2073. return result;
  2074. }
  2075. getOutputNode( builder ) {
  2076. const properties = builder.getNodeProperties( this );
  2077. if ( properties.outputNode === null ) {
  2078. properties.outputNode = this.setupOutput( builder );
  2079. }
  2080. return properties.outputNode;
  2081. }
  2082. setup( builder ) {
  2083. return this.getOutputNode( builder );
  2084. }
  2085. setupOutput( builder ) {
  2086. builder.addStack();
  2087. builder.stack.outputNode = this.call( builder );
  2088. return builder.removeStack();
  2089. }
  2090. generate( builder, output ) {
  2091. const outputNode = this.getOutputNode( builder );
  2092. return outputNode.build( builder, output );
  2093. }
  2094. }
  2095. class ShaderNodeInternal extends Node {
  2096. constructor( jsFunc, nodeType ) {
  2097. super( nodeType );
  2098. this.jsFunc = jsFunc;
  2099. this.layout = null;
  2100. this.global = true;
  2101. this.once = false;
  2102. }
  2103. setLayout( layout ) {
  2104. this.layout = layout;
  2105. return this;
  2106. }
  2107. call( inputs = null ) {
  2108. nodeObjects( inputs );
  2109. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  2110. }
  2111. setup() {
  2112. return this.call();
  2113. }
  2114. }
  2115. const bools = [ false, true ];
  2116. const uints = [ 0, 1, 2, 3 ];
  2117. const ints = [ - 1, - 2 ];
  2118. 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 ];
  2119. const boolsCacheMap = new Map();
  2120. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2121. const uintsCacheMap = new Map();
  2122. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2123. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2124. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2125. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2126. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2127. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2128. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2129. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2130. const getConstNode = ( value, type ) => {
  2131. if ( constNodesCacheMap.has( value ) ) {
  2132. return constNodesCacheMap.get( value );
  2133. } else if ( value.isNode === true ) {
  2134. return value;
  2135. } else {
  2136. return new ConstNode( value, type );
  2137. }
  2138. };
  2139. const safeGetNodeType = ( node ) => {
  2140. try {
  2141. return node.getNodeType();
  2142. } catch ( _ ) {
  2143. return undefined;
  2144. }
  2145. };
  2146. const ConvertType = function ( type, cacheMap = null ) {
  2147. return ( ...params ) => {
  2148. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  2149. params = [ getValueFromType( type, ...params ) ];
  2150. }
  2151. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2152. return nodeObject( cacheMap.get( params[ 0 ] ) );
  2153. }
  2154. if ( params.length === 1 ) {
  2155. const node = getConstNode( params[ 0 ], type );
  2156. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  2157. return nodeObject( new ConvertNode( node, type ) );
  2158. }
  2159. const nodes = params.map( param => getConstNode( param ) );
  2160. return nodeObject( new JoinNode( nodes, type ) );
  2161. };
  2162. };
  2163. // exports
  2164. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2165. // utils
  2166. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2167. // shader node base
  2168. function ShaderNode( jsFunc, nodeType ) {
  2169. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  2170. }
  2171. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2172. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2173. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2174. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  2175. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  2176. const Fn = ( jsFunc, nodeType ) => {
  2177. const shaderNode = new ShaderNode( jsFunc, nodeType );
  2178. const fn = ( ...params ) => {
  2179. let inputs;
  2180. nodeObjects( params );
  2181. if ( params[ 0 ] && params[ 0 ].isNode ) {
  2182. inputs = [ ...params ];
  2183. } else {
  2184. inputs = params[ 0 ];
  2185. }
  2186. return shaderNode.call( inputs );
  2187. };
  2188. fn.shaderNode = shaderNode;
  2189. fn.setLayout = ( layout ) => {
  2190. shaderNode.setLayout( layout );
  2191. return fn;
  2192. };
  2193. fn.once = () => {
  2194. shaderNode.once = true;
  2195. return fn;
  2196. };
  2197. return fn;
  2198. };
  2199. const tslFn = ( ...params ) => { // @deprecated, r168
  2200. console.warn( 'TSL.ShaderNode: tslFn() has been renamed to Fn().' );
  2201. return Fn( ...params );
  2202. };
  2203. //
  2204. addMethodChaining( 'toGlobal', ( node ) => {
  2205. node.global = true;
  2206. return node;
  2207. } );
  2208. //
  2209. const setCurrentStack = ( stack ) => {
  2210. currentStack = stack;
  2211. };
  2212. const getCurrentStack = () => currentStack;
  2213. const If = ( ...params ) => currentStack.If( ...params );
  2214. function append( node ) {
  2215. if ( currentStack ) currentStack.add( node );
  2216. return node;
  2217. }
  2218. addMethodChaining( 'append', append );
  2219. // types
  2220. const color = new ConvertType( 'color' );
  2221. const float = new ConvertType( 'float', cacheMaps.float );
  2222. const int = new ConvertType( 'int', cacheMaps.ints );
  2223. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2224. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2225. const vec2 = new ConvertType( 'vec2' );
  2226. const ivec2 = new ConvertType( 'ivec2' );
  2227. const uvec2 = new ConvertType( 'uvec2' );
  2228. const bvec2 = new ConvertType( 'bvec2' );
  2229. const vec3 = new ConvertType( 'vec3' );
  2230. const ivec3 = new ConvertType( 'ivec3' );
  2231. const uvec3 = new ConvertType( 'uvec3' );
  2232. const bvec3 = new ConvertType( 'bvec3' );
  2233. const vec4 = new ConvertType( 'vec4' );
  2234. const ivec4 = new ConvertType( 'ivec4' );
  2235. const uvec4 = new ConvertType( 'uvec4' );
  2236. const bvec4 = new ConvertType( 'bvec4' );
  2237. const mat2 = new ConvertType( 'mat2' );
  2238. const mat3 = new ConvertType( 'mat3' );
  2239. const mat4 = new ConvertType( 'mat4' );
  2240. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2241. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2242. addMethodChaining( 'toColor', color );
  2243. addMethodChaining( 'toFloat', float );
  2244. addMethodChaining( 'toInt', int );
  2245. addMethodChaining( 'toUint', uint );
  2246. addMethodChaining( 'toBool', bool );
  2247. addMethodChaining( 'toVec2', vec2 );
  2248. addMethodChaining( 'toIVec2', ivec2 );
  2249. addMethodChaining( 'toUVec2', uvec2 );
  2250. addMethodChaining( 'toBVec2', bvec2 );
  2251. addMethodChaining( 'toVec3', vec3 );
  2252. addMethodChaining( 'toIVec3', ivec3 );
  2253. addMethodChaining( 'toUVec3', uvec3 );
  2254. addMethodChaining( 'toBVec3', bvec3 );
  2255. addMethodChaining( 'toVec4', vec4 );
  2256. addMethodChaining( 'toIVec4', ivec4 );
  2257. addMethodChaining( 'toUVec4', uvec4 );
  2258. addMethodChaining( 'toBVec4', bvec4 );
  2259. addMethodChaining( 'toMat2', mat2 );
  2260. addMethodChaining( 'toMat3', mat3 );
  2261. addMethodChaining( 'toMat4', mat4 );
  2262. // basic nodes
  2263. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode );
  2264. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2265. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2266. addMethodChaining( 'element', element );
  2267. addMethodChaining( 'convert', convert );
  2268. /** @module UniformGroupNode **/
  2269. /**
  2270. * This node can be used to group single instances of {@link UniformNode}
  2271. * and manage them as a uniform buffer.
  2272. *
  2273. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  2274. * will be used when defining the {@link UniformNode#groupNode} property.
  2275. *
  2276. * - `objectGroup`: Uniform buffer per object.
  2277. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  2278. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  2279. *
  2280. * @augments Node
  2281. */
  2282. class UniformGroupNode extends Node {
  2283. static get type() {
  2284. return 'UniformGroupNode';
  2285. }
  2286. /**
  2287. * Constructs a new uniform group node.
  2288. *
  2289. * @param {String} name - The name of the uniform group node.
  2290. * @param {Boolean} [shared=false] - Whether this uniform group node is shared or not.
  2291. * @param {Number} [order=1] - Influences the internal sorting.
  2292. */
  2293. constructor( name, shared = false, order = 1 ) {
  2294. super( 'string' );
  2295. /**
  2296. * The name of the uniform group node.
  2297. *
  2298. * @type {String}
  2299. */
  2300. this.name = name;
  2301. /**
  2302. * Whether this uniform group node is shared or not.
  2303. *
  2304. * @type {Boolean}
  2305. * @default false
  2306. */
  2307. this.shared = shared;
  2308. /**
  2309. * Influences the internal sorting.
  2310. * TODO: Add details when this property should be changed.
  2311. *
  2312. * @type {Number}
  2313. * @default 1
  2314. */
  2315. this.order = order;
  2316. /**
  2317. * This flag can be used for type testing.
  2318. *
  2319. * @type {Boolean}
  2320. * @readonly
  2321. * @default true
  2322. */
  2323. this.isUniformGroup = true;
  2324. }
  2325. serialize( data ) {
  2326. super.serialize( data );
  2327. data.name = this.name;
  2328. data.version = this.version;
  2329. data.shared = this.shared;
  2330. }
  2331. deserialize( data ) {
  2332. super.deserialize( data );
  2333. this.name = data.name;
  2334. this.version = data.version;
  2335. this.shared = data.shared;
  2336. }
  2337. }
  2338. /**
  2339. * TSL function for creating a uniform group node with the given name.
  2340. *
  2341. * @function
  2342. * @param {String} name - The name of the uniform group node.
  2343. * @returns {UniformGroupNode}
  2344. */
  2345. const uniformGroup = ( name ) => new UniformGroupNode( name );
  2346. /**
  2347. * TSL function for creating a shared uniform group node with the given name and order.
  2348. *
  2349. * @function
  2350. * @param {String} name - The name of the uniform group node.
  2351. * @param {Number} [order=0] - Influences the internal sorting.
  2352. * @returns {UniformGroupNode}
  2353. */
  2354. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  2355. /**
  2356. * TSL object that represents a shared uniform group node which is updated once per frame.
  2357. *
  2358. * @type {UniformGroupNode}
  2359. */
  2360. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  2361. /**
  2362. * TSL object that represents a shared uniform group node which is updated once per render.
  2363. *
  2364. * @type {UniformGroupNode}
  2365. */
  2366. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  2367. /**
  2368. * TSL object that represents a uniform group node which is updated once per object.
  2369. *
  2370. * @type {UniformGroupNode}
  2371. */
  2372. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  2373. /** @module UniformNode **/
  2374. /**
  2375. * Class for representing a uniform.
  2376. *
  2377. * @augments InputNode
  2378. */
  2379. class UniformNode extends InputNode {
  2380. static get type() {
  2381. return 'UniformNode';
  2382. }
  2383. /**
  2384. * Constructs a new uniform node.
  2385. *
  2386. * @param {Any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2387. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2388. */
  2389. constructor( value, nodeType = null ) {
  2390. super( value, nodeType );
  2391. /**
  2392. * This flag can be used for type testing.
  2393. *
  2394. * @type {Boolean}
  2395. * @readonly
  2396. * @default true
  2397. */
  2398. this.isUniformNode = true;
  2399. /**
  2400. * The name or label of the uniform.
  2401. *
  2402. * @type {String}
  2403. * @default ''
  2404. */
  2405. this.name = '';
  2406. /**
  2407. * The uniform group of this uniform. By default, uniforms are
  2408. * managed per object but they might belong to a shared group
  2409. * which is updated per frame or render call.
  2410. *
  2411. * @type {UniformGroupNode}
  2412. */
  2413. this.groupNode = objectGroup;
  2414. }
  2415. /**
  2416. * Sets the {@link UniformNode#name} property.
  2417. *
  2418. * @param {String} name - The name of the uniform.
  2419. * @return {UniformNode} A reference to this node.
  2420. */
  2421. label( name ) {
  2422. this.name = name;
  2423. return this;
  2424. }
  2425. /**
  2426. * Sets the {@link UniformNode#groupNode} property.
  2427. *
  2428. * @param {UniformGroupNode} group - The uniform group.
  2429. * @return {UniformNode} A reference to this node.
  2430. */
  2431. setGroup( group ) {
  2432. this.groupNode = group;
  2433. return this;
  2434. }
  2435. /**
  2436. * Returns the {@link UniformNode#groupNode}.
  2437. *
  2438. * @return {UniformGroupNode} The uniform group.
  2439. */
  2440. getGroup() {
  2441. return this.groupNode;
  2442. }
  2443. /**
  2444. * By default, this method returns the result of {@link Node#getHash} but derived
  2445. * classes might overwrite this method with a different implementation.
  2446. *
  2447. * @param {NodeBuilder} builder - The current node builder.
  2448. * @return {String} The uniform hash.
  2449. */
  2450. getUniformHash( builder ) {
  2451. return this.getHash( builder );
  2452. }
  2453. onUpdate( callback, updateType ) {
  2454. const self = this.getSelf();
  2455. callback = callback.bind( self );
  2456. return super.onUpdate( ( frame ) => {
  2457. const value = callback( frame, self );
  2458. if ( value !== undefined ) {
  2459. this.value = value;
  2460. }
  2461. }, updateType );
  2462. }
  2463. generate( builder, output ) {
  2464. const type = this.getNodeType( builder );
  2465. const hash = this.getUniformHash( builder );
  2466. let sharedNode = builder.getNodeFromHash( hash );
  2467. if ( sharedNode === undefined ) {
  2468. builder.setHashNode( this, hash );
  2469. sharedNode = this;
  2470. }
  2471. const sharedNodeType = sharedNode.getInputType( builder );
  2472. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  2473. const propertyName = builder.getPropertyName( nodeUniform );
  2474. if ( builder.context.label !== undefined ) delete builder.context.label;
  2475. return builder.format( propertyName, type, output );
  2476. }
  2477. }
  2478. /**
  2479. * TSL function for creating a uniform node.
  2480. *
  2481. * @function
  2482. * @param {Any} arg1 - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2483. * @param {String?} arg2 - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2484. * @returns {UniformNode}
  2485. */
  2486. const uniform = ( arg1, arg2 ) => {
  2487. const nodeType = getConstNodeType( arg2 || arg1 );
  2488. // @TODO: get ConstNode from .traverse() in the future
  2489. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  2490. return nodeObject( new UniformNode( value, nodeType ) );
  2491. };
  2492. /** @module PropertyNode **/
  2493. /**
  2494. * This class represents a shader property. It can be used
  2495. * to explicitly define a property and assign a value to it.
  2496. *
  2497. * ```js
  2498. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2499. *```
  2500. * `PropertyNode` is used by the engine to predefined common material properties
  2501. * for TSL code.
  2502. *
  2503. * @augments Node
  2504. */
  2505. class PropertyNode extends Node {
  2506. static get type() {
  2507. return 'PropertyNode';
  2508. }
  2509. /**
  2510. * Constructs a new property node.
  2511. *
  2512. * @param {String} nodeType - The type of the node.
  2513. * @param {String?} [name=null] - The name of the property in the shader.
  2514. * @param {Boolean} [varying=false] - Whether this property is a varying or not.
  2515. */
  2516. constructor( nodeType, name = null, varying = false ) {
  2517. super( nodeType );
  2518. /**
  2519. * The name of the property in the shader. If no name is defined,
  2520. * the node system auto-generates one.
  2521. *
  2522. * @type {String?}
  2523. * @default null
  2524. */
  2525. this.name = name;
  2526. /**
  2527. * Whether this property is a varying or not.
  2528. *
  2529. * @type {Boolean}
  2530. * @default false
  2531. */
  2532. this.varying = varying;
  2533. /**
  2534. * This flag can be used for type testing.
  2535. *
  2536. * @type {Boolean}
  2537. * @readonly
  2538. * @default true
  2539. */
  2540. this.isPropertyNode = true;
  2541. }
  2542. getHash( builder ) {
  2543. return this.name || super.getHash( builder );
  2544. }
  2545. /**
  2546. * The method is overwritten so it always returns `true`.
  2547. *
  2548. * @param {NodeBuilder} builder - The current node builder.
  2549. * @return {Boolean} Whether this node is global or not.
  2550. */
  2551. isGlobal( /*builder*/ ) {
  2552. return true;
  2553. }
  2554. generate( builder ) {
  2555. let nodeVar;
  2556. if ( this.varying === true ) {
  2557. nodeVar = builder.getVaryingFromNode( this, this.name );
  2558. nodeVar.needsInterpolation = true;
  2559. } else {
  2560. nodeVar = builder.getVarFromNode( this, this.name );
  2561. }
  2562. return builder.getPropertyName( nodeVar );
  2563. }
  2564. }
  2565. /**
  2566. * TSL function for creating a property node.
  2567. *
  2568. * @function
  2569. * @param {String} type - The type of the node.
  2570. * @param {String?} [name=null] - The name of the property in the shader.
  2571. * @returns {PropertyNode}
  2572. */
  2573. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2574. /**
  2575. * TSL function for creating a varying property node.
  2576. *
  2577. * @function
  2578. * @param {String} type - The type of the node.
  2579. * @param {String?} [name=null] - The name of the varying in the shader.
  2580. * @returns {PropertyNode}
  2581. */
  2582. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2583. /**
  2584. * TSL object that represents the shader variable `DiffuseColor`.
  2585. *
  2586. * @type {PropertyNode<vec4>}
  2587. */
  2588. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2589. /**
  2590. * TSL object that represents the shader variable `EmissiveColor`.
  2591. *
  2592. * @type {PropertyNode<vec3>}
  2593. */
  2594. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2595. /**
  2596. * TSL object that represents the shader variable `Roughness`.
  2597. *
  2598. * @type {PropertyNode<float>}
  2599. */
  2600. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2601. /**
  2602. * TSL object that represents the shader variable `Metalness`.
  2603. *
  2604. * @type {PropertyNode<float>}
  2605. */
  2606. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2607. /**
  2608. * TSL object that represents the shader variable `Clearcoat`.
  2609. *
  2610. * @type {PropertyNode<float>}
  2611. */
  2612. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2613. /**
  2614. * TSL object that represents the shader variable `ClearcoatRoughness`.
  2615. *
  2616. * @type {PropertyNode<float>}
  2617. */
  2618. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  2619. /**
  2620. * TSL object that represents the shader variable `Sheen`.
  2621. *
  2622. * @type {PropertyNode<vec3>}
  2623. */
  2624. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  2625. /**
  2626. * TSL object that represents the shader variable `SheenRoughness`.
  2627. *
  2628. * @type {PropertyNode<float>}
  2629. */
  2630. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  2631. /**
  2632. * TSL object that represents the shader variable `Iridescence`.
  2633. *
  2634. * @type {PropertyNode<float>}
  2635. */
  2636. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  2637. /**
  2638. * TSL object that represents the shader variable `IridescenceIOR`.
  2639. *
  2640. * @type {PropertyNode<float>}
  2641. */
  2642. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  2643. /**
  2644. * TSL object that represents the shader variable `IridescenceThickness`.
  2645. *
  2646. * @type {PropertyNode<float>}
  2647. */
  2648. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  2649. /**
  2650. * TSL object that represents the shader variable `AlphaT`.
  2651. *
  2652. * @type {PropertyNode<float>}
  2653. */
  2654. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  2655. /**
  2656. * TSL object that represents the shader variable `Anisotropy`.
  2657. *
  2658. * @type {PropertyNode<float>}
  2659. */
  2660. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  2661. /**
  2662. * TSL object that represents the shader variable `AnisotropyT`.
  2663. *
  2664. * @type {PropertyNode<vec3>}
  2665. */
  2666. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  2667. /**
  2668. * TSL object that represents the shader variable `AnisotropyB`.
  2669. *
  2670. * @type {PropertyNode<vec3>}
  2671. */
  2672. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  2673. /**
  2674. * TSL object that represents the shader variable `SpecularColor`.
  2675. *
  2676. * @type {PropertyNode<color>}
  2677. */
  2678. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  2679. /**
  2680. * TSL object that represents the shader variable `SpecularF90`.
  2681. *
  2682. * @type {PropertyNode<float>}
  2683. */
  2684. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  2685. /**
  2686. * TSL object that represents the shader variable `Shininess`.
  2687. *
  2688. * @type {PropertyNode<float>}
  2689. */
  2690. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  2691. /**
  2692. * TSL object that represents the shader variable `Output`.
  2693. *
  2694. * @type {PropertyNode<vec4>}
  2695. */
  2696. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  2697. /**
  2698. * TSL object that represents the shader variable `dashSize`.
  2699. *
  2700. * @type {PropertyNode<float>}
  2701. */
  2702. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  2703. /**
  2704. * TSL object that represents the shader variable `gapSize`.
  2705. *
  2706. * @type {PropertyNode<float>}
  2707. */
  2708. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  2709. /**
  2710. * TSL object that represents the shader variable `pointWidth`.
  2711. *
  2712. * @type {PropertyNode<float>}
  2713. */
  2714. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  2715. /**
  2716. * TSL object that represents the shader variable `IOR`.
  2717. *
  2718. * @type {PropertyNode<float>}
  2719. */
  2720. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  2721. /**
  2722. * TSL object that represents the shader variable `Transmission`.
  2723. *
  2724. * @type {PropertyNode<float>}
  2725. */
  2726. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  2727. /**
  2728. * TSL object that represents the shader variable `Thickness`.
  2729. *
  2730. * @type {PropertyNode<float>}
  2731. */
  2732. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  2733. /**
  2734. * TSL object that represents the shader variable `AttenuationDistance`.
  2735. *
  2736. * @type {PropertyNode<float>}
  2737. */
  2738. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  2739. /**
  2740. * TSL object that represents the shader variable `AttenuationColor`.
  2741. *
  2742. * @type {PropertyNode<color>}
  2743. */
  2744. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  2745. /**
  2746. * TSL object that represents the shader variable `Dispersion`.
  2747. *
  2748. * @type {PropertyNode<float>}
  2749. */
  2750. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  2751. /** @module AssignNode **/
  2752. /**
  2753. * These node represents an assign operation. Meaning a node is assigned
  2754. * to another node.
  2755. *
  2756. * @augments TempNode
  2757. */
  2758. class AssignNode extends TempNode {
  2759. static get type() {
  2760. return 'AssignNode';
  2761. }
  2762. /**
  2763. * Constructs a new assign node.
  2764. *
  2765. * @param {Node} targetNode - The target node.
  2766. * @param {Node} sourceNode - The source type.
  2767. */
  2768. constructor( targetNode, sourceNode ) {
  2769. super();
  2770. /**
  2771. * The target node.
  2772. *
  2773. * @type {Node}
  2774. */
  2775. this.targetNode = targetNode;
  2776. /**
  2777. * The source node.
  2778. *
  2779. * @type {Node}
  2780. */
  2781. this.sourceNode = sourceNode;
  2782. }
  2783. /**
  2784. * Whether this node is used more than once in context of other nodes. This method
  2785. * is overwritten since it always returns `false` (assigns are unique).
  2786. *
  2787. * @return {Boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  2788. */
  2789. hasDependencies() {
  2790. return false;
  2791. }
  2792. getNodeType( builder, output ) {
  2793. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  2794. }
  2795. /**
  2796. * Whether a split is required when assigning source to target. This can happen when the component length of
  2797. * target and source data type does not match.
  2798. *
  2799. * @param {NodeBuilder} builder - The current node builder.
  2800. * @return {Boolean} Whether a split is required when assigning source to target.
  2801. */
  2802. needsSplitAssign( builder ) {
  2803. const { targetNode } = this;
  2804. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  2805. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  2806. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  2807. return assignDifferentVector;
  2808. }
  2809. return false;
  2810. }
  2811. generate( builder, output ) {
  2812. const { targetNode, sourceNode } = this;
  2813. const needsSplitAssign = this.needsSplitAssign( builder );
  2814. const targetType = targetNode.getNodeType( builder );
  2815. const target = targetNode.context( { assign: true } ).build( builder );
  2816. const source = sourceNode.build( builder, targetType );
  2817. const sourceType = sourceNode.getNodeType( builder );
  2818. const nodeData = builder.getDataFromNode( this );
  2819. //
  2820. let snippet;
  2821. if ( nodeData.initialized === true ) {
  2822. if ( output !== 'void' ) {
  2823. snippet = target;
  2824. }
  2825. } else if ( needsSplitAssign ) {
  2826. const sourceVar = builder.getVarFromNode( this, null, targetType );
  2827. const sourceProperty = builder.getPropertyName( sourceVar );
  2828. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  2829. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  2830. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  2831. const component = targetNode.components[ i ];
  2832. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  2833. }
  2834. if ( output !== 'void' ) {
  2835. snippet = target;
  2836. }
  2837. } else {
  2838. snippet = `${ target } = ${ source }`;
  2839. if ( output === 'void' || sourceType === 'void' ) {
  2840. builder.addLineFlowCode( snippet, this );
  2841. if ( output !== 'void' ) {
  2842. snippet = target;
  2843. }
  2844. }
  2845. }
  2846. nodeData.initialized = true;
  2847. return builder.format( snippet, targetType, output );
  2848. }
  2849. }
  2850. /**
  2851. * TSL function for creating an assign node.
  2852. *
  2853. * @function
  2854. * @param {Node} targetNode - The target node.
  2855. * @param {Node} sourceNode - The source type.
  2856. * @returns {AssignNode}
  2857. */
  2858. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  2859. addMethodChaining( 'assign', assign );
  2860. /**
  2861. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  2862. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  2863. * this logic.
  2864. *
  2865. * @augments TempNode
  2866. */
  2867. class FunctionCallNode extends TempNode {
  2868. static get type() {
  2869. return 'FunctionCallNode';
  2870. }
  2871. /**
  2872. * Constructs a new function call node.
  2873. *
  2874. * @param {FunctionNode?} functionNode - The function node.
  2875. * @param {Object<String, Node>} [parameters={}] - The parameters for the function call.
  2876. */
  2877. constructor( functionNode = null, parameters = {} ) {
  2878. super();
  2879. /**
  2880. * The function node.
  2881. *
  2882. * @type {FunctionNode}
  2883. * @default null
  2884. */
  2885. this.functionNode = functionNode;
  2886. /**
  2887. * The parameters of the function call.
  2888. *
  2889. * @type {Object<String, Node>}
  2890. * @default {}
  2891. */
  2892. this.parameters = parameters;
  2893. }
  2894. /**
  2895. * Sets the parameters of the function call node.
  2896. *
  2897. * @param {Object<String, Node>} parameters - The parameters to set.
  2898. * @return {FunctionCallNode} A reference to this node.
  2899. */
  2900. setParameters( parameters ) {
  2901. this.parameters = parameters;
  2902. return this;
  2903. }
  2904. /**
  2905. * Returns the parameters of the function call node.
  2906. *
  2907. * @return {Object<String, Node>} The parameters of this node.
  2908. */
  2909. getParameters() {
  2910. return this.parameters;
  2911. }
  2912. getNodeType( builder ) {
  2913. return this.functionNode.getNodeType( builder );
  2914. }
  2915. generate( builder ) {
  2916. const params = [];
  2917. const functionNode = this.functionNode;
  2918. const inputs = functionNode.getInputs( builder );
  2919. const parameters = this.parameters;
  2920. const generateInput = ( node, inputNode ) => {
  2921. const type = inputNode.type;
  2922. const pointer = type === 'pointer';
  2923. let output;
  2924. if ( pointer ) output = '&' + node.build( builder );
  2925. else output = node.build( builder, type );
  2926. return output;
  2927. };
  2928. if ( Array.isArray( parameters ) ) {
  2929. for ( let i = 0; i < parameters.length; i ++ ) {
  2930. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  2931. }
  2932. } else {
  2933. for ( const inputNode of inputs ) {
  2934. const node = parameters[ inputNode.name ];
  2935. if ( node !== undefined ) {
  2936. params.push( generateInput( node, inputNode ) );
  2937. } else {
  2938. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  2939. }
  2940. }
  2941. }
  2942. const functionName = functionNode.build( builder, 'property' );
  2943. return `${functionName}( ${params.join( ', ' )} )`;
  2944. }
  2945. }
  2946. const call = ( func, ...params ) => {
  2947. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  2948. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  2949. };
  2950. addMethodChaining( 'call', call );
  2951. /** @module OperatorNode **/
  2952. /**
  2953. * This node represents basic mathematical and logical operations like addition,
  2954. * subtraction or comparisons (e.g. `equal()`).
  2955. *
  2956. * @augments TempNode
  2957. */
  2958. class OperatorNode extends TempNode {
  2959. static get type() {
  2960. return 'OperatorNode';
  2961. }
  2962. /**
  2963. * Constructs a new operator node.
  2964. *
  2965. * @param {String} op - The operator.
  2966. * @param {Node} aNode - The first input.
  2967. * @param {Node} bNode - The second input.
  2968. * @param {...Node} params - Additional input parameters.
  2969. */
  2970. constructor( op, aNode, bNode, ...params ) {
  2971. super();
  2972. if ( params.length > 0 ) {
  2973. let finalOp = new OperatorNode( op, aNode, bNode );
  2974. for ( let i = 0; i < params.length - 1; i ++ ) {
  2975. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  2976. }
  2977. aNode = finalOp;
  2978. bNode = params[ params.length - 1 ];
  2979. }
  2980. /**
  2981. * The operator.
  2982. *
  2983. * @type {String}
  2984. */
  2985. this.op = op;
  2986. /**
  2987. * The first input.
  2988. *
  2989. * @type {Node}
  2990. */
  2991. this.aNode = aNode;
  2992. /**
  2993. * The second input.
  2994. *
  2995. * @type {Node}
  2996. */
  2997. this.bNode = bNode;
  2998. }
  2999. /**
  3000. * This method is overwritten since the node type is inferred from the operator
  3001. * and the input node types.
  3002. *
  3003. * @param {NodeBuilder} builder - The current node builder.
  3004. * @param {String} output - The current output string.
  3005. * @return {String} The node type.
  3006. */
  3007. getNodeType( builder, output ) {
  3008. const op = this.op;
  3009. const aNode = this.aNode;
  3010. const bNode = this.bNode;
  3011. const typeA = aNode.getNodeType( builder );
  3012. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  3013. if ( typeA === 'void' || typeB === 'void' ) {
  3014. return 'void';
  3015. } else if ( op === '%' ) {
  3016. return typeA;
  3017. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3018. return builder.getIntegerType( typeA );
  3019. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  3020. return 'bool';
  3021. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3022. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3023. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3024. } else {
  3025. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  3026. return typeB;
  3027. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  3028. // matrix x vector
  3029. return builder.getVectorFromMatrix( typeA );
  3030. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  3031. // vector x matrix
  3032. return builder.getVectorFromMatrix( typeB );
  3033. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3034. // anytype x anytype: use the greater length vector
  3035. return typeB;
  3036. }
  3037. return typeA;
  3038. }
  3039. }
  3040. generate( builder, output ) {
  3041. const op = this.op;
  3042. const aNode = this.aNode;
  3043. const bNode = this.bNode;
  3044. const type = this.getNodeType( builder, output );
  3045. let typeA = null;
  3046. let typeB = null;
  3047. if ( type !== 'void' ) {
  3048. typeA = aNode.getNodeType( builder );
  3049. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  3050. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  3051. if ( builder.isVector( typeA ) ) {
  3052. typeB = typeA;
  3053. } else if ( typeA !== typeB ) {
  3054. typeA = typeB = 'float';
  3055. }
  3056. } else if ( op === '>>' || op === '<<' ) {
  3057. typeA = type;
  3058. typeB = builder.changeComponentType( typeB, 'uint' );
  3059. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  3060. // matrix x vector
  3061. typeB = builder.getVectorFromMatrix( typeA );
  3062. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  3063. // vector x matrix
  3064. typeA = builder.getVectorFromMatrix( typeB );
  3065. } else {
  3066. // anytype x anytype
  3067. typeA = typeB = type;
  3068. }
  3069. } else {
  3070. typeA = typeB = type;
  3071. }
  3072. const a = aNode.build( builder, typeA );
  3073. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  3074. const outputLength = builder.getTypeLength( output );
  3075. const fnOpSnippet = builder.getFunctionOperator( op );
  3076. if ( output !== 'void' ) {
  3077. if ( op === '<' && outputLength > 1 ) {
  3078. if ( builder.useComparisonMethod ) {
  3079. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  3080. } else {
  3081. return builder.format( `( ${ a } < ${ b } )`, type, output );
  3082. }
  3083. } else if ( op === '<=' && outputLength > 1 ) {
  3084. if ( builder.useComparisonMethod ) {
  3085. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  3086. } else {
  3087. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  3088. }
  3089. } else if ( op === '>' && outputLength > 1 ) {
  3090. if ( builder.useComparisonMethod ) {
  3091. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  3092. } else {
  3093. return builder.format( `( ${ a } > ${ b } )`, type, output );
  3094. }
  3095. } else if ( op === '>=' && outputLength > 1 ) {
  3096. if ( builder.useComparisonMethod ) {
  3097. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  3098. } else {
  3099. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  3100. }
  3101. } else if ( op === '!' || op === '~' ) {
  3102. return builder.format( `(${op}${a})`, typeA, output );
  3103. } else if ( fnOpSnippet ) {
  3104. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3105. } else {
  3106. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3107. }
  3108. } else if ( typeA !== 'void' ) {
  3109. if ( fnOpSnippet ) {
  3110. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3111. } else {
  3112. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3113. }
  3114. }
  3115. }
  3116. serialize( data ) {
  3117. super.serialize( data );
  3118. data.op = this.op;
  3119. }
  3120. deserialize( data ) {
  3121. super.deserialize( data );
  3122. this.op = data.op;
  3123. }
  3124. }
  3125. /**
  3126. * Returns the addition of two or more value.
  3127. *
  3128. * @function
  3129. * @param {Node} aNode - The first input.
  3130. * @param {Node} bNode - The second input.
  3131. * @param {...Node} params - Additional input parameters.
  3132. * @returns {OperatorNode}
  3133. */
  3134. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  3135. /**
  3136. * Returns the subtraction of two or more value.
  3137. *
  3138. * @function
  3139. * @param {Node} aNode - The first input.
  3140. * @param {Node} bNode - The second input.
  3141. * @param {...Node} params - Additional input parameters.
  3142. * @returns {OperatorNode}
  3143. */
  3144. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  3145. /**
  3146. * Returns the multiplication of two or more value.
  3147. *
  3148. * @function
  3149. * @param {Node} aNode - The first input.
  3150. * @param {Node} bNode - The second input.
  3151. * @param {...Node} params - Additional input parameters.
  3152. * @returns {OperatorNode}
  3153. */
  3154. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  3155. /**
  3156. * Returns the division of two or more value.
  3157. *
  3158. * @function
  3159. * @param {Node} aNode - The first input.
  3160. * @param {Node} bNode - The second input.
  3161. * @param {...Node} params - Additional input parameters.
  3162. * @returns {OperatorNode}
  3163. */
  3164. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  3165. /**
  3166. * Computes the remainder of dividing the first node by the second, for integer values.
  3167. *
  3168. * @function
  3169. * @param {Node} aNode - The first input.
  3170. * @param {Node} bNode - The second input.
  3171. * @returns {OperatorNode}
  3172. */
  3173. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  3174. /**
  3175. * Checks if two nodes are equal.
  3176. *
  3177. * @function
  3178. * @param {Node} aNode - The first input.
  3179. * @param {Node} bNode - The second input.
  3180. * @returns {OperatorNode}
  3181. */
  3182. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  3183. /**
  3184. * Checks if two nodes are not equal.
  3185. *
  3186. * @function
  3187. * @param {Node} aNode - The first input.
  3188. * @param {Node} bNode - The second input.
  3189. * @returns {OperatorNode}
  3190. */
  3191. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  3192. /**
  3193. * Checks if the first node is less than the second.
  3194. *
  3195. * @function
  3196. * @param {Node} aNode - The first input.
  3197. * @param {Node} bNode - The second input.
  3198. * @returns {OperatorNode}
  3199. */
  3200. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  3201. /**
  3202. * Checks if the first node is greater than the second.
  3203. *
  3204. * @function
  3205. * @param {Node} aNode - The first input.
  3206. * @param {Node} bNode - The second input.
  3207. * @returns {OperatorNode}
  3208. */
  3209. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  3210. /**
  3211. * Checks if the first node is less than or equal to the second.
  3212. *
  3213. * @function
  3214. * @param {Node} aNode - The first input.
  3215. * @param {Node} bNode - The second input.
  3216. * @returns {OperatorNode}
  3217. */
  3218. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  3219. /**
  3220. * Checks if the first node is greater than or equal to the second.
  3221. *
  3222. * @function
  3223. * @param {Node} aNode - The first input.
  3224. * @param {Node} bNode - The second input.
  3225. * @returns {OperatorNode}
  3226. */
  3227. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  3228. /**
  3229. * Performs logical AND on two nodes.
  3230. *
  3231. * @function
  3232. * @param {Node} aNode - The first input.
  3233. * @param {Node} bNode - The second input.
  3234. * @returns {OperatorNode}
  3235. */
  3236. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  3237. /**
  3238. * Performs logical OR on two nodes.
  3239. *
  3240. * @function
  3241. * @param {Node} aNode - The first input.
  3242. * @param {Node} bNode - The second input.
  3243. * @returns {OperatorNode}
  3244. */
  3245. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  3246. /**
  3247. * Performs logical NOT on a node.
  3248. *
  3249. * @function
  3250. * @param {Node} aNode - The first input.
  3251. * @param {Node} bNode - The second input.
  3252. * @returns {OperatorNode}
  3253. */
  3254. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  3255. /**
  3256. * Performs logical XOR on two nodes.
  3257. *
  3258. * @function
  3259. * @param {Node} aNode - The first input.
  3260. * @param {Node} bNode - The second input.
  3261. * @returns {OperatorNode}
  3262. */
  3263. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  3264. /**
  3265. * Performs bitwise AND on two nodes.
  3266. *
  3267. * @function
  3268. * @param {Node} aNode - The first input.
  3269. * @param {Node} bNode - The second input.
  3270. * @returns {OperatorNode}
  3271. */
  3272. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  3273. /**
  3274. * Performs bitwise NOT on a node.
  3275. *
  3276. * @function
  3277. * @param {Node} aNode - The first input.
  3278. * @param {Node} bNode - The second input.
  3279. * @returns {OperatorNode}
  3280. */
  3281. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  3282. /**
  3283. * Performs bitwise OR on two nodes.
  3284. *
  3285. * @function
  3286. * @param {Node} aNode - The first input.
  3287. * @param {Node} bNode - The second input.
  3288. * @returns {OperatorNode}
  3289. */
  3290. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  3291. /**
  3292. * Performs bitwise XOR on two nodes.
  3293. *
  3294. * @function
  3295. * @param {Node} aNode - The first input.
  3296. * @param {Node} bNode - The second input.
  3297. * @returns {OperatorNode}
  3298. */
  3299. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  3300. /**
  3301. * Shifts a node to the left.
  3302. *
  3303. * @function
  3304. * @param {Node} aNode - The node to shift.
  3305. * @param {Node} bNode - The value to shift.
  3306. * @returns {OperatorNode}
  3307. */
  3308. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  3309. /**
  3310. * Shifts a node to the right.
  3311. *
  3312. * @function
  3313. * @param {Node} aNode - The node to shift.
  3314. * @param {Node} bNode - The value to shift.
  3315. * @returns {OperatorNode}
  3316. */
  3317. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  3318. addMethodChaining( 'add', add );
  3319. addMethodChaining( 'sub', sub );
  3320. addMethodChaining( 'mul', mul );
  3321. addMethodChaining( 'div', div );
  3322. addMethodChaining( 'modInt', modInt );
  3323. addMethodChaining( 'equal', equal );
  3324. addMethodChaining( 'notEqual', notEqual );
  3325. addMethodChaining( 'lessThan', lessThan );
  3326. addMethodChaining( 'greaterThan', greaterThan );
  3327. addMethodChaining( 'lessThanEqual', lessThanEqual );
  3328. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  3329. addMethodChaining( 'and', and );
  3330. addMethodChaining( 'or', or );
  3331. addMethodChaining( 'not', not );
  3332. addMethodChaining( 'xor', xor );
  3333. addMethodChaining( 'bitAnd', bitAnd );
  3334. addMethodChaining( 'bitNot', bitNot );
  3335. addMethodChaining( 'bitOr', bitOr );
  3336. addMethodChaining( 'bitXor', bitXor );
  3337. addMethodChaining( 'shiftLeft', shiftLeft );
  3338. addMethodChaining( 'shiftRight', shiftRight );
  3339. const remainder = ( ...params ) => { // @deprecated, r168
  3340. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  3341. return modInt( ...params );
  3342. };
  3343. addMethodChaining( 'remainder', remainder );
  3344. /** @module MathNode **/
  3345. /**
  3346. * This node represents a variety of mathematical methods available in shaders.
  3347. * They are divided into three categories:
  3348. *
  3349. * - Methods with one input like `sin`, `cos` or `normalize`.
  3350. * - Methods with two inputs like `dot`, `cross` or `pow`.
  3351. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  3352. *
  3353. * @augments TempNode
  3354. */
  3355. class MathNode extends TempNode {
  3356. static get type() {
  3357. return 'MathNode';
  3358. }
  3359. /**
  3360. * Constructs a new math node.
  3361. *
  3362. * @param {String} method - The method name.
  3363. * @param {Node} aNode - The first input.
  3364. * @param {Node?} [bNode=null] - The second input.
  3365. * @param {Node?} [cNode=null] - The third input.
  3366. */
  3367. constructor( method, aNode, bNode = null, cNode = null ) {
  3368. super();
  3369. /**
  3370. * The method name.
  3371. *
  3372. * @type {String}
  3373. */
  3374. this.method = method;
  3375. /**
  3376. * The first input.
  3377. *
  3378. * @type {Node}
  3379. */
  3380. this.aNode = aNode;
  3381. /**
  3382. * The second input.
  3383. *
  3384. * @type {Node?}
  3385. * @default null
  3386. */
  3387. this.bNode = bNode;
  3388. /**
  3389. * The third input.
  3390. *
  3391. * @type {Node?}
  3392. * @default null
  3393. */
  3394. this.cNode = cNode;
  3395. }
  3396. /**
  3397. * The input type is inferred from the node types of the input nodes.
  3398. *
  3399. * @param {NodeBuilder} builder - The current node builder.
  3400. * @return {String} The input type.
  3401. */
  3402. getInputType( builder ) {
  3403. const aType = this.aNode.getNodeType( builder );
  3404. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  3405. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  3406. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  3407. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  3408. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  3409. if ( aLen > bLen && aLen > cLen ) {
  3410. return aType;
  3411. } else if ( bLen > cLen ) {
  3412. return bType;
  3413. } else if ( cLen > aLen ) {
  3414. return cType;
  3415. }
  3416. return aType;
  3417. }
  3418. /**
  3419. * The selected method as well as the input type determine the node type of this node.
  3420. *
  3421. * @param {NodeBuilder} builder - The current node builder.
  3422. * @return {String} The node type.
  3423. */
  3424. getNodeType( builder ) {
  3425. const method = this.method;
  3426. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  3427. return 'float';
  3428. } else if ( method === MathNode.CROSS ) {
  3429. return 'vec3';
  3430. } else if ( method === MathNode.ALL ) {
  3431. return 'bool';
  3432. } else if ( method === MathNode.EQUALS ) {
  3433. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  3434. } else if ( method === MathNode.MOD ) {
  3435. return this.aNode.getNodeType( builder );
  3436. } else {
  3437. return this.getInputType( builder );
  3438. }
  3439. }
  3440. generate( builder, output ) {
  3441. let method = this.method;
  3442. const type = this.getNodeType( builder );
  3443. const inputType = this.getInputType( builder );
  3444. const a = this.aNode;
  3445. const b = this.bNode;
  3446. const c = this.cNode;
  3447. const coordinateSystem = builder.renderer.coordinateSystem;
  3448. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  3449. // dir can be either a direction vector or a normal vector
  3450. // upper-left 3x3 of matrix is assumed to be orthogonal
  3451. let tA = a;
  3452. let tB = b;
  3453. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  3454. tB = vec4( vec3( tB ), 0.0 );
  3455. } else {
  3456. tA = vec4( vec3( tA ), 0.0 );
  3457. }
  3458. const mulNode = mul( tA, tB ).xyz;
  3459. return normalize( mulNode ).build( builder, output );
  3460. } else if ( method === MathNode.NEGATE ) {
  3461. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  3462. } else if ( method === MathNode.ONE_MINUS ) {
  3463. return sub( 1.0, a ).build( builder, output );
  3464. } else if ( method === MathNode.RECIPROCAL ) {
  3465. return div( 1.0, a ).build( builder, output );
  3466. } else if ( method === MathNode.DIFFERENCE ) {
  3467. return abs( sub( a, b ) ).build( builder, output );
  3468. } else {
  3469. const params = [];
  3470. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  3471. params.push(
  3472. a.build( builder, type ),
  3473. b.build( builder, type )
  3474. );
  3475. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  3476. params.push(
  3477. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  3478. b.build( builder, inputType )
  3479. );
  3480. } else if ( ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  3481. params.push(
  3482. a.build( builder, inputType ),
  3483. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  3484. );
  3485. } else if ( method === MathNode.REFRACT ) {
  3486. params.push(
  3487. a.build( builder, inputType ),
  3488. b.build( builder, inputType ),
  3489. c.build( builder, 'float' )
  3490. );
  3491. } else if ( method === MathNode.MIX ) {
  3492. params.push(
  3493. a.build( builder, inputType ),
  3494. b.build( builder, inputType ),
  3495. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  3496. );
  3497. } else {
  3498. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  3499. method = 'atan2';
  3500. }
  3501. params.push( a.build( builder, inputType ) );
  3502. if ( b !== null ) params.push( b.build( builder, inputType ) );
  3503. if ( c !== null ) params.push( c.build( builder, inputType ) );
  3504. }
  3505. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  3506. }
  3507. }
  3508. serialize( data ) {
  3509. super.serialize( data );
  3510. data.method = this.method;
  3511. }
  3512. deserialize( data ) {
  3513. super.deserialize( data );
  3514. this.method = data.method;
  3515. }
  3516. }
  3517. // 1 input
  3518. MathNode.ALL = 'all';
  3519. MathNode.ANY = 'any';
  3520. MathNode.RADIANS = 'radians';
  3521. MathNode.DEGREES = 'degrees';
  3522. MathNode.EXP = 'exp';
  3523. MathNode.EXP2 = 'exp2';
  3524. MathNode.LOG = 'log';
  3525. MathNode.LOG2 = 'log2';
  3526. MathNode.SQRT = 'sqrt';
  3527. MathNode.INVERSE_SQRT = 'inversesqrt';
  3528. MathNode.FLOOR = 'floor';
  3529. MathNode.CEIL = 'ceil';
  3530. MathNode.NORMALIZE = 'normalize';
  3531. MathNode.FRACT = 'fract';
  3532. MathNode.SIN = 'sin';
  3533. MathNode.COS = 'cos';
  3534. MathNode.TAN = 'tan';
  3535. MathNode.ASIN = 'asin';
  3536. MathNode.ACOS = 'acos';
  3537. MathNode.ATAN = 'atan';
  3538. MathNode.ABS = 'abs';
  3539. MathNode.SIGN = 'sign';
  3540. MathNode.LENGTH = 'length';
  3541. MathNode.NEGATE = 'negate';
  3542. MathNode.ONE_MINUS = 'oneMinus';
  3543. MathNode.DFDX = 'dFdx';
  3544. MathNode.DFDY = 'dFdy';
  3545. MathNode.ROUND = 'round';
  3546. MathNode.RECIPROCAL = 'reciprocal';
  3547. MathNode.TRUNC = 'trunc';
  3548. MathNode.FWIDTH = 'fwidth';
  3549. MathNode.TRANSPOSE = 'transpose';
  3550. // 2 inputs
  3551. MathNode.BITCAST = 'bitcast';
  3552. MathNode.EQUALS = 'equals';
  3553. MathNode.MIN = 'min';
  3554. MathNode.MAX = 'max';
  3555. MathNode.MOD = 'mod';
  3556. MathNode.STEP = 'step';
  3557. MathNode.REFLECT = 'reflect';
  3558. MathNode.DISTANCE = 'distance';
  3559. MathNode.DIFFERENCE = 'difference';
  3560. MathNode.DOT = 'dot';
  3561. MathNode.CROSS = 'cross';
  3562. MathNode.POW = 'pow';
  3563. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  3564. // 3 inputs
  3565. MathNode.MIX = 'mix';
  3566. MathNode.CLAMP = 'clamp';
  3567. MathNode.REFRACT = 'refract';
  3568. MathNode.SMOOTHSTEP = 'smoothstep';
  3569. MathNode.FACEFORWARD = 'faceforward';
  3570. // 1 inputs
  3571. /**
  3572. * A small value used to handle floating-point precision errors.
  3573. *
  3574. * @type {Node<float>}
  3575. */
  3576. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  3577. /**
  3578. * Represents infinity.
  3579. *
  3580. * @type {Node<float>}
  3581. */
  3582. const INFINITY = /*@__PURE__*/ float( 1e6 );
  3583. /**
  3584. * Represents PI.
  3585. *
  3586. * @type {Node<float>}
  3587. */
  3588. const PI = /*@__PURE__*/ float( Math.PI );
  3589. /**
  3590. * Represents PI * 2.
  3591. *
  3592. * @type {Node<float>}
  3593. */
  3594. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  3595. /**
  3596. * Returns `true` if all components of `x` are `true`.
  3597. *
  3598. * @function
  3599. * @param {Node | Number} x - The parameter.
  3600. * @returns {Node<bool>}
  3601. */
  3602. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  3603. /**
  3604. * Returns `true` if any components of `x` are `true`.
  3605. *
  3606. * @function
  3607. * @param {Node | Number} x - The parameter.
  3608. * @returns {Node<bool>}
  3609. */
  3610. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  3611. /**
  3612. * Converts a quantity in degrees to radians.
  3613. *
  3614. * @function
  3615. * @param {Node | Number} x - The input in degrees.
  3616. * @returns {Node}
  3617. */
  3618. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  3619. /**
  3620. * Convert a quantity in radians to degrees.
  3621. *
  3622. * @function
  3623. * @param {Node | Number} x - The input in radians.
  3624. * @returns {Node}
  3625. */
  3626. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  3627. /**
  3628. * Returns the natural exponentiation of the parameter.
  3629. *
  3630. * @function
  3631. * @param {Node | Number} x - The parameter.
  3632. * @returns {Node}
  3633. */
  3634. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  3635. /**
  3636. * Returns 2 raised to the power of the parameter.
  3637. *
  3638. * @function
  3639. * @param {Node | Number} x - The parameter.
  3640. * @returns {Node}
  3641. */
  3642. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  3643. /**
  3644. * Returns the natural logarithm of the parameter.
  3645. *
  3646. * @function
  3647. * @param {Node | Number} x - The parameter.
  3648. * @returns {Node}
  3649. */
  3650. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  3651. /**
  3652. * Returns the base 2 logarithm of the parameter.
  3653. *
  3654. * @function
  3655. * @param {Node | Number} x - The parameter.
  3656. * @returns {Node}
  3657. */
  3658. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  3659. /**
  3660. * Returns the square root of the parameter.
  3661. *
  3662. * @function
  3663. * @param {Node | Number} x - The parameter.
  3664. * @returns {Node}
  3665. */
  3666. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  3667. /**
  3668. * Returns the inverse of the square root of the parameter.
  3669. *
  3670. * @function
  3671. * @param {Node | Number} x - The parameter.
  3672. * @returns {Node}
  3673. */
  3674. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  3675. /**
  3676. * Finds the nearest integer less than or equal to the parameter.
  3677. *
  3678. * @function
  3679. * @param {Node | Number} x - The parameter.
  3680. * @returns {Node}
  3681. */
  3682. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  3683. /**
  3684. * Finds the nearest integer that is greater than or equal to the parameter.
  3685. *
  3686. * @function
  3687. * @param {Node | Number} x - The parameter.
  3688. * @returns {Node}
  3689. */
  3690. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  3691. /**
  3692. * Calculates the unit vector in the same direction as the original vector.
  3693. *
  3694. * @function
  3695. * @param {Node} x - The input vector.
  3696. * @returns {Node}
  3697. */
  3698. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  3699. /**
  3700. * Computes the fractional part of the parameter.
  3701. *
  3702. * @function
  3703. * @param {Node | Number} x - The parameter.
  3704. * @returns {Node}
  3705. */
  3706. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  3707. /**
  3708. * Returns the sine of the parameter.
  3709. *
  3710. * @function
  3711. * @param {Node | Number} x - The parameter.
  3712. * @returns {Node}
  3713. */
  3714. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  3715. /**
  3716. * Returns the cosine of the parameter.
  3717. *
  3718. * @function
  3719. * @param {Node | Number} x - The parameter.
  3720. * @returns {Node}
  3721. */
  3722. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  3723. /**
  3724. * Returns the tangent of the parameter.
  3725. *
  3726. * @function
  3727. * @param {Node | Number} x - The parameter.
  3728. * @returns {Node}
  3729. */
  3730. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  3731. /**
  3732. * Returns the arcsine of the parameter.
  3733. *
  3734. * @function
  3735. * @param {Node | Number} x - The parameter.
  3736. * @returns {Node}
  3737. */
  3738. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  3739. /**
  3740. * Returns the arccosine of the parameter.
  3741. *
  3742. * @function
  3743. * @param {Node | Number} x - The parameter.
  3744. * @returns {Node}
  3745. */
  3746. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  3747. /**
  3748. * Returns the arc-tangent of the parameter.
  3749. *
  3750. * @function
  3751. * @param {Node | Number} x - The parameter.
  3752. * @returns {Node}
  3753. */
  3754. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  3755. /**
  3756. * Returns the absolute value of the parameter.
  3757. *
  3758. * @function
  3759. * @param {Node | Number} x - The parameter.
  3760. * @returns {Node}
  3761. */
  3762. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  3763. /**
  3764. * Extracts the sign of the parameter.
  3765. *
  3766. * @function
  3767. * @param {Node | Number} x - The parameter.
  3768. * @returns {Node}
  3769. */
  3770. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  3771. /**
  3772. * Calculates the length of a vector.
  3773. *
  3774. * @function
  3775. * @param {Node} x - The parameter.
  3776. * @returns {Node<float>}
  3777. */
  3778. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  3779. /**
  3780. * Negates the value of the parameter (-x).
  3781. *
  3782. * @function
  3783. * @param {Node | Number} x - The parameter.
  3784. * @returns {Node}
  3785. */
  3786. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  3787. /**
  3788. * Return `1` minus the parameter.
  3789. *
  3790. * @function
  3791. * @param {Node | Number} x - The parameter.
  3792. * @returns {Node}
  3793. */
  3794. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  3795. /**
  3796. * Returns the partial derivative of the parameter with respect to x.
  3797. *
  3798. * @function
  3799. * @param {Node | Number} x - The parameter.
  3800. * @returns {Node}
  3801. */
  3802. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  3803. /**
  3804. * Returns the partial derivative of the parameter with respect to y.
  3805. *
  3806. * @function
  3807. * @param {Node | Number} x - The parameter.
  3808. * @returns {Node}
  3809. */
  3810. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  3811. /**
  3812. * Rounds the parameter to the nearest integer.
  3813. *
  3814. * @function
  3815. * @param {Node | Number} x - The parameter.
  3816. * @returns {Node}
  3817. */
  3818. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  3819. /**
  3820. * Returns the reciprocal of the parameter `(1/x)`.
  3821. *
  3822. * @function
  3823. * @param {Node | Number} x - The parameter.
  3824. * @returns {Node}
  3825. */
  3826. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  3827. /**
  3828. * Truncates the parameter, removing the fractional part.
  3829. *
  3830. * @function
  3831. * @param {Node | Number} x - The parameter.
  3832. * @returns {Node}
  3833. */
  3834. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  3835. /**
  3836. * Returns the sum of the absolute derivatives in x and y.
  3837. *
  3838. * @function
  3839. * @param {Node | Number} x - The parameter.
  3840. * @returns {Node}
  3841. */
  3842. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  3843. /**
  3844. * Returns the transpose of a matrix.
  3845. *
  3846. * @function
  3847. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  3848. * @returns {Node}
  3849. */
  3850. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  3851. // 2 inputs
  3852. /**
  3853. * Reinterpret the bit representation of a value in one type as a value in another type.
  3854. *
  3855. * @function
  3856. * @param {Node | Number} x - The parameter.
  3857. * @param {String} y - The new type.
  3858. * @returns {Node}
  3859. */
  3860. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  3861. /**
  3862. * Returns `true` if `x` equals `y`.
  3863. *
  3864. * @function
  3865. * @param {Node | Number} x - The first parameter.
  3866. * @param {Node | Number} y - The second parameter.
  3867. * @returns {Node<bool>}
  3868. */
  3869. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  3870. /**
  3871. * Returns the lesser of two values.
  3872. *
  3873. * @function
  3874. * @param {Node | Number} x - The y parameter.
  3875. * @param {Node | Number} y - The x parameter.
  3876. * @returns {Node}
  3877. */
  3878. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  3879. /**
  3880. * Returns the greater of two values.
  3881. *
  3882. * @function
  3883. * @param {Node | Number} x - The y parameter.
  3884. * @param {Node | Number} y - The x parameter.
  3885. * @returns {Node}
  3886. */
  3887. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  3888. /**
  3889. * Computes the remainder of dividing the first node by the second one.
  3890. *
  3891. * @function
  3892. * @param {Node | Number} x - The y parameter.
  3893. * @param {Node | Number} y - The x parameter.
  3894. * @returns {Node}
  3895. */
  3896. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  3897. /**
  3898. * Generate a step function by comparing two values.
  3899. *
  3900. * @function
  3901. * @param {Node | Number} x - The y parameter.
  3902. * @param {Node | Number} y - The x parameter.
  3903. * @returns {Node}
  3904. */
  3905. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  3906. /**
  3907. * Calculates the reflection direction for an incident vector.
  3908. *
  3909. * @function
  3910. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  3911. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  3912. * @returns {Node<vec2|vec3|vec4>}
  3913. */
  3914. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  3915. /**
  3916. * Calculates the distance between two points.
  3917. *
  3918. * @function
  3919. * @param {Node<vec2|vec3|vec4>} x - The first point.
  3920. * @param {Node<vec2|vec3|vec4>} y - The second point.
  3921. * @returns {Node<float>}
  3922. */
  3923. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  3924. /**
  3925. * Calculates the absolute difference between two values.
  3926. *
  3927. * @function
  3928. * @param {Node | Number} x - The first parameter.
  3929. * @param {Node | Number} y - The second parameter.
  3930. * @returns {Node}
  3931. */
  3932. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  3933. /**
  3934. * Calculates the dot product of two vectors.
  3935. *
  3936. * @function
  3937. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  3938. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  3939. * @returns {Node<float>}
  3940. */
  3941. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  3942. /**
  3943. * Calculates the cross product of two vectors.
  3944. *
  3945. * @function
  3946. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  3947. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  3948. * @returns {Node<vec2|vec3|vec4>}
  3949. */
  3950. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  3951. /**
  3952. * Return the value of the first parameter raised to the power of the second one.
  3953. *
  3954. * @function
  3955. * @param {Node | Number} x - The first parameter.
  3956. * @param {Node | Number} y - The second parameter.
  3957. * @returns {Node}
  3958. */
  3959. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  3960. /**
  3961. * Returns the square of the parameter.
  3962. *
  3963. * @function
  3964. * @param {Node | Number} x - The first parameter.
  3965. * @returns {Node}
  3966. */
  3967. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  3968. /**
  3969. * Returns the cube of the parameter.
  3970. *
  3971. * @function
  3972. * @param {Node | Number} x - The first parameter.
  3973. * @returns {Node}
  3974. */
  3975. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  3976. /**
  3977. * Returns the fourth power of the parameter.
  3978. *
  3979. * @function
  3980. * @param {Node | Number} x - The first parameter.
  3981. * @returns {Node}
  3982. */
  3983. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  3984. /**
  3985. * Transforms the direction of a vector by a matrix and then normalizes the result.
  3986. *
  3987. * @function
  3988. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  3989. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  3990. * @returns {Node}
  3991. */
  3992. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  3993. /**
  3994. * Returns the cube root of a number.
  3995. *
  3996. * @function
  3997. * @param {Node | Number} a - The first parameter.
  3998. * @returns {Node}
  3999. */
  4000. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  4001. /**
  4002. * Calculate the squared length of a vector.
  4003. *
  4004. * @function
  4005. * @param {Node<vec2|vec3|vec4>} a - The vector.
  4006. * @returns {Node<float>}
  4007. */
  4008. const lengthSq = ( a ) => dot( a, a );
  4009. /**
  4010. * Linearly interpolates between two values.
  4011. *
  4012. * @function
  4013. * @param {Node | Number} a - The first parameter.
  4014. * @param {Node | Number} b - The second parameter.
  4015. * @param {Node | Number} t - The interpolation value.
  4016. * @returns {Node}
  4017. */
  4018. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  4019. /**
  4020. * Constrains a value to lie between two further values.
  4021. *
  4022. * @function
  4023. * @param {Node | Number} value - The value to constrain.
  4024. * @param {Node | Number} [low=0] - The lower bound.
  4025. * @param {Node | Number} [high=1] - The upper bound.
  4026. * @returns {Node}
  4027. */
  4028. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  4029. /**
  4030. * Constrains a value between `0` and `1`.
  4031. *
  4032. * @function
  4033. * @param {Node | Number} value - The value to constrain.
  4034. * @returns {Node}
  4035. */
  4036. const saturate = ( value ) => clamp( value );
  4037. /**
  4038. * Calculates the refraction direction for an incident vector.
  4039. *
  4040. * @function
  4041. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4042. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4043. * @param {Node<float>} eta - The the ratio of indices of refraction.
  4044. * @returns {Node<vec2|vec3|vec4>}
  4045. */
  4046. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  4047. /**
  4048. * Performs a Hermite interpolation between two values.
  4049. *
  4050. * @function
  4051. * @param {Node | Number} low - The value of the lower edge of the Hermite function.
  4052. * @param {Node | Number} high - The value of the upper edge of the Hermite function.
  4053. * @param {Node | Number} x - The source value for interpolation.
  4054. * @returns {Node}
  4055. */
  4056. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  4057. /**
  4058. * Returns a vector pointing in the same direction as another.
  4059. *
  4060. * @function
  4061. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  4062. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4063. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  4064. * @returns {Node<vec2|vec3|vec4>}
  4065. */
  4066. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  4067. /**
  4068. * Returns a random value for the given uv.
  4069. *
  4070. * @function
  4071. * @param {Node<vec2>} uv - The uv node.
  4072. * @returns {Node<float>}
  4073. */
  4074. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  4075. const a = 12.9898, b = 78.233, c = 43758.5453;
  4076. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  4077. return fract( sin( sn ).mul( c ) );
  4078. } );
  4079. /**
  4080. * Alias for `mix()` with a different parameter order.
  4081. *
  4082. * @function
  4083. * @param {Node | Number} t - The interpolation value.
  4084. * @param {Node | Number} e1 - The first parameter.
  4085. * @param {Node | Number} e2 - The second parameter.
  4086. * @returns {Node}
  4087. */
  4088. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  4089. /**
  4090. * Alias for `smoothstep()` with a different parameter order.
  4091. *
  4092. * @function
  4093. * @param {Node | Number} x - The source value for interpolation.
  4094. * @param {Node | Number} low - The value of the lower edge of the Hermite function.
  4095. * @param {Node | Number} high - The value of the upper edge of the Hermite function.
  4096. * @returns {Node}
  4097. */
  4098. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  4099. /**
  4100. * Returns the arc-tangent of the quotient of its parameters.
  4101. *
  4102. * @function
  4103. * @param {Node | Number} y - The y parameter.
  4104. * @param {Node | Number} x - The x parameter.
  4105. * @returns {Node}
  4106. */
  4107. const atan2 = ( y, x ) => { // @deprecated, r172
  4108. console.warn( 'THREE.TSL: "atan2" is overloaded. Use "atan" instead.' );
  4109. return atan( y, x );
  4110. };
  4111. // GLSL alias function
  4112. const faceforward = faceForward;
  4113. const inversesqrt = inverseSqrt;
  4114. // Method chaining
  4115. addMethodChaining( 'all', all );
  4116. addMethodChaining( 'any', any );
  4117. addMethodChaining( 'equals', equals );
  4118. addMethodChaining( 'radians', radians );
  4119. addMethodChaining( 'degrees', degrees );
  4120. addMethodChaining( 'exp', exp );
  4121. addMethodChaining( 'exp2', exp2 );
  4122. addMethodChaining( 'log', log );
  4123. addMethodChaining( 'log2', log2 );
  4124. addMethodChaining( 'sqrt', sqrt );
  4125. addMethodChaining( 'inverseSqrt', inverseSqrt );
  4126. addMethodChaining( 'floor', floor );
  4127. addMethodChaining( 'ceil', ceil );
  4128. addMethodChaining( 'normalize', normalize );
  4129. addMethodChaining( 'fract', fract );
  4130. addMethodChaining( 'sin', sin );
  4131. addMethodChaining( 'cos', cos );
  4132. addMethodChaining( 'tan', tan );
  4133. addMethodChaining( 'asin', asin );
  4134. addMethodChaining( 'acos', acos );
  4135. addMethodChaining( 'atan', atan );
  4136. addMethodChaining( 'abs', abs );
  4137. addMethodChaining( 'sign', sign );
  4138. addMethodChaining( 'length', length );
  4139. addMethodChaining( 'lengthSq', lengthSq );
  4140. addMethodChaining( 'negate', negate );
  4141. addMethodChaining( 'oneMinus', oneMinus );
  4142. addMethodChaining( 'dFdx', dFdx );
  4143. addMethodChaining( 'dFdy', dFdy );
  4144. addMethodChaining( 'round', round );
  4145. addMethodChaining( 'reciprocal', reciprocal );
  4146. addMethodChaining( 'trunc', trunc );
  4147. addMethodChaining( 'fwidth', fwidth );
  4148. addMethodChaining( 'atan2', atan2 );
  4149. addMethodChaining( 'min', min$1 );
  4150. addMethodChaining( 'max', max$1 );
  4151. addMethodChaining( 'mod', mod );
  4152. addMethodChaining( 'step', step );
  4153. addMethodChaining( 'reflect', reflect );
  4154. addMethodChaining( 'distance', distance );
  4155. addMethodChaining( 'dot', dot );
  4156. addMethodChaining( 'cross', cross );
  4157. addMethodChaining( 'pow', pow );
  4158. addMethodChaining( 'pow2', pow2 );
  4159. addMethodChaining( 'pow3', pow3 );
  4160. addMethodChaining( 'pow4', pow4 );
  4161. addMethodChaining( 'transformDirection', transformDirection );
  4162. addMethodChaining( 'mix', mixElement );
  4163. addMethodChaining( 'clamp', clamp );
  4164. addMethodChaining( 'refract', refract );
  4165. addMethodChaining( 'smoothstep', smoothstepElement );
  4166. addMethodChaining( 'faceForward', faceForward );
  4167. addMethodChaining( 'difference', difference );
  4168. addMethodChaining( 'saturate', saturate );
  4169. addMethodChaining( 'cbrt', cbrt );
  4170. addMethodChaining( 'transpose', transpose );
  4171. addMethodChaining( 'rand', rand );
  4172. /** @module ConditionalNode **/
  4173. /**
  4174. * Represents a logical `if/else` statement. Can be used as an alternative
  4175. * to the `If()`/`Else()` syntax.
  4176. *
  4177. * The corresponding TSL `select()` looks like so:
  4178. * ```js
  4179. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  4180. * ```
  4181. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  4182. * determine the outcome of the entire statement.
  4183. *
  4184. * @augments Node
  4185. */
  4186. class ConditionalNode extends Node {
  4187. static get type() {
  4188. return 'ConditionalNode';
  4189. }
  4190. /**
  4191. * Constructs a new conditional node.
  4192. *
  4193. * @param {Node} condNode - The node that defines the condition.
  4194. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4195. * @param {Node?} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4196. */
  4197. constructor( condNode, ifNode, elseNode = null ) {
  4198. super();
  4199. /**
  4200. * The node that defines the condition.
  4201. *
  4202. * @type {Node}
  4203. */
  4204. this.condNode = condNode;
  4205. /**
  4206. * The node that is evaluate when the condition ends up `true`.
  4207. *
  4208. * @type {Node}
  4209. */
  4210. this.ifNode = ifNode;
  4211. /**
  4212. * The node that is evaluate when the condition ends up `false`.
  4213. *
  4214. * @type {Node?}
  4215. * @default null
  4216. */
  4217. this.elseNode = elseNode;
  4218. }
  4219. /**
  4220. * This method is overwritten since the node type is inferred from the if/else
  4221. * nodes.
  4222. *
  4223. * @param {NodeBuilder} builder - The current node builder.
  4224. * @return {String} The node type.
  4225. */
  4226. getNodeType( builder ) {
  4227. const { ifNode, elseNode } = builder.getNodeProperties( this );
  4228. if ( ifNode === undefined ) {
  4229. // fallback setup
  4230. this.setup( builder );
  4231. return this.getNodeType( builder );
  4232. }
  4233. const ifType = ifNode.getNodeType( builder );
  4234. if ( elseNode !== null ) {
  4235. const elseType = elseNode.getNodeType( builder );
  4236. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  4237. return elseType;
  4238. }
  4239. }
  4240. return ifType;
  4241. }
  4242. setup( builder ) {
  4243. const condNode = this.condNode.cache();
  4244. const ifNode = this.ifNode.cache();
  4245. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  4246. //
  4247. const currentNodeBlock = builder.context.nodeBlock;
  4248. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  4249. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  4250. //
  4251. const properties = builder.getNodeProperties( this );
  4252. properties.condNode = condNode;
  4253. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  4254. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  4255. }
  4256. generate( builder, output ) {
  4257. const type = this.getNodeType( builder );
  4258. const nodeData = builder.getDataFromNode( this );
  4259. if ( nodeData.nodeProperty !== undefined ) {
  4260. return nodeData.nodeProperty;
  4261. }
  4262. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  4263. const needsOutput = output !== 'void';
  4264. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  4265. nodeData.nodeProperty = nodeProperty;
  4266. const nodeSnippet = condNode.build( builder, 'bool' );
  4267. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  4268. let ifSnippet = ifNode.build( builder, type );
  4269. if ( ifSnippet ) {
  4270. if ( needsOutput ) {
  4271. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  4272. } else {
  4273. ifSnippet = 'return ' + ifSnippet + ';';
  4274. }
  4275. }
  4276. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  4277. if ( elseNode !== null ) {
  4278. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  4279. let elseSnippet = elseNode.build( builder, type );
  4280. if ( elseSnippet ) {
  4281. if ( needsOutput ) {
  4282. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  4283. } else {
  4284. elseSnippet = 'return ' + elseSnippet + ';';
  4285. }
  4286. }
  4287. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  4288. } else {
  4289. builder.addFlowCode( '\n\n' );
  4290. }
  4291. return builder.format( nodeProperty, type, output );
  4292. }
  4293. }
  4294. /**
  4295. * TSL function for creating a conditional node.
  4296. *
  4297. * @function
  4298. * @param {Node} condNode - The node that defines the condition.
  4299. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4300. * @param {Node?} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4301. * @returns {ConditionalNode}
  4302. */
  4303. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  4304. addMethodChaining( 'select', select );
  4305. //
  4306. const cond = ( ...params ) => { // @deprecated, r168
  4307. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  4308. return select( ...params );
  4309. };
  4310. addMethodChaining( 'cond', cond );
  4311. /** @module ContextNode **/
  4312. /**
  4313. * This node can be used as a context management component for another node.
  4314. * {@link NodeBuilder} performs its node building process in a specific context and
  4315. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  4316. *
  4317. * ```js
  4318. *node.context( { getUV: () => customCoord } );
  4319. *```
  4320. * @augments Node
  4321. */
  4322. class ContextNode extends Node {
  4323. static get type() {
  4324. return 'ContextNode';
  4325. }
  4326. /**
  4327. * Constructs a new context node.
  4328. *
  4329. * @param {Node} node - The node whose context should be modified.
  4330. * @param {Object} [value={}] - The modified context data.
  4331. */
  4332. constructor( node, value = {} ) {
  4333. super();
  4334. /**
  4335. * This flag can be used for type testing.
  4336. *
  4337. * @type {Boolean}
  4338. * @readonly
  4339. * @default true
  4340. */
  4341. this.isContextNode = true;
  4342. /**
  4343. * The node whose context should be modified.
  4344. *
  4345. * @type {Node}
  4346. */
  4347. this.node = node;
  4348. /**
  4349. * The modified context data.
  4350. *
  4351. * @type {Object}
  4352. * @default {}
  4353. */
  4354. this.value = value;
  4355. }
  4356. /**
  4357. * This method is overwritten to ensure it returns the reference to {@link module:ContextNode~ContextNode#node}.
  4358. *
  4359. * @return {Node} A reference to {@link module:ContextNode~ContextNode#node}.
  4360. */
  4361. getScope() {
  4362. return this.node.getScope();
  4363. }
  4364. /**
  4365. * This method is overwritten to ensure it returns the type of {@link module:ContextNode~ContextNode#node}.
  4366. *
  4367. * @param {NodeBuilder} builder - The current node builder.
  4368. * @return {String} The node type.
  4369. */
  4370. getNodeType( builder ) {
  4371. return this.node.getNodeType( builder );
  4372. }
  4373. analyze( builder ) {
  4374. this.node.build( builder );
  4375. }
  4376. setup( builder ) {
  4377. const previousContext = builder.getContext();
  4378. builder.setContext( { ...builder.context, ...this.value } );
  4379. const node = this.node.build( builder );
  4380. builder.setContext( previousContext );
  4381. return node;
  4382. }
  4383. generate( builder, output ) {
  4384. const previousContext = builder.getContext();
  4385. builder.setContext( { ...builder.context, ...this.value } );
  4386. const snippet = this.node.build( builder, output );
  4387. builder.setContext( previousContext );
  4388. return snippet;
  4389. }
  4390. }
  4391. /**
  4392. * TSL function for creating a context node.
  4393. *
  4394. * @function
  4395. * @param {Node} node - The node whose context should be modified.
  4396. * @param {Object} [value={}] - The modified context data.
  4397. * @returns {ContextNode}
  4398. */
  4399. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  4400. /**
  4401. * TSL function for defining a label context value for a given node.
  4402. *
  4403. * @function
  4404. * @param {Node} node - The node whose context should be modified.
  4405. * @param {String} name - The name/label to set.
  4406. * @returns {ContextNode}
  4407. */
  4408. const label = ( node, name ) => context( node, { label: name } );
  4409. addMethodChaining( 'context', context );
  4410. addMethodChaining( 'label', label );
  4411. /** @module VarNode **/
  4412. /**
  4413. * Class for representing shader variables as nodes. Variables are created from
  4414. * existing nodes like the following:
  4415. *
  4416. * ```js
  4417. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  4418. * ```
  4419. *
  4420. * @augments Node
  4421. */
  4422. class VarNode extends Node {
  4423. static get type() {
  4424. return 'VarNode';
  4425. }
  4426. /**
  4427. * Constructs a new variable node.
  4428. *
  4429. * @param {Node} node - The node for which a variable should be created.
  4430. * @param {String?} name - The name of the variable in the shader.
  4431. */
  4432. constructor( node, name = null ) {
  4433. super();
  4434. /**
  4435. * The node for which a variable should be created.
  4436. *
  4437. * @type {Node}
  4438. */
  4439. this.node = node;
  4440. /**
  4441. * The name of the variable in the shader. If no name is defined,
  4442. * the node system auto-generates one.
  4443. *
  4444. * @type {String?}
  4445. * @default null
  4446. */
  4447. this.name = name;
  4448. /**
  4449. * `VarNode` sets this property to `true` by default.
  4450. *
  4451. * @type {Boolean}
  4452. * @default true
  4453. */
  4454. this.global = true;
  4455. /**
  4456. * This flag can be used for type testing.
  4457. *
  4458. * @type {Boolean}
  4459. * @readonly
  4460. * @default true
  4461. */
  4462. this.isVarNode = true;
  4463. }
  4464. getHash( builder ) {
  4465. return this.name || super.getHash( builder );
  4466. }
  4467. getNodeType( builder ) {
  4468. return this.node.getNodeType( builder );
  4469. }
  4470. generate( builder ) {
  4471. const { node, name } = this;
  4472. const nodeVar = builder.getVarFromNode( this, name, builder.getVectorType( this.getNodeType( builder ) ) );
  4473. const propertyName = builder.getPropertyName( nodeVar );
  4474. const snippet = node.build( builder, nodeVar.type );
  4475. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  4476. return propertyName;
  4477. }
  4478. }
  4479. /**
  4480. * TSL function for creating a var node.
  4481. *
  4482. * @function
  4483. * @param {Node} node - The node for which a variable should be created.
  4484. * @param {String?} name - The name of the variable in the shader.
  4485. * @returns {VarNode}
  4486. */
  4487. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  4488. addMethodChaining( 'toVar', ( ...params ) => createVar( ...params ).append() );
  4489. // Deprecated
  4490. const temp = ( node ) => { // @deprecated, r170
  4491. console.warn( 'TSL: "temp" is deprecated. Use ".toVar()" instead.' );
  4492. return createVar( node );
  4493. };
  4494. addMethodChaining( 'temp', temp );
  4495. /** @module VaryingNode **/
  4496. /**
  4497. * Class for representing shader varyings as nodes. Varyings are create from
  4498. * existing nodes like the following:
  4499. *
  4500. * ```js
  4501. * const positionLocal = positionGeometry.varying( 'vPositionLocal' );
  4502. * ```
  4503. *
  4504. * @augments Node
  4505. */
  4506. class VaryingNode extends Node {
  4507. static get type() {
  4508. return 'VaryingNode';
  4509. }
  4510. /**
  4511. * Constructs a new varying node.
  4512. *
  4513. * @param {Node} node - The node for which a varying should be created.
  4514. * @param {String?} name - The name of the varying in the shader.
  4515. */
  4516. constructor( node, name = null ) {
  4517. super();
  4518. /**
  4519. * The node for which a varying should be created.
  4520. *
  4521. * @type {Node}
  4522. */
  4523. this.node = node;
  4524. /**
  4525. * The name of the varying in the shader. If no name is defined,
  4526. * the node system auto-generates one.
  4527. *
  4528. * @type {String?}
  4529. * @default null
  4530. */
  4531. this.name = name;
  4532. /**
  4533. * This flag can be used for type testing.
  4534. *
  4535. * @type {Boolean}
  4536. * @readonly
  4537. * @default true
  4538. */
  4539. this.isVaryingNode = true;
  4540. }
  4541. /**
  4542. * The method is overwritten so it always returns `true`.
  4543. *
  4544. * @param {NodeBuilder} builder - The current node builder.
  4545. * @return {Boolean} Whether this node is global or not.
  4546. */
  4547. isGlobal( /*builder*/ ) {
  4548. return true;
  4549. }
  4550. getHash( builder ) {
  4551. return this.name || super.getHash( builder );
  4552. }
  4553. getNodeType( builder ) {
  4554. // VaryingNode is auto type
  4555. return this.node.getNodeType( builder );
  4556. }
  4557. /**
  4558. * This method performs the setup of a varying node with the current node builder.
  4559. *
  4560. * @param {NodeBuilder} builder - The current node builder.
  4561. * @return {NodeVarying} The node varying from the node builder.
  4562. */
  4563. setupVarying( builder ) {
  4564. const properties = builder.getNodeProperties( this );
  4565. let varying = properties.varying;
  4566. if ( varying === undefined ) {
  4567. const name = this.name;
  4568. const type = this.getNodeType( builder );
  4569. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  4570. properties.node = this.node;
  4571. }
  4572. // this property can be used to check if the varying can be optimized for a variable
  4573. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  4574. return varying;
  4575. }
  4576. setup( builder ) {
  4577. this.setupVarying( builder );
  4578. }
  4579. analyze( builder ) {
  4580. this.setupVarying( builder );
  4581. return this.node.analyze( builder );
  4582. }
  4583. generate( builder ) {
  4584. const properties = builder.getNodeProperties( this );
  4585. const varying = this.setupVarying( builder );
  4586. const needsReassign = builder.shaderStage === 'fragment' && properties.reassignPosition === true && builder.context.needsPositionReassign;
  4587. if ( properties.propertyName === undefined || needsReassign ) {
  4588. const type = this.getNodeType( builder );
  4589. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  4590. // force node run in vertex stage
  4591. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  4592. properties.propertyName = propertyName;
  4593. if ( needsReassign ) {
  4594. // once reassign varying in fragment stage
  4595. properties.reassignPosition = false;
  4596. } else if ( properties.reassignPosition === undefined && builder.context.isPositionNodeInput ) {
  4597. properties.reassignPosition = true;
  4598. }
  4599. }
  4600. return builder.getPropertyName( varying );
  4601. }
  4602. }
  4603. /**
  4604. * TSL function for creating a varying node.
  4605. *
  4606. * @function
  4607. * @param {Node} node - The node for which a varying should be created.
  4608. * @param {String?} name - The name of the varying in the shader.
  4609. * @returns {VaryingNode}
  4610. */
  4611. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  4612. /**
  4613. * Computes a node in the vertex stage.
  4614. *
  4615. * @function
  4616. * @param {Node} node - The node which should be executed in the vertex stage.
  4617. * @returns {VaryingNode}
  4618. */
  4619. const vertexStage = ( node ) => varying( node );
  4620. addMethodChaining( 'varying', varying );
  4621. addMethodChaining( 'vertexStage', vertexStage );
  4622. /** @module ColorSpaceFunctions **/
  4623. /**
  4624. * Converts the given color value from sRGB to linear-sRGB color space.
  4625. *
  4626. * @method
  4627. * @param {Node<vec3>} color - The sRGB color.
  4628. * @return {Node<vec3>} The linear-sRGB color.
  4629. */
  4630. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  4631. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  4632. const b = color.mul( 0.0773993808 );
  4633. const factor = color.lessThanEqual( 0.04045 );
  4634. const rgbResult = mix( a, b, factor );
  4635. return rgbResult;
  4636. } ).setLayout( {
  4637. name: 'sRGBTransferEOTF',
  4638. type: 'vec3',
  4639. inputs: [
  4640. { name: 'color', type: 'vec3' }
  4641. ]
  4642. } );
  4643. /**
  4644. * Converts the given color value from linear-sRGB to sRGB color space.
  4645. *
  4646. * @method
  4647. * @param {Node<vec3>} color - The linear-sRGB color.
  4648. * @return {Node<vec3>} The sRGB color.
  4649. */
  4650. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  4651. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  4652. const b = color.mul( 12.92 );
  4653. const factor = color.lessThanEqual( 0.0031308 );
  4654. const rgbResult = mix( a, b, factor );
  4655. return rgbResult;
  4656. } ).setLayout( {
  4657. name: 'sRGBTransferOETF',
  4658. type: 'vec3',
  4659. inputs: [
  4660. { name: 'color', type: 'vec3' }
  4661. ]
  4662. } );
  4663. /** @module ColorSpaceNode **/
  4664. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  4665. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  4666. /**
  4667. * This node represents a color space conversion. Meaning it converts
  4668. * a color value from a source to a target color space.
  4669. *
  4670. * @augments TempNode
  4671. */
  4672. class ColorSpaceNode extends TempNode {
  4673. static get type() {
  4674. return 'ColorSpaceNode';
  4675. }
  4676. /**
  4677. * Constructs a new color space node.
  4678. *
  4679. * @param {Node} colorNode - Represents the color to convert.
  4680. * @param {String} source - The source color space.
  4681. * @param {String} target - The target color space.
  4682. */
  4683. constructor( colorNode, source, target ) {
  4684. super( 'vec4' );
  4685. /**
  4686. * Represents the color to convert.
  4687. *
  4688. * @type {Node}
  4689. */
  4690. this.colorNode = colorNode;
  4691. /**
  4692. * The source color space.
  4693. *
  4694. * @type {String}
  4695. */
  4696. this.source = source;
  4697. /**
  4698. * The target color space.
  4699. *
  4700. * @type {String}
  4701. */
  4702. this.target = target;
  4703. }
  4704. /**
  4705. * This method resolves the constants `WORKING_COLOR_SPACE` and
  4706. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  4707. * color management and renderer.
  4708. *
  4709. * @param {NodeBuilder} builder - The current node builder.
  4710. * @param {String} colorSpace - The color space to resolve.
  4711. * @return {String} The resolved color space.
  4712. */
  4713. resolveColorSpace( builder, colorSpace ) {
  4714. if ( colorSpace === WORKING_COLOR_SPACE ) {
  4715. return ColorManagement.workingColorSpace;
  4716. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  4717. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  4718. }
  4719. return colorSpace;
  4720. }
  4721. setup( builder ) {
  4722. const { colorNode } = this;
  4723. const source = this.resolveColorSpace( builder, this.source );
  4724. const target = this.resolveColorSpace( builder, this.target );
  4725. let outputNode = colorNode;
  4726. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  4727. return outputNode;
  4728. }
  4729. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  4730. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  4731. }
  4732. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  4733. outputNode = vec4(
  4734. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  4735. outputNode.a
  4736. );
  4737. }
  4738. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  4739. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  4740. }
  4741. return outputNode;
  4742. }
  4743. }
  4744. /**
  4745. * TSL function for converting a given color node to the current output color space.
  4746. *
  4747. * @function
  4748. * @param {Node} node - Represents the node to convert.
  4749. * @returns {ColorSpaceNode}
  4750. */
  4751. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  4752. /**
  4753. * TSL function for converting a given color node to the current working color space.
  4754. *
  4755. * @function
  4756. * @param {Node} node - Represents the node to convert.
  4757. * @returns {ColorSpaceNode}
  4758. */
  4759. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  4760. /**
  4761. * TSL function for converting a given color node from the current working color space to the given color space.
  4762. *
  4763. * @function
  4764. * @param {Node} node - Represents the node to convert.
  4765. * @param {String} colorSpace - The target color space.
  4766. * @returns {ColorSpaceNode}
  4767. */
  4768. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  4769. /**
  4770. * TSL function for converting a given color node from the given color space to the current working color space.
  4771. *
  4772. * @function
  4773. * @param {Node} node - Represents the node to convert.
  4774. * @param {String} colorSpace - The source color space.
  4775. * @returns {ColorSpaceNode}
  4776. */
  4777. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  4778. /**
  4779. * TSL function for converting a given color node from one color space to another one.
  4780. *
  4781. * @function
  4782. * @param {Node} node - Represents the node to convert.
  4783. * @param {String} sourceColorSpace - The source color space.
  4784. * @param {String} targetColorSpace - The target color space.
  4785. * @returns {ColorSpaceNode}
  4786. */
  4787. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  4788. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  4789. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  4790. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  4791. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  4792. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  4793. /** @module ReferenceBaseNode **/
  4794. /**
  4795. * This class is only relevant if the referenced property is array-like.
  4796. * In this case, `ReferenceElementNode` allows to refer to a specific
  4797. * element inside the data structure via an index.
  4798. *
  4799. * @augments ArrayElementNode
  4800. */
  4801. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  4802. static get type() {
  4803. return 'ReferenceElementNode';
  4804. }
  4805. /**
  4806. * Constructs a new reference element node.
  4807. *
  4808. * @param {Node?} referenceNode - The reference node.
  4809. * @param {Node} indexNode - The index node that defines the element access.
  4810. */
  4811. constructor( referenceNode, indexNode ) {
  4812. super( referenceNode, indexNode );
  4813. /**
  4814. * Similar to {@link module:ReferenceBaseNode~ReferenceBaseNode#reference}, an additional
  4815. * property references to the current node.
  4816. *
  4817. * @type {Node?}
  4818. * @default null
  4819. */
  4820. this.referenceNode = referenceNode;
  4821. /**
  4822. * This flag can be used for type testing.
  4823. *
  4824. * @type {Boolean}
  4825. * @readonly
  4826. * @default true
  4827. */
  4828. this.isReferenceElementNode = true;
  4829. }
  4830. /**
  4831. * This method is overwritten since the node type is inferred from
  4832. * the uniform type of the reference node.
  4833. *
  4834. * @param {NodeBuilder} builder - The current node builder.
  4835. * @return {String} The node type.
  4836. */
  4837. getNodeType() {
  4838. return this.referenceNode.uniformType;
  4839. }
  4840. generate( builder ) {
  4841. const snippet = super.generate( builder );
  4842. const arrayType = this.referenceNode.getNodeType();
  4843. const elementType = this.getNodeType();
  4844. return builder.format( snippet, arrayType, elementType );
  4845. }
  4846. };
  4847. /**
  4848. * Base class for nodes which establishes a reference to a property of another object.
  4849. * In this way, the value of the node is automatically linked to the value of
  4850. * referenced object. Reference nodes internally represent the linked value
  4851. * as a uniform.
  4852. *
  4853. * @augments Node
  4854. */
  4855. class ReferenceBaseNode extends Node {
  4856. static get type() {
  4857. return 'ReferenceBaseNode';
  4858. }
  4859. /**
  4860. * Constructs a new reference base node.
  4861. *
  4862. * @param {String} property - The name of the property the node refers to.
  4863. * @param {String} uniformType - The uniform type that should be used to represent the property value.
  4864. * @param {Object?} [object=null] - The object the property belongs to.
  4865. * @param {Number?} [count=null] - When the linked property is an array-like, this parameter defines its length.
  4866. */
  4867. constructor( property, uniformType, object = null, count = null ) {
  4868. super();
  4869. /**
  4870. * The name of the property the node refers to.
  4871. *
  4872. * @type {String}
  4873. */
  4874. this.property = property;
  4875. /**
  4876. * The uniform type that should be used to represent the property value.
  4877. *
  4878. * @type {String}
  4879. */
  4880. this.uniformType = uniformType;
  4881. /**
  4882. * The object the property belongs to.
  4883. *
  4884. * @type {Object?}
  4885. * @default null
  4886. */
  4887. this.object = object;
  4888. /**
  4889. * When the linked property is an array, this parameter defines its length.
  4890. *
  4891. * @type {Number?}
  4892. * @default null
  4893. */
  4894. this.count = count;
  4895. /**
  4896. * The property name might have dots so nested properties can be referred.
  4897. * The hierarchy of the names is stored inside this array.
  4898. *
  4899. * @type {Array<String>}
  4900. */
  4901. this.properties = property.split( '.' );
  4902. /**
  4903. * Points to the current referred object. This property exists next to {@link module:ReferenceNode~ReferenceNode#object}
  4904. * since the final reference might be updated from calling code.
  4905. *
  4906. * @type {Object?}
  4907. * @default null
  4908. */
  4909. this.reference = object;
  4910. /**
  4911. * The uniform node that holds the value of the reference node.
  4912. *
  4913. * @type {UniformNode}
  4914. * @default null
  4915. */
  4916. this.node = null;
  4917. /**
  4918. * The uniform group of the internal uniform.
  4919. *
  4920. * @type {UniformGroupNode}
  4921. * @default null
  4922. */
  4923. this.group = null;
  4924. /**
  4925. * Overwritten since reference nodes are updated per object.
  4926. *
  4927. * @type {String}
  4928. * @default 'object'
  4929. */
  4930. this.updateType = NodeUpdateType.OBJECT;
  4931. }
  4932. /**
  4933. * Sets the uniform group for this reference node.
  4934. *
  4935. * @param {UniformGroupNode} group - The uniform group to set.
  4936. * @return {ReferenceBaseNode} A reference to this node.
  4937. */
  4938. setGroup( group ) {
  4939. this.group = group;
  4940. return this;
  4941. }
  4942. /**
  4943. * When the referred property is array-like, this method can be used
  4944. * to access elements via an index node.
  4945. *
  4946. * @param {IndexNode} indexNode - indexNode.
  4947. * @return {ReferenceElementNode} A reference to an element.
  4948. */
  4949. element( indexNode ) {
  4950. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  4951. }
  4952. /**
  4953. * Sets the node type which automatically defines the internal
  4954. * uniform type.
  4955. *
  4956. * @param {String} uniformType - The type to set.
  4957. */
  4958. setNodeType( uniformType ) {
  4959. const node = uniform( null, uniformType ).getSelf();
  4960. if ( this.group !== null ) {
  4961. node.setGroup( this.group );
  4962. }
  4963. this.node = node;
  4964. }
  4965. /**
  4966. * This method is overwritten since the node type is inferred from
  4967. * the type of the reference node.
  4968. *
  4969. * @param {NodeBuilder} builder - The current node builder.
  4970. * @return {String} The node type.
  4971. */
  4972. getNodeType( builder ) {
  4973. if ( this.node === null ) {
  4974. this.updateReference( builder );
  4975. this.updateValue();
  4976. }
  4977. return this.node.getNodeType( builder );
  4978. }
  4979. /**
  4980. * Returns the property value from the given referred object.
  4981. *
  4982. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  4983. * @return {Any} The value.
  4984. */
  4985. getValueFromReference( object = this.reference ) {
  4986. const { properties } = this;
  4987. let value = object[ properties[ 0 ] ];
  4988. for ( let i = 1; i < properties.length; i ++ ) {
  4989. value = value[ properties[ i ] ];
  4990. }
  4991. return value;
  4992. }
  4993. /**
  4994. * Allows to update the reference based on the given state. The state is only
  4995. * evaluated {@link module:ReferenceBaseNode~ReferenceBaseNode#object} is not set.
  4996. *
  4997. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  4998. * @return {Object} The updated reference.
  4999. */
  5000. updateReference( state ) {
  5001. this.reference = this.object !== null ? this.object : state.object;
  5002. return this.reference;
  5003. }
  5004. /**
  5005. * The output of the reference node is the internal uniform node.
  5006. *
  5007. * @param {NodeBuilder} builder - The current node builder.
  5008. * @return {UniformNode} The output node.
  5009. */
  5010. setup() {
  5011. this.updateValue();
  5012. return this.node;
  5013. }
  5014. /**
  5015. * Overwritten to to update the internal uniform value.
  5016. *
  5017. * @param {NodeFrame} frame - A reference to the current node frame.
  5018. */
  5019. update( /*frame*/ ) {
  5020. this.updateValue();
  5021. }
  5022. /**
  5023. * Retrieves the value from the referred object property and uses it
  5024. * to updated the internal uniform.
  5025. */
  5026. updateValue() {
  5027. if ( this.node === null ) this.setNodeType( this.uniformType );
  5028. const value = this.getValueFromReference();
  5029. if ( Array.isArray( value ) ) {
  5030. this.node.array = value;
  5031. } else {
  5032. this.node.value = value;
  5033. }
  5034. }
  5035. }
  5036. /**
  5037. * TSL function for creating a reference base node.
  5038. *
  5039. * @function
  5040. * @param {String} name - The name of the property the node refers to.
  5041. * @param {String} type - The uniform type that should be used to represent the property value.
  5042. * @param {Object} object - The object the property belongs to.
  5043. * @returns {ReferenceBaseNode}
  5044. */
  5045. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  5046. /** @module RendererReferenceNode **/
  5047. /**
  5048. * This node is a special type of reference node which is intended
  5049. * for linking renderer properties with node values.
  5050. * ```js
  5051. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  5052. * ```
  5053. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  5054. * automatically be updated.
  5055. *
  5056. * @augments ReferenceBaseNode
  5057. */
  5058. class RendererReferenceNode extends ReferenceBaseNode {
  5059. static get type() {
  5060. return 'RendererReferenceNode';
  5061. }
  5062. /**
  5063. * Constructs a new renderer reference node.
  5064. *
  5065. * @param {String} property - The name of the property the node refers to.
  5066. * @param {String} inputType - The uniform type that should be used to represent the property value.
  5067. * @param {Renderer?} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5068. * the node refers to the renderer of the current state.
  5069. */
  5070. constructor( property, inputType, renderer = null ) {
  5071. super( property, inputType, renderer );
  5072. /**
  5073. * The renderer the property belongs to. When no renderer is set,
  5074. * the node refers to the renderer of the current state.
  5075. *
  5076. * @type {Renderer?}
  5077. * @default null
  5078. */
  5079. this.renderer = renderer;
  5080. this.setGroup( renderGroup );
  5081. }
  5082. /**
  5083. * Updates the reference based on the given state. The state is only evaluated
  5084. * {@link module:RendererReferenceNode~RendererReferenceNode#renderer} is not set.
  5085. *
  5086. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5087. * @return {Object} The updated reference.
  5088. */
  5089. updateReference( state ) {
  5090. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  5091. return this.reference;
  5092. }
  5093. }
  5094. /**
  5095. * TSL function for creating a renderer reference node.
  5096. *
  5097. * @function
  5098. * @param {String} name - The name of the property the node refers to.
  5099. * @param {String} type - The uniform type that should be used to represent the property value.
  5100. * @param {Renderer?} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5101. * the node refers to the renderer of the current state.
  5102. * @returns {RendererReferenceNode}
  5103. */
  5104. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  5105. /** @module ToneMappingNode **/
  5106. /**
  5107. * This node represents a tone mapping operation.
  5108. *
  5109. * @augments TempNode
  5110. */
  5111. class ToneMappingNode extends TempNode {
  5112. static get type() {
  5113. return 'ToneMappingNode';
  5114. }
  5115. /**
  5116. * Constructs a new tone mapping node.
  5117. *
  5118. * @param {Number} toneMapping - The tone mapping type.
  5119. * @param {Node} exposureNode - The tone mapping exposure.
  5120. * @param {Node} [colorNode=null] - The color node to process.
  5121. */
  5122. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  5123. super( 'vec3' );
  5124. /**
  5125. * The tone mapping type.
  5126. *
  5127. * @type {Number}
  5128. */
  5129. this.toneMapping = toneMapping;
  5130. /**
  5131. * The tone mapping exposure.
  5132. *
  5133. * @type {Node}
  5134. * @default null
  5135. */
  5136. this.exposureNode = exposureNode;
  5137. /**
  5138. * Represents the color to process.
  5139. *
  5140. * @type {Node?}
  5141. * @default null
  5142. */
  5143. this.colorNode = colorNode;
  5144. }
  5145. /**
  5146. * Overwrites the default `customCacheKey()` implementation by including the tone
  5147. * mapping type into the cache key.
  5148. *
  5149. * @return {Number} The hash.
  5150. */
  5151. customCacheKey() {
  5152. return hash$1( this.toneMapping );
  5153. }
  5154. setup( builder ) {
  5155. const colorNode = this.colorNode || builder.context.color;
  5156. const toneMapping = this.toneMapping;
  5157. if ( toneMapping === NoToneMapping ) return colorNode;
  5158. let outputNode = null;
  5159. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  5160. if ( toneMappingFn !== null ) {
  5161. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  5162. } else {
  5163. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  5164. outputNode = colorNode;
  5165. }
  5166. return outputNode;
  5167. }
  5168. }
  5169. /**
  5170. * TSL function for creating a tone mapping node.
  5171. *
  5172. * @function
  5173. * @param {Number} mapping - The tone mapping type.
  5174. * @param {Node<float> | Number} exposure - The tone mapping exposure.
  5175. * @param {Node<vec3> | Color} color - The color node to process.
  5176. * @returns {ToneMappingNode<vec3>}
  5177. */
  5178. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  5179. /**
  5180. * TSL object that represents the global tone mapping exposure of the renderer.
  5181. *
  5182. * @type {RendererReferenceNode<vec3>}
  5183. */
  5184. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  5185. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  5186. /** @module BufferAttributeNode **/
  5187. /**
  5188. * In earlier `three.js` versions it was only possible to define attribute data
  5189. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  5190. * on the node level.
  5191. * ```js
  5192. * const geometry = new THREE.PlaneGeometry();
  5193. * const positionAttribute = geometry.getAttribute( 'position' );
  5194. *
  5195. * const colors = [];
  5196. * for ( let i = 0; i < position.count; i ++ ) {
  5197. * colors.push( 1, 0, 0 );
  5198. * }
  5199. *
  5200. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  5201. * ```
  5202. * This new approach is especially interesting when geometry data are generated via
  5203. * compute shaders. The below line converts a storage buffer into an attribute node.
  5204. * ```js
  5205. * material.positionNode = positionBuffer.toAttribute();
  5206. * ```
  5207. * @augments InputNode
  5208. */
  5209. class BufferAttributeNode extends InputNode {
  5210. static get type() {
  5211. return 'BufferAttributeNode';
  5212. }
  5213. /**
  5214. * Constructs a new buffer attribute node.
  5215. *
  5216. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  5217. * @param {String?} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  5218. * @param {Number} [bufferStride=0] - The buffer stride.
  5219. * @param {Number} [bufferOffset=0] - The buffer offset.
  5220. */
  5221. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  5222. super( value, bufferType );
  5223. /**
  5224. * This flag can be used for type testing.
  5225. *
  5226. * @type {Boolean}
  5227. * @readonly
  5228. * @default true
  5229. */
  5230. this.isBufferNode = true;
  5231. /**
  5232. * The buffer type (e.g. `'vec3'`).
  5233. *
  5234. * @type {String}
  5235. * @default null
  5236. */
  5237. this.bufferType = bufferType;
  5238. /**
  5239. * The buffer stride.
  5240. *
  5241. * @type {Number}
  5242. * @default 0
  5243. */
  5244. this.bufferStride = bufferStride;
  5245. /**
  5246. * The buffer offset.
  5247. *
  5248. * @type {Number}
  5249. * @default 0
  5250. */
  5251. this.bufferOffset = bufferOffset;
  5252. /**
  5253. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  5254. * if you are planning to update the attribute data per frame.
  5255. *
  5256. * @type {Number}
  5257. * @default StaticDrawUsage
  5258. */
  5259. this.usage = StaticDrawUsage;
  5260. /**
  5261. * Whether the attribute is instanced or not.
  5262. *
  5263. * @type {Boolean}
  5264. * @default false
  5265. */
  5266. this.instanced = false;
  5267. /**
  5268. * A reference to the buffer attribute.
  5269. *
  5270. * @type {BufferAttribute?}
  5271. * @default null
  5272. */
  5273. this.attribute = null;
  5274. /**
  5275. * `BufferAttributeNode` sets this property to `true` by default.
  5276. *
  5277. * @type {Boolean}
  5278. * @default true
  5279. */
  5280. this.global = true;
  5281. if ( value && value.isBufferAttribute === true ) {
  5282. this.attribute = value;
  5283. this.usage = value.usage;
  5284. this.instanced = value.isInstancedBufferAttribute;
  5285. }
  5286. }
  5287. /**
  5288. * This method is overwritten since the attribute data might be shared
  5289. * and thus the hash should be shared as well.
  5290. *
  5291. * @param {NodeBuilder} builder - The current node builder.
  5292. * @return {String} The hash.
  5293. */
  5294. getHash( builder ) {
  5295. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  5296. let bufferData = builder.globalCache.getData( this.value );
  5297. if ( bufferData === undefined ) {
  5298. bufferData = {
  5299. node: this
  5300. };
  5301. builder.globalCache.setData( this.value, bufferData );
  5302. }
  5303. return bufferData.node.uuid;
  5304. }
  5305. return this.uuid;
  5306. }
  5307. /**
  5308. * This method is overwritten since the node type is inferred from
  5309. * the buffer attribute.
  5310. *
  5311. * @param {NodeBuilder} builder - The current node builder.
  5312. * @return {String} The node type.
  5313. */
  5314. getNodeType( builder ) {
  5315. if ( this.bufferType === null ) {
  5316. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  5317. }
  5318. return this.bufferType;
  5319. }
  5320. /**
  5321. * Depending on which value was passed to the node, `setup()` behaves
  5322. * differently. If no instance of `BufferAttribute` was passed, the method
  5323. * creates an internal attribute and configures it respectively.
  5324. *
  5325. * @param {NodeBuilder} builder - The current node builder.
  5326. */
  5327. setup( builder ) {
  5328. if ( this.attribute !== null ) return;
  5329. const type = this.getNodeType( builder );
  5330. const array = this.value;
  5331. const itemSize = builder.getTypeLength( type );
  5332. const stride = this.bufferStride || itemSize;
  5333. const offset = this.bufferOffset;
  5334. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  5335. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  5336. buffer.setUsage( this.usage );
  5337. this.attribute = bufferAttribute;
  5338. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  5339. }
  5340. /**
  5341. * Generates the code snippet of the buffer attribute node.
  5342. *
  5343. * @param {NodeBuilder} builder - The current node builder.
  5344. * @return {String} The generated code snippet.
  5345. */
  5346. generate( builder ) {
  5347. const nodeType = this.getNodeType( builder );
  5348. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  5349. const propertyName = builder.getPropertyName( nodeAttribute );
  5350. let output = null;
  5351. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  5352. this.name = propertyName;
  5353. output = propertyName;
  5354. } else {
  5355. const nodeVarying = varying( this );
  5356. output = nodeVarying.build( builder, nodeType );
  5357. }
  5358. return output;
  5359. }
  5360. /**
  5361. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  5362. *
  5363. * @param {NodeBuilder} builder - The current node builder.
  5364. * @return {String} The input type.
  5365. */
  5366. getInputType( /*builder*/ ) {
  5367. return 'bufferAttribute';
  5368. }
  5369. /**
  5370. * Sets the `usage` property to the given value.
  5371. *
  5372. * @param {Number} value - The usage to set.
  5373. * @return {BufferAttributeNode} A reference to this node.
  5374. */
  5375. setUsage( value ) {
  5376. this.usage = value;
  5377. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  5378. this.attribute.usage = value;
  5379. }
  5380. return this;
  5381. }
  5382. /**
  5383. * Sets the `instanced` property to the given value.
  5384. *
  5385. * @param {Number} value - The value to set.
  5386. * @return {BufferAttributeNode} A reference to this node.
  5387. */
  5388. setInstanced( value ) {
  5389. this.instanced = value;
  5390. return this;
  5391. }
  5392. }
  5393. /**
  5394. * TSL function for creating a buffer attribute node.
  5395. *
  5396. * @function
  5397. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5398. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5399. * @param {Number} [stride=0] - The buffer stride.
  5400. * @param {Number} [offset=0] - The buffer offset.
  5401. * @returns {BufferAttributeNode}
  5402. */
  5403. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  5404. /**
  5405. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  5406. * Use this function if attribute data are updated per frame.
  5407. *
  5408. * @function
  5409. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5410. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5411. * @param {Number} [stride=0] - The buffer stride.
  5412. * @param {Number} [offset=0] - The buffer offset.
  5413. * @returns {BufferAttributeNode}
  5414. */
  5415. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  5416. /**
  5417. * TSL function for creating a buffer attribute node but with enabled instancing
  5418. *
  5419. * @function
  5420. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5421. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5422. * @param {Number} [stride=0] - The buffer stride.
  5423. * @param {Number} [offset=0] - The buffer offset.
  5424. * @returns {BufferAttributeNode}
  5425. */
  5426. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  5427. /**
  5428. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  5429. *
  5430. * @function
  5431. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5432. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5433. * @param {Number} [stride=0] - The buffer stride.
  5434. * @param {Number} [offset=0] - The buffer offset.
  5435. * @returns {BufferAttributeNode}
  5436. */
  5437. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  5438. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  5439. /** @module ComputeNode **/
  5440. /**
  5441. * TODO
  5442. *
  5443. * @augments Node
  5444. */
  5445. class ComputeNode extends Node {
  5446. static get type() {
  5447. return 'ComputeNode';
  5448. }
  5449. /**
  5450. * Constructs a new compute node.
  5451. *
  5452. * @param {Node} computeNode - TODO
  5453. * @param {Number} count - TODO.
  5454. * @param {Array<Number>} [workgroupSize=[64]] - TODO.
  5455. */
  5456. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  5457. super( 'void' );
  5458. /**
  5459. * This flag can be used for type testing.
  5460. *
  5461. * @type {Boolean}
  5462. * @readonly
  5463. * @default true
  5464. */
  5465. this.isComputeNode = true;
  5466. /**
  5467. * TODO
  5468. *
  5469. * @type {Node}
  5470. */
  5471. this.computeNode = computeNode;
  5472. /**
  5473. * TODO
  5474. *
  5475. * @type {Number}
  5476. */
  5477. this.count = count;
  5478. /**
  5479. * TODO
  5480. *
  5481. * @type {Array<Number>}
  5482. * @default [64]
  5483. */
  5484. this.workgroupSize = workgroupSize;
  5485. /**
  5486. * TODO
  5487. *
  5488. * @type {Number}
  5489. */
  5490. this.dispatchCount = 0;
  5491. /**
  5492. * TODO
  5493. *
  5494. * @type {Number}
  5495. */
  5496. this.version = 1;
  5497. /**
  5498. * The name or label of the uniform.
  5499. *
  5500. * @type {String}
  5501. * @default ''
  5502. */
  5503. this.name = '';
  5504. /**
  5505. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  5506. * is executed once per object by default.
  5507. *
  5508. * @type {String}
  5509. * @default 'object'
  5510. */
  5511. this.updateBeforeType = NodeUpdateType.OBJECT;
  5512. /**
  5513. * TODO
  5514. *
  5515. * @type {Function}
  5516. */
  5517. this.onInitFunction = null;
  5518. this.updateDispatchCount();
  5519. }
  5520. /**
  5521. * Executes the `dispose` event for this node.
  5522. */
  5523. dispose() {
  5524. this.dispatchEvent( { type: 'dispose' } );
  5525. }
  5526. /**
  5527. * Sets the {@link ComputeNode#name} property.
  5528. *
  5529. * @param {String} name - The name of the uniform.
  5530. * @return {ComputeNode} A reference to this node.
  5531. */
  5532. label( name ) {
  5533. this.name = name;
  5534. return this;
  5535. }
  5536. /**
  5537. * TODO
  5538. */
  5539. updateDispatchCount() {
  5540. const { count, workgroupSize } = this;
  5541. let size = workgroupSize[ 0 ];
  5542. for ( let i = 1; i < workgroupSize.length; i ++ )
  5543. size *= workgroupSize[ i ];
  5544. this.dispatchCount = Math.ceil( count / size );
  5545. }
  5546. /**
  5547. * TODO
  5548. *
  5549. * @param {Function} callback - TODO.
  5550. * @return {ComputeNode} A reference to this node.
  5551. */
  5552. onInit( callback ) {
  5553. this.onInitFunction = callback;
  5554. return this;
  5555. }
  5556. /**
  5557. * The method execute the compute for this node.
  5558. *
  5559. * @param {NodeFrame} frame - A reference to the current node frame.
  5560. */
  5561. updateBefore( { renderer } ) {
  5562. renderer.compute( this );
  5563. }
  5564. generate( builder ) {
  5565. const { shaderStage } = builder;
  5566. if ( shaderStage === 'compute' ) {
  5567. const snippet = this.computeNode.build( builder, 'void' );
  5568. if ( snippet !== '' ) {
  5569. builder.addLineFlowCode( snippet, this );
  5570. }
  5571. }
  5572. }
  5573. }
  5574. /**
  5575. * TSL function for creating a compute node.
  5576. *
  5577. * @function
  5578. * @param {Node} node - TODO
  5579. * @param {Number} count - TODO.
  5580. * @param {Array<Number>} [workgroupSize=[64]] - TODO.
  5581. * @returns {AtomicFunctionNode}
  5582. */
  5583. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  5584. addMethodChaining( 'compute', compute );
  5585. /** @module CacheNode **/
  5586. /**
  5587. * This node can be used as a cache management component for another node.
  5588. * Caching is in general used by default in {@link NodeBuilder} but this node
  5589. * allows the usage of a shared parent cache during the build process.
  5590. *
  5591. * @augments Node
  5592. */
  5593. class CacheNode extends Node {
  5594. static get type() {
  5595. return 'CacheNode';
  5596. }
  5597. /**
  5598. * Constructs a new cache node.
  5599. *
  5600. * @param {Node} node - The node that should be cached.
  5601. * @param {Boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  5602. */
  5603. constructor( node, parent = true ) {
  5604. super();
  5605. /**
  5606. * The node that should be cached.
  5607. *
  5608. * @type {Node}
  5609. */
  5610. this.node = node;
  5611. /**
  5612. * Whether this node refers to a shared parent cache or not.
  5613. *
  5614. * @type {Boolean}
  5615. * @default true
  5616. */
  5617. this.parent = parent;
  5618. /**
  5619. * This flag can be used for type testing.
  5620. *
  5621. * @type {Boolean}
  5622. * @readonly
  5623. * @default true
  5624. */
  5625. this.isCacheNode = true;
  5626. }
  5627. getNodeType( builder ) {
  5628. const previousCache = builder.getCache();
  5629. const cache = builder.getCacheFromNode( this, this.parent );
  5630. builder.setCache( cache );
  5631. const nodeType = this.node.getNodeType( builder );
  5632. builder.setCache( previousCache );
  5633. return nodeType;
  5634. }
  5635. build( builder, ...params ) {
  5636. const previousCache = builder.getCache();
  5637. const cache = builder.getCacheFromNode( this, this.parent );
  5638. builder.setCache( cache );
  5639. const data = this.node.build( builder, ...params );
  5640. builder.setCache( previousCache );
  5641. return data;
  5642. }
  5643. }
  5644. /**
  5645. * TSL function for creating a cache node.
  5646. *
  5647. * @function
  5648. * @param {Node} node - The node that should be cached.
  5649. * @param {Boolean} parent - Whether this node refers to a shared parent cache or not.
  5650. * @returns {CacheNode}
  5651. */
  5652. const cache = ( node, parent ) => nodeObject( new CacheNode( nodeObject( node ), parent ) );
  5653. addMethodChaining( 'cache', cache );
  5654. /** @module BypassNode **/
  5655. /**
  5656. * The class generates the code of a given node but returns another node in the output.
  5657. * This can be used to call a method or node that does not return a value, i.e.
  5658. * type `void` on an input where returning a value is required. Example:
  5659. *
  5660. * ```js
  5661. * material.colorNode = myColor.bypass( runVoidFn() )
  5662. *```
  5663. *
  5664. * @augments Node
  5665. */
  5666. class BypassNode extends Node {
  5667. static get type() {
  5668. return 'BypassNode';
  5669. }
  5670. /**
  5671. * Constructs a new bypass node.
  5672. *
  5673. * @param {Node} outputNode - The output node.
  5674. * @param {Node} callNode - The call node.
  5675. */
  5676. constructor( outputNode, callNode ) {
  5677. super();
  5678. /**
  5679. * This flag can be used for type testing.
  5680. *
  5681. * @type {Boolean}
  5682. * @readonly
  5683. * @default true
  5684. */
  5685. this.isBypassNode = true;
  5686. /**
  5687. * The output node.
  5688. *
  5689. * @type {Node}
  5690. */
  5691. this.outputNode = outputNode;
  5692. /**
  5693. * The call node.
  5694. *
  5695. * @type {Node}
  5696. */
  5697. this.callNode = callNode;
  5698. }
  5699. getNodeType( builder ) {
  5700. return this.outputNode.getNodeType( builder );
  5701. }
  5702. generate( builder ) {
  5703. const snippet = this.callNode.build( builder, 'void' );
  5704. if ( snippet !== '' ) {
  5705. builder.addLineFlowCode( snippet, this );
  5706. }
  5707. return this.outputNode.build( builder );
  5708. }
  5709. }
  5710. /**
  5711. * TSL function for creating a bypass node.
  5712. *
  5713. * @function
  5714. * @param {Node} outputNode - The output node.
  5715. * @param {Node} callNode - The call node.
  5716. * @returns {BypassNode}
  5717. */
  5718. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  5719. addMethodChaining( 'bypass', bypass );
  5720. /** @module RemapNode **/
  5721. /**
  5722. * This node allows to remap a node value from one range into another. E.g a value of
  5723. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  5724. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  5725. *
  5726. * @augments Node
  5727. */
  5728. class RemapNode extends Node {
  5729. static get type() {
  5730. return 'RemapNode';
  5731. }
  5732. /**
  5733. * Constructs a new remap node.
  5734. *
  5735. * @param {Node} node - The node that should be remapped.
  5736. * @param {Node} inLowNode - The source or current lower bound of the range.
  5737. * @param {Node} inHighNode - The source or current upper bound of the range.
  5738. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  5739. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  5740. */
  5741. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  5742. super();
  5743. /**
  5744. * The node that should be remapped.
  5745. *
  5746. * @type {Node}
  5747. */
  5748. this.node = node;
  5749. /**
  5750. * The source or current lower bound of the range.
  5751. *
  5752. * @type {Node}
  5753. */
  5754. this.inLowNode = inLowNode;
  5755. /**
  5756. * The source or current upper bound of the range.
  5757. *
  5758. * @type {Node}
  5759. */
  5760. this.inHighNode = inHighNode;
  5761. /**
  5762. * The target lower bound of the range.
  5763. *
  5764. * @type {Node}
  5765. * @default float(0)
  5766. */
  5767. this.outLowNode = outLowNode;
  5768. /**
  5769. * The target upper bound of the range.
  5770. *
  5771. * @type {Node}
  5772. * @default float(1)
  5773. */
  5774. this.outHighNode = outHighNode;
  5775. /**
  5776. * Whether the node value should be clamped before
  5777. * remapping it to the target range.
  5778. *
  5779. * @type {Boolean}
  5780. * @default true
  5781. */
  5782. this.doClamp = true;
  5783. }
  5784. setup() {
  5785. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  5786. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  5787. if ( doClamp === true ) t = t.clamp();
  5788. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  5789. }
  5790. }
  5791. /**
  5792. * TSL function for creating a remap node.
  5793. *
  5794. * @function
  5795. * @param {Node} node - The node that should be remapped.
  5796. * @param {Node} inLowNode - The source or current lower bound of the range.
  5797. * @param {Node} inHighNode - The source or current upper bound of the range.
  5798. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  5799. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  5800. * @returns {RemapNode}
  5801. */
  5802. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  5803. /**
  5804. * TSL function for creating a remap node, but with enabled clamping.
  5805. *
  5806. * @function
  5807. * @param {Node} node - The node that should be remapped.
  5808. * @param {Node} inLowNode - The source or current lower bound of the range.
  5809. * @param {Node} inHighNode - The source or current upper bound of the range.
  5810. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  5811. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  5812. * @returns {RemapNode}
  5813. */
  5814. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  5815. addMethodChaining( 'remap', remap );
  5816. addMethodChaining( 'remapClamp', remapClamp );
  5817. /** @module ExpressionNode **/
  5818. /**
  5819. * This class can be used to implement basic expressions in shader code.
  5820. * Basic examples for that are `return`, `continue` or `discard` statements.
  5821. *
  5822. * @augments Node
  5823. */
  5824. class ExpressionNode extends Node {
  5825. static get type() {
  5826. return 'ExpressionNode';
  5827. }
  5828. /**
  5829. * Constructs a new expression node.
  5830. *
  5831. * @param {String} [snippet=''] - The native code snippet.
  5832. * @param {String} [nodeType='void'] - The node type.
  5833. */
  5834. constructor( snippet = '', nodeType = 'void' ) {
  5835. super( nodeType );
  5836. /**
  5837. * The native code snippet.
  5838. *
  5839. * @type {String}
  5840. * @default ''
  5841. */
  5842. this.snippet = snippet;
  5843. }
  5844. generate( builder, output ) {
  5845. const type = this.getNodeType( builder );
  5846. const snippet = this.snippet;
  5847. if ( type === 'void' ) {
  5848. builder.addLineFlowCode( snippet, this );
  5849. } else {
  5850. return builder.format( `( ${ snippet } )`, type, output );
  5851. }
  5852. }
  5853. }
  5854. /**
  5855. * TSL function for creating an expression node.
  5856. *
  5857. * @function
  5858. * @param {String} [snippet=''] - The native code snippet.
  5859. * @param {String} [nodeType='void'] - The node type.
  5860. * @returns {ExpressionNode}
  5861. */
  5862. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  5863. /** @module Discard **/
  5864. /**
  5865. * Represents a `discard` shader operation in TSL.
  5866. *
  5867. * @method
  5868. * @param {ConditionalNode?} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  5869. * @return {Node} The `discard` expression.
  5870. */
  5871. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  5872. /**
  5873. * Represents a `return` shader operation in TSL.
  5874. *
  5875. * @method
  5876. * @return {ExpressionNode} The `return` expression.
  5877. */
  5878. const Return = () => expression( 'return' ).append();
  5879. addMethodChaining( 'discard', Discard );
  5880. /** @module RenderOutputNode **/
  5881. /**
  5882. * Normally, tone mapping and color conversion happens automatically
  5883. * before outputting pixel too the default (screen) framebuffer. In certain
  5884. * post processing setups this happens to late because certain effects
  5885. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  5886. * to apply tone mapping and color space conversion at an arbitrary point
  5887. * in the effect chain.
  5888. *
  5889. * When applying tone mapping and color space conversion manually with this node,
  5890. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  5891. *
  5892. * ```js
  5893. * const postProcessing = new PostProcessing( renderer );
  5894. * postProcessing.outputColorTransform = false;
  5895. *
  5896. * const scenePass = pass( scene, camera );
  5897. * const outputPass = renderOutput( scenePass );
  5898. *
  5899. * postProcessing.outputNode = outputPass;
  5900. * ```
  5901. *
  5902. * @augments TempNode
  5903. */
  5904. class RenderOutputNode extends TempNode {
  5905. static get type() {
  5906. return 'RenderOutputNode';
  5907. }
  5908. /**
  5909. * Constructs a new render output node.
  5910. *
  5911. * @param {Node} colorNode - The color node to process.
  5912. * @param {Number} toneMapping - The tone mapping type.
  5913. * @param {String} outputColorSpace - The output color space.
  5914. */
  5915. constructor( colorNode, toneMapping, outputColorSpace ) {
  5916. super( 'vec4' );
  5917. /**
  5918. * The color node to process.
  5919. *
  5920. * @type {Node}
  5921. */
  5922. this.colorNode = colorNode;
  5923. /**
  5924. * The tone mapping type.
  5925. *
  5926. * @type {Number?}
  5927. */
  5928. this.toneMapping = toneMapping;
  5929. /**
  5930. * The output color space.
  5931. *
  5932. * @type {String?}
  5933. */
  5934. this.outputColorSpace = outputColorSpace;
  5935. /**
  5936. * This flag can be used for type testing.
  5937. *
  5938. * @type {Boolean}
  5939. * @readonly
  5940. * @default true
  5941. */
  5942. this.isRenderOutputNode = true;
  5943. }
  5944. setup( { context } ) {
  5945. let outputNode = this.colorNode || context.color;
  5946. // tone mapping
  5947. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  5948. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  5949. if ( toneMapping !== NoToneMapping ) {
  5950. outputNode = outputNode.toneMapping( toneMapping );
  5951. }
  5952. // working to output color space
  5953. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  5954. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  5955. }
  5956. return outputNode;
  5957. }
  5958. }
  5959. /**
  5960. * TSL function for creating a posterize node.
  5961. *
  5962. * @function
  5963. * @param {Node} color - The color node to process.
  5964. * @param {Number?} [toneMapping=null] - The tone mapping type.
  5965. * @param {String?} [outputColorSpace=null] - The output color space.
  5966. * @returns {RenderOutputNode}
  5967. */
  5968. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  5969. addMethodChaining( 'renderOutput', renderOutput );
  5970. // Non-PURE exports list, side-effects are required here.
  5971. // TSL Base Syntax
  5972. function addNodeElement( name/*, nodeElement*/ ) {
  5973. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  5974. }
  5975. /** @module AttributeNode **/
  5976. /**
  5977. * Base class for representing shader attributes as nodes.
  5978. *
  5979. * @augments Node
  5980. */
  5981. class AttributeNode extends Node {
  5982. static get type() {
  5983. return 'AttributeNode';
  5984. }
  5985. /**
  5986. * Constructs a new attribute node.
  5987. *
  5988. * @param {String} attributeName - The name of the attribute.
  5989. * @param {String?} nodeType - The node type.
  5990. */
  5991. constructor( attributeName, nodeType = null ) {
  5992. super( nodeType );
  5993. /**
  5994. * `AttributeNode` sets this property to `true` by default.
  5995. *
  5996. * @type {Boolean}
  5997. * @default true
  5998. */
  5999. this.global = true;
  6000. this._attributeName = attributeName;
  6001. }
  6002. getHash( builder ) {
  6003. return this.getAttributeName( builder );
  6004. }
  6005. getNodeType( builder ) {
  6006. let nodeType = this.nodeType;
  6007. if ( nodeType === null ) {
  6008. const attributeName = this.getAttributeName( builder );
  6009. if ( builder.hasGeometryAttribute( attributeName ) ) {
  6010. const attribute = builder.geometry.getAttribute( attributeName );
  6011. nodeType = builder.getTypeFromAttribute( attribute );
  6012. } else {
  6013. nodeType = 'float';
  6014. }
  6015. }
  6016. return nodeType;
  6017. }
  6018. /**
  6019. * Sets the attribute name to the given value. The method can be
  6020. * overwritten in derived classes if the final name must be computed
  6021. * analytically.
  6022. *
  6023. * @param {String} attributeName - The name of the attribute.
  6024. * @return {AttributeNode} A reference to this node.
  6025. */
  6026. setAttributeName( attributeName ) {
  6027. this._attributeName = attributeName;
  6028. return this;
  6029. }
  6030. /**
  6031. * Returns the attribute name of this node. The method can be
  6032. * overwritten in derived classes if the final name must be computed
  6033. * analytically.
  6034. *
  6035. * @param {NodeBuilder} builder - The current node builder.
  6036. * @return {String} The attribute name.
  6037. */
  6038. getAttributeName( /*builder*/ ) {
  6039. return this._attributeName;
  6040. }
  6041. generate( builder ) {
  6042. const attributeName = this.getAttributeName( builder );
  6043. const nodeType = this.getNodeType( builder );
  6044. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  6045. if ( geometryAttribute === true ) {
  6046. const attribute = builder.geometry.getAttribute( attributeName );
  6047. const attributeType = builder.getTypeFromAttribute( attribute );
  6048. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  6049. if ( builder.shaderStage === 'vertex' ) {
  6050. return builder.format( nodeAttribute.name, attributeType, nodeType );
  6051. } else {
  6052. const nodeVarying = varying( this );
  6053. return nodeVarying.build( builder, nodeType );
  6054. }
  6055. } else {
  6056. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  6057. return builder.generateConst( nodeType );
  6058. }
  6059. }
  6060. serialize( data ) {
  6061. super.serialize( data );
  6062. data.global = this.global;
  6063. data._attributeName = this._attributeName;
  6064. }
  6065. deserialize( data ) {
  6066. super.deserialize( data );
  6067. this.global = data.global;
  6068. this._attributeName = data._attributeName;
  6069. }
  6070. }
  6071. /**
  6072. * TSL function for creating an attribute node.
  6073. *
  6074. * @function
  6075. * @param {String} name - The name of the attribute.
  6076. * @param {String?} nodeType - The node type.
  6077. * @returns {AttributeNode}
  6078. */
  6079. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  6080. /** @module UV **/
  6081. /**
  6082. * TSL function for creating an uv attribute node with the given index.
  6083. *
  6084. * @function
  6085. * @param {Number} [index=0] - The uv index.
  6086. * @return {AttributeNode<vec2>} The uv attribute node.
  6087. */
  6088. const uv = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  6089. /** @module TextureSizeNode **/
  6090. /**
  6091. * A node that represents the dimensions of a texture. The texture size is
  6092. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  6093. * or `textureSize()`.
  6094. *
  6095. * @augments Node
  6096. */
  6097. class TextureSizeNode extends Node {
  6098. static get type() {
  6099. return 'TextureSizeNode';
  6100. }
  6101. /**
  6102. * Constructs a new texture size node.
  6103. *
  6104. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6105. * @param {Node<int>?} [levelNode=null] - A level node which defines the requested mip.
  6106. */
  6107. constructor( textureNode, levelNode = null ) {
  6108. super( 'uvec2' );
  6109. /**
  6110. * This flag can be used for type testing.
  6111. *
  6112. * @type {Boolean}
  6113. * @readonly
  6114. * @default true
  6115. */
  6116. this.isTextureSizeNode = true;
  6117. /**
  6118. * A texture node which size should be retrieved.
  6119. *
  6120. * @type {TextureNode}
  6121. */
  6122. this.textureNode = textureNode;
  6123. /**
  6124. * A level node which defines the requested mip.
  6125. *
  6126. * @type {Node<int>}
  6127. * @default null
  6128. */
  6129. this.levelNode = levelNode;
  6130. }
  6131. generate( builder, output ) {
  6132. const textureProperty = this.textureNode.build( builder, 'property' );
  6133. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  6134. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  6135. }
  6136. }
  6137. /**
  6138. * TSL function for creating a texture size node.
  6139. *
  6140. * @function
  6141. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6142. * @param {Node<int>?} [levelNode=null] - A level node which defines the requested mip.
  6143. * @returns {TextureSizeNode}
  6144. */
  6145. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  6146. /** @module MatcapUVNode **/
  6147. /**
  6148. * A special type of uniform node that computes the
  6149. * maximum mipmap level for a given texture node.
  6150. *
  6151. * ```js
  6152. * const level = maxMipLevel( textureNode );
  6153. * ```
  6154. *
  6155. * @augments module:UniformNode~UniformNode
  6156. */
  6157. class MaxMipLevelNode extends UniformNode {
  6158. static get type() {
  6159. return 'MaxMipLevelNode';
  6160. }
  6161. /**
  6162. * Constructs a new max mip level node.
  6163. *
  6164. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  6165. */
  6166. constructor( textureNode ) {
  6167. super( 0 );
  6168. /**
  6169. * The texture node to compute the max mip level for.
  6170. *
  6171. * @private
  6172. * @type {TextureNode}
  6173. */
  6174. this._textureNode = textureNode;
  6175. /**
  6176. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  6177. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  6178. *
  6179. * @type {String}
  6180. * @default 'frame'
  6181. */
  6182. this.updateType = NodeUpdateType.FRAME;
  6183. }
  6184. /**
  6185. * The texture node to compute the max mip level for.
  6186. *
  6187. * @readonly
  6188. * @type {TextureNode}
  6189. */
  6190. get textureNode() {
  6191. return this._textureNode;
  6192. }
  6193. /**
  6194. * The texture.
  6195. *
  6196. * @readonly
  6197. * @type {Texture}
  6198. */
  6199. get texture() {
  6200. return this._textureNode.value;
  6201. }
  6202. update() {
  6203. const texture = this.texture;
  6204. const images = texture.images;
  6205. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  6206. if ( image && image.width !== undefined ) {
  6207. const { width, height } = image;
  6208. this.value = Math.log2( Math.max( width, height ) );
  6209. }
  6210. }
  6211. }
  6212. /**
  6213. * TSL function for creating a max mip level node.
  6214. *
  6215. * @function
  6216. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  6217. * @returns {MaxMipLevelNode}
  6218. */
  6219. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  6220. /** @module TextureNode **/
  6221. /**
  6222. * This type of uniform node represents a 2D texture.
  6223. *
  6224. * @augments module:UniformNode~UniformNode
  6225. */
  6226. class TextureNode extends UniformNode {
  6227. static get type() {
  6228. return 'TextureNode';
  6229. }
  6230. /**
  6231. * Constructs a new texture node.
  6232. *
  6233. * @param {Texture} value - The texture.
  6234. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  6235. * @param {Node<int>?} [levelNode=null] - The level node.
  6236. * @param {Node<float>?} [biasNode=null] - The bias node.
  6237. */
  6238. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  6239. super( value );
  6240. /**
  6241. * This flag can be used for type testing.
  6242. *
  6243. * @type {Boolean}
  6244. * @readonly
  6245. * @default true
  6246. */
  6247. this.isTextureNode = true;
  6248. /**
  6249. * Represents the texture coordinates.
  6250. *
  6251. * @type {Node<vec2|vec3>?}
  6252. * @default null
  6253. */
  6254. this.uvNode = uvNode;
  6255. /**
  6256. * Represents the mip level that should be selected.
  6257. *
  6258. * @type {Node<int>?}
  6259. * @default null
  6260. */
  6261. this.levelNode = levelNode;
  6262. /**
  6263. * Represents the bias to be applied during level-of-detail computation.
  6264. *
  6265. * @type {Node<float>?}
  6266. * @default null
  6267. */
  6268. this.biasNode = biasNode;
  6269. /**
  6270. * Represents a reference value a texture sample is compared to.
  6271. *
  6272. * @type {Node<float>?}
  6273. * @default null
  6274. */
  6275. this.compareNode = null;
  6276. /**
  6277. * When using texture arrays, the depth node defines the layer to select.
  6278. *
  6279. * @type {Node<int>?}
  6280. * @default null
  6281. */
  6282. this.depthNode = null;
  6283. /**
  6284. * When defined, a texture is sampled using explicit gradients.
  6285. *
  6286. * @type {Array<Node<vec2>>?}
  6287. * @default null
  6288. */
  6289. this.gradNode = null;
  6290. /**
  6291. * Whether texture values should be sampled or fetched.
  6292. *
  6293. * @type {Boolean}
  6294. * @default true
  6295. */
  6296. this.sampler = true;
  6297. /**
  6298. * Whether the uv transformation matrix should be
  6299. * automatically updated or not. Use `setUpdateMatrix()`
  6300. * if you want to change the value of the property.
  6301. *
  6302. * @type {Boolean}
  6303. * @default false
  6304. */
  6305. this.updateMatrix = false;
  6306. /**
  6307. * By default the `update()` method is not executed. `setUpdateMatrix()`
  6308. * sets the value to `frame` when the uv transformation matrix should
  6309. * automatically be updated.
  6310. *
  6311. * @type {String}
  6312. * @default 'none'
  6313. */
  6314. this.updateType = NodeUpdateType.NONE;
  6315. /**
  6316. * The reference node.
  6317. *
  6318. * @type {Node?}
  6319. * @default null
  6320. */
  6321. this.referenceNode = null;
  6322. /**
  6323. * The texture value is stored in a private property.
  6324. *
  6325. * @private
  6326. * @type {Texture}
  6327. */
  6328. this._value = value;
  6329. /**
  6330. * The uniform node that represents the uv transformation matrix.
  6331. *
  6332. * @private
  6333. * @type {UniformNode<mat3>?}
  6334. */
  6335. this._matrixUniform = null;
  6336. this.setUpdateMatrix( uvNode === null );
  6337. }
  6338. set value( value ) {
  6339. if ( this.referenceNode ) {
  6340. this.referenceNode.value = value;
  6341. } else {
  6342. this._value = value;
  6343. }
  6344. }
  6345. /**
  6346. * The texture value.
  6347. *
  6348. * @type {Texture}
  6349. */
  6350. get value() {
  6351. return this.referenceNode ? this.referenceNode.value : this._value;
  6352. }
  6353. /**
  6354. * Overwritten since the uniform hash is defined by the texture's UUID.
  6355. *
  6356. * @param {NodeBuilder} builder - The current node builder.
  6357. * @return {String} The uniform hash.
  6358. */
  6359. getUniformHash( /*builder*/ ) {
  6360. return this.value.uuid;
  6361. }
  6362. /**
  6363. * Overwritten since the node type is inferred from the texture type.
  6364. *
  6365. * @param {NodeBuilder} builder - The current node builder.
  6366. * @return {String} The node type.
  6367. */
  6368. getNodeType( /*builder*/ ) {
  6369. if ( this.value.isDepthTexture === true ) return 'float';
  6370. if ( this.value.type === UnsignedIntType ) {
  6371. return 'uvec4';
  6372. } else if ( this.value.type === IntType ) {
  6373. return 'ivec4';
  6374. }
  6375. return 'vec4';
  6376. }
  6377. /**
  6378. * Overwrites the default implementation to return a fixed value `'texture'`.
  6379. *
  6380. * @param {NodeBuilder} builder - The current node builder.
  6381. * @return {String} The input type.
  6382. */
  6383. getInputType( /*builder*/ ) {
  6384. return 'texture';
  6385. }
  6386. /**
  6387. * Returns a default uvs based on the current texture's channel.
  6388. *
  6389. * @return {AttributeNode<vec2>} The default uvs.
  6390. */
  6391. getDefaultUV() {
  6392. return uv( this.value.channel );
  6393. }
  6394. /**
  6395. * Overwritten to always return the texture reference of the node.
  6396. *
  6397. * @param {Any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  6398. * @return {Texture} The texture reference.
  6399. */
  6400. updateReference( /*state*/ ) {
  6401. return this.value;
  6402. }
  6403. /**
  6404. * Transforms the given uv node with the texture transformation matrix.
  6405. *
  6406. * @param {Node} uvNode - The uv node to transform.
  6407. * @return {Node} The transformed uv node.
  6408. */
  6409. getTransformedUV( uvNode ) {
  6410. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  6411. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  6412. }
  6413. /**
  6414. * Defines whether the uv transformation matrix should automatically be updated or not.
  6415. *
  6416. * @param {Boolean} value - The update toggle.
  6417. * @return {TextureNode} A reference to this node.
  6418. */
  6419. setUpdateMatrix( value ) {
  6420. this.updateMatrix = value;
  6421. this.updateType = value ? NodeUpdateType.RENDER : NodeUpdateType.NONE;
  6422. return this;
  6423. }
  6424. /**
  6425. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  6426. * to modify the uv node for correct sampling.
  6427. *
  6428. * @param {NodeBuilder} builder - The current node builder.
  6429. * @param {Node} uvNode - The uv node to setup.
  6430. * @return {Node} The updated uv node.
  6431. */
  6432. setupUV( builder, uvNode ) {
  6433. const texture = this.value;
  6434. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  6435. if ( this.sampler ) {
  6436. uvNode = uvNode.flipY();
  6437. } else {
  6438. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  6439. }
  6440. }
  6441. return uvNode;
  6442. }
  6443. /**
  6444. * Setups texture node by preparing the internal nodes for code generation.
  6445. *
  6446. * @param {NodeBuilder} builder - The current node builder.
  6447. */
  6448. setup( builder ) {
  6449. const properties = builder.getNodeProperties( this );
  6450. properties.referenceNode = this.referenceNode;
  6451. //
  6452. const texture = this.value;
  6453. if ( ! texture || texture.isTexture !== true ) {
  6454. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  6455. }
  6456. //
  6457. let uvNode = this.uvNode;
  6458. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  6459. uvNode = builder.context.getUV( this );
  6460. }
  6461. if ( ! uvNode ) uvNode = this.getDefaultUV();
  6462. if ( this.updateMatrix === true ) {
  6463. uvNode = this.getTransformedUV( uvNode );
  6464. }
  6465. uvNode = this.setupUV( builder, uvNode );
  6466. //
  6467. let levelNode = this.levelNode;
  6468. if ( levelNode === null && builder.context.getTextureLevel ) {
  6469. levelNode = builder.context.getTextureLevel( this );
  6470. }
  6471. //
  6472. properties.uvNode = uvNode;
  6473. properties.levelNode = levelNode;
  6474. properties.biasNode = this.biasNode;
  6475. properties.compareNode = this.compareNode;
  6476. properties.gradNode = this.gradNode;
  6477. properties.depthNode = this.depthNode;
  6478. }
  6479. /**
  6480. * Generates the uv code snippet.
  6481. *
  6482. * @param {NodeBuilder} builder - The current node builder.
  6483. * @param {Node} uvNode - The uv node to generate code for.
  6484. * @return {String} The generated code snippet.
  6485. */
  6486. generateUV( builder, uvNode ) {
  6487. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  6488. }
  6489. /**
  6490. * Generates the snippet for the texture sampling.
  6491. *
  6492. * @param {NodeBuilder} builder - The current node builder.
  6493. * @param {String} textureProperty - The texture property.
  6494. * @param {String} uvSnippet - The uv snippet.
  6495. * @param {String} levelSnippet - The level snippet.
  6496. * @param {String} biasSnippet - The bias snippet.
  6497. * @param {String} depthSnippet - The depth snippet.
  6498. * @param {String} compareSnippet - The compare snippet.
  6499. * @param {String} gradSnippet - The grad snippet.
  6500. * @return {String} The generated code snippet.
  6501. */
  6502. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  6503. const texture = this.value;
  6504. let snippet;
  6505. if ( levelSnippet ) {
  6506. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  6507. } else if ( biasSnippet ) {
  6508. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  6509. } else if ( gradSnippet ) {
  6510. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  6511. } else if ( compareSnippet ) {
  6512. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  6513. } else if ( this.sampler === false ) {
  6514. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  6515. } else {
  6516. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  6517. }
  6518. return snippet;
  6519. }
  6520. /**
  6521. * Generates the code snippet of the texture node.
  6522. *
  6523. * @param {NodeBuilder} builder - The current node builder.
  6524. * @param {String} output - The current output.
  6525. * @return {String} The generated code snippet.
  6526. */
  6527. generate( builder, output ) {
  6528. const texture = this.value;
  6529. const properties = builder.getNodeProperties( this );
  6530. const textureProperty = super.generate( builder, 'property' );
  6531. if ( output === 'sampler' ) {
  6532. return textureProperty + '_sampler';
  6533. } else if ( builder.isReference( output ) ) {
  6534. return textureProperty;
  6535. } else {
  6536. const nodeData = builder.getDataFromNode( this );
  6537. let propertyName = nodeData.propertyName;
  6538. if ( propertyName === undefined ) {
  6539. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  6540. const uvSnippet = this.generateUV( builder, uvNode );
  6541. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  6542. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  6543. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  6544. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  6545. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  6546. const nodeVar = builder.getVarFromNode( this );
  6547. propertyName = builder.getPropertyName( nodeVar );
  6548. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  6549. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  6550. nodeData.snippet = snippet;
  6551. nodeData.propertyName = propertyName;
  6552. }
  6553. let snippet = propertyName;
  6554. const nodeType = this.getNodeType( builder );
  6555. if ( builder.needsToWorkingColorSpace( texture ) ) {
  6556. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  6557. }
  6558. return builder.format( snippet, nodeType, output );
  6559. }
  6560. }
  6561. /**
  6562. * Sets the sampler value.
  6563. *
  6564. * @param {Boolean} value - The sampler value to set.
  6565. * @return {TextureNode} A reference to this texture node.
  6566. */
  6567. setSampler( value ) {
  6568. this.sampler = value;
  6569. return this;
  6570. }
  6571. /**
  6572. * Returns the sampler value.
  6573. *
  6574. * @return {Boolean} The sampler value.
  6575. */
  6576. getSampler() {
  6577. return this.sampler;
  6578. }
  6579. // @TODO: Move to TSL
  6580. uv( uvNode ) { // @deprecated, r172
  6581. console.warn( 'THREE.TextureNode: .uv() has been renamed. Use .sample() instead.' );
  6582. return this.sample( uvNode );
  6583. }
  6584. /**
  6585. * Samples the texture with the given uv node.
  6586. *
  6587. * @param {Node} uvNode - The uv node.
  6588. * @return {TextureNode} A texture node representing the texture sample.
  6589. */
  6590. sample( uvNode ) {
  6591. const textureNode = this.clone();
  6592. textureNode.uvNode = nodeObject( uvNode );
  6593. textureNode.referenceNode = this.getSelf();
  6594. return nodeObject( textureNode );
  6595. }
  6596. /**
  6597. * Samples a blurred version of the texture by defining an internal bias.
  6598. *
  6599. * @param {Node<float>} amountNode - How blurred the texture should be.
  6600. * @return {TextureNode} A texture node representing the texture sample.
  6601. */
  6602. blur( amountNode ) {
  6603. const textureNode = this.clone();
  6604. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  6605. textureNode.referenceNode = this.getSelf();
  6606. return nodeObject( textureNode );
  6607. }
  6608. /**
  6609. * Samples a specific mip of the texture.
  6610. *
  6611. * @param {Node<int>} levelNode - The mip level to sample.
  6612. * @return {TextureNode} A texture node representing the texture sample.
  6613. */
  6614. level( levelNode ) {
  6615. const textureNode = this.clone();
  6616. textureNode.levelNode = nodeObject( levelNode );
  6617. textureNode.referenceNode = this.getSelf();
  6618. return nodeObject( textureNode );
  6619. }
  6620. /**
  6621. * Returns the texture size of the requested level.
  6622. *
  6623. * @param {Node<int>} levelNode - The level to compute the size for.
  6624. * @return {TextureSizeNode} The texture size.
  6625. */
  6626. size( levelNode ) {
  6627. return textureSize( this, levelNode );
  6628. }
  6629. /**
  6630. * Samples the texture with the given bias.
  6631. *
  6632. * @param {Node<float>} biasNode - The bias node.
  6633. * @return {TextureNode} A texture node representing the texture sample.
  6634. */
  6635. bias( biasNode ) {
  6636. const textureNode = this.clone();
  6637. textureNode.biasNode = nodeObject( biasNode );
  6638. textureNode.referenceNode = this.getSelf();
  6639. return nodeObject( textureNode );
  6640. }
  6641. /**
  6642. * Samples the texture by executing a compare operation.
  6643. *
  6644. * @param {Node<float>} compareNode - The node that defines the compare value.
  6645. * @return {TextureNode} A texture node representing the texture sample.
  6646. */
  6647. compare( compareNode ) {
  6648. const textureNode = this.clone();
  6649. textureNode.compareNode = nodeObject( compareNode );
  6650. textureNode.referenceNode = this.getSelf();
  6651. return nodeObject( textureNode );
  6652. }
  6653. /**
  6654. * Samples the texture using an explicit gradient.
  6655. *
  6656. * @param {Node<vec2>} gradNodeX - The gradX node.
  6657. * @param {Node<vec2>} gradNodeY - The gradY node.
  6658. * @return {TextureNode} A texture node representing the texture sample.
  6659. */
  6660. grad( gradNodeX, gradNodeY ) {
  6661. const textureNode = this.clone();
  6662. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  6663. textureNode.referenceNode = this.getSelf();
  6664. return nodeObject( textureNode );
  6665. }
  6666. /**
  6667. * Samples the texture by defining a depth node.
  6668. *
  6669. * @param {Node<int>} depthNode - The depth node.
  6670. * @return {TextureNode} A texture node representing the texture sample.
  6671. */
  6672. depth( depthNode ) {
  6673. const textureNode = this.clone();
  6674. textureNode.depthNode = nodeObject( depthNode );
  6675. textureNode.referenceNode = this.getSelf();
  6676. return nodeObject( textureNode );
  6677. }
  6678. // --
  6679. serialize( data ) {
  6680. super.serialize( data );
  6681. data.value = this.value.toJSON( data.meta ).uuid;
  6682. data.sampler = this.sampler;
  6683. data.updateMatrix = this.updateMatrix;
  6684. data.updateType = this.updateType;
  6685. }
  6686. deserialize( data ) {
  6687. super.deserialize( data );
  6688. this.value = data.meta.textures[ data.value ];
  6689. this.sampler = data.sampler;
  6690. this.updateMatrix = data.updateMatrix;
  6691. this.updateType = data.updateType;
  6692. }
  6693. /**
  6694. * The update is used to implement the update of the uv transformation matrix.
  6695. */
  6696. update() {
  6697. const texture = this.value;
  6698. const matrixUniform = this._matrixUniform;
  6699. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  6700. if ( texture.matrixAutoUpdate === true ) {
  6701. texture.updateMatrix();
  6702. }
  6703. }
  6704. /**
  6705. * Clones the texture node.
  6706. *
  6707. * @return {TextureNode} The cloned texture node.
  6708. */
  6709. clone() {
  6710. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  6711. newNode.sampler = this.sampler;
  6712. return newNode;
  6713. }
  6714. }
  6715. /**
  6716. * TSL function for creating a texture node.
  6717. *
  6718. * @function
  6719. * @param {Texture} value - The texture.
  6720. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  6721. * @param {Node<int>?} [levelNode=null] - The level node.
  6722. * @param {Node<float>?} [biasNode=null] - The bias node.
  6723. * @returns {TextureNode}
  6724. */
  6725. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  6726. /**
  6727. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  6728. *
  6729. * @function
  6730. * @param {Texture} value - The texture.
  6731. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  6732. * @param {Node<int>?} [levelNode=null] - The level node.
  6733. * @param {Node<float>?} [biasNode=null] - The bias node.
  6734. * @returns {TextureNode}
  6735. */
  6736. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  6737. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  6738. /**
  6739. * Converts a texture or texture node to a sampler.
  6740. *
  6741. * @function
  6742. * @param {TextureNode|Texture} aTexture - The texture or texture node to convert.
  6743. * @returns {Node}
  6744. */
  6745. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  6746. /** @module Camera **/
  6747. /**
  6748. * TSL object that represents the `near` value of the camera used for the current render.
  6749. *
  6750. * @type {UniformNode<float>}
  6751. */
  6752. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  6753. /**
  6754. * TSL object that represents the `far` value of the camera used for the current render.
  6755. *
  6756. * @type {UniformNode<float>}
  6757. */
  6758. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  6759. /**
  6760. * TSL object that represents the projection matrix of the camera used for the current render.
  6761. *
  6762. * @type {UniformNode<mat4>}
  6763. */
  6764. const cameraProjectionMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  6765. /**
  6766. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  6767. *
  6768. * @type {UniformNode<mat4>}
  6769. */
  6770. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  6771. /**
  6772. * TSL object that represents the view matrix of the camera used for the current render.
  6773. *
  6774. * @type {UniformNode<mat4>}
  6775. */
  6776. const cameraViewMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  6777. /**
  6778. * TSL object that represents the world matrix of the camera used for the current render.
  6779. *
  6780. * @type {UniformNode<mat4>}
  6781. */
  6782. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  6783. /**
  6784. * TSL object that represents the normal matrix of the camera used for the current render.
  6785. *
  6786. * @type {UniformNode<mat3>}
  6787. */
  6788. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  6789. /**
  6790. * TSL object that represents the position in world space of the camera used for the current render.
  6791. *
  6792. * @type {UniformNode<vec3>}
  6793. */
  6794. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  6795. /** @module Object3DNode **/
  6796. /**
  6797. * This node can be used to access transformation related metrics of 3D objects.
  6798. * Depending on the selected scope, a different metric is represented as a uniform
  6799. * in the shader. The following scopes are supported:
  6800. *
  6801. * - `POSITION`: The object's position in world space.
  6802. * - `VIEW_POSITION`: The object's position in view/camera space.
  6803. * - `DIRECTION`: The object's direction in world space.
  6804. * - `SCALE`: The object's scale in world space.
  6805. * - `WORLD_MATRIX`: The object's matrix in world space.
  6806. *
  6807. * @augments Node
  6808. */
  6809. class Object3DNode extends Node {
  6810. static get type() {
  6811. return 'Object3DNode';
  6812. }
  6813. /**
  6814. * Constructs a new object 3D node.
  6815. *
  6816. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  6817. * @param {Object3D?} [object3d=null] - The 3D object.
  6818. */
  6819. constructor( scope, object3d = null ) {
  6820. super();
  6821. /**
  6822. * The node reports a different type of transformation depending on the scope.
  6823. *
  6824. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  6825. */
  6826. this.scope = scope;
  6827. /**
  6828. * The 3D object.
  6829. *
  6830. * @type {Object3D?}
  6831. * @default null
  6832. */
  6833. this.object3d = object3d;
  6834. /**
  6835. * Overwritten since this type of node is updated per object.
  6836. *
  6837. * @type {String}
  6838. * @default 'object'
  6839. */
  6840. this.updateType = NodeUpdateType.OBJECT;
  6841. /**
  6842. * Holds the value of the node as a uniform.
  6843. *
  6844. * @private
  6845. * @type {UniformNode}
  6846. */
  6847. this._uniformNode = new UniformNode( null );
  6848. }
  6849. /**
  6850. * Overwritten since the node type is inferred from the scope.
  6851. *
  6852. * @param {NodeBuilder} builder - The current node builder.
  6853. * @return {String} The node type.
  6854. */
  6855. getNodeType() {
  6856. const scope = this.scope;
  6857. if ( scope === Object3DNode.WORLD_MATRIX ) {
  6858. return 'mat4';
  6859. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  6860. return 'vec3';
  6861. }
  6862. }
  6863. /**
  6864. * Updates the uniform value depending on the scope.
  6865. *
  6866. * @param {NodeFrame} frame - The current node frame.
  6867. */
  6868. update( frame ) {
  6869. const object = this.object3d;
  6870. const uniformNode = this._uniformNode;
  6871. const scope = this.scope;
  6872. if ( scope === Object3DNode.WORLD_MATRIX ) {
  6873. uniformNode.value = object.matrixWorld;
  6874. } else if ( scope === Object3DNode.POSITION ) {
  6875. uniformNode.value = uniformNode.value || new Vector3();
  6876. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  6877. } else if ( scope === Object3DNode.SCALE ) {
  6878. uniformNode.value = uniformNode.value || new Vector3();
  6879. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  6880. } else if ( scope === Object3DNode.DIRECTION ) {
  6881. uniformNode.value = uniformNode.value || new Vector3();
  6882. object.getWorldDirection( uniformNode.value );
  6883. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  6884. const camera = frame.camera;
  6885. uniformNode.value = uniformNode.value || new Vector3();
  6886. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  6887. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  6888. }
  6889. }
  6890. /**
  6891. * Generates the code snippet of the uniform node. The node type of the uniform
  6892. * node also depends on the selected scope.
  6893. *
  6894. * @param {NodeBuilder} builder - The current node builder.
  6895. * @return {String} The generated code snippet.
  6896. */
  6897. generate( builder ) {
  6898. const scope = this.scope;
  6899. if ( scope === Object3DNode.WORLD_MATRIX ) {
  6900. this._uniformNode.nodeType = 'mat4';
  6901. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  6902. this._uniformNode.nodeType = 'vec3';
  6903. }
  6904. return this._uniformNode.build( builder );
  6905. }
  6906. serialize( data ) {
  6907. super.serialize( data );
  6908. data.scope = this.scope;
  6909. }
  6910. deserialize( data ) {
  6911. super.deserialize( data );
  6912. this.scope = data.scope;
  6913. }
  6914. }
  6915. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  6916. Object3DNode.POSITION = 'position';
  6917. Object3DNode.SCALE = 'scale';
  6918. Object3DNode.VIEW_POSITION = 'viewPosition';
  6919. Object3DNode.DIRECTION = 'direction';
  6920. /**
  6921. * TSL function for creating an object 3D node that represents the object's direction in world space.
  6922. *
  6923. * @function
  6924. * @param {Object3D?} [object3d=null] - The 3D object.
  6925. * @returns {Object3DNode<vec3>}
  6926. */
  6927. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  6928. /**
  6929. * TSL function for creating an object 3D node that represents the object's world matrix.
  6930. *
  6931. * @function
  6932. * @param {Object3D?} [object3d=null] - The 3D object.
  6933. * @returns {Object3DNode<mat4>}
  6934. */
  6935. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  6936. /**
  6937. * TSL function for creating an object 3D node that represents the object's position in world space.
  6938. *
  6939. * @function
  6940. * @param {Object3D?} [object3d=null] - The 3D object.
  6941. * @returns {Object3DNode<vec3>}
  6942. */
  6943. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  6944. /**
  6945. * TSL function for creating an object 3D node that represents the object's scale in world space.
  6946. *
  6947. * @function
  6948. * @param {Object3D?} [object3d=null] - The 3D object.
  6949. * @returns {Object3DNode<vec3>}
  6950. */
  6951. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  6952. /**
  6953. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  6954. *
  6955. * @function
  6956. * @param {Object3D?} [object3d=null] - The 3D object.
  6957. * @returns {Object3DNode<vec3>}
  6958. */
  6959. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  6960. /** @module ModelNode **/
  6961. /**
  6962. * This type of node is a specialized version of `Object3DNode`
  6963. * with larger set of model related metrics. Unlike `Object3DNode`,
  6964. * `ModelNode` extracts the reference to the 3D object from the
  6965. * current node frame state.
  6966. *
  6967. * @augments module:Object3DNode~Object3DNode
  6968. */
  6969. class ModelNode extends Object3DNode {
  6970. static get type() {
  6971. return 'ModelNode';
  6972. }
  6973. /**
  6974. * Constructs a new object model node.
  6975. *
  6976. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  6977. */
  6978. constructor( scope ) {
  6979. super( scope );
  6980. }
  6981. /**
  6982. * Extracts the model reference from the frame state and then
  6983. * updates the uniform value depending on the scope.
  6984. *
  6985. * @param {NodeFrame} frame - The current node frame.
  6986. */
  6987. update( frame ) {
  6988. this.object3d = frame.object;
  6989. super.update( frame );
  6990. }
  6991. }
  6992. /**
  6993. * TSL object that represents the object's direction in world space.
  6994. *
  6995. * @type {ModelNode<vec3>}
  6996. */
  6997. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  6998. /**
  6999. * TSL object that represents the object's world matrix.
  7000. *
  7001. * @type {ModelNode<mat4>}
  7002. */
  7003. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  7004. /**
  7005. * TSL object that represents the object's position in world space.
  7006. *
  7007. * @type {ModelNode<vec3>}
  7008. */
  7009. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  7010. /**
  7011. * TSL object that represents the object's scale in world space.
  7012. *
  7013. * @type {ModelNode<vec3>}
  7014. */
  7015. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  7016. /**
  7017. * TSL object that represents the object's position in view/camera space.
  7018. *
  7019. * @type {ModelNode<vec3>}
  7020. */
  7021. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  7022. /**
  7023. * TSL object that represents the object's normal matrix.
  7024. *
  7025. * @type {UniformNode<mat3>}
  7026. */
  7027. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  7028. /**
  7029. * TSL object that represents the object's inverse world matrix.
  7030. *
  7031. * @type {UniformNode<mat4>}
  7032. */
  7033. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  7034. /**
  7035. * TSL object that represents the object's model view matrix.
  7036. *
  7037. * @type {Node<mat4>}
  7038. */
  7039. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7040. return builder.renderer.nodes.modelViewMatrix || mediumpModelViewMatrix;
  7041. } ).once() )().toVar( 'modelViewMatrix' );
  7042. // GPU Precision
  7043. /**
  7044. * TSL object that represents the object's model view in `mediump` precision.
  7045. *
  7046. * @type {Node<mat4>}
  7047. */
  7048. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  7049. // CPU Precision
  7050. /**
  7051. * TSL object that represents the object's model view in `highp` precision
  7052. * which is achieved by computing the matrix in JS and not in the shader.
  7053. *
  7054. * @type {Node<mat4>}
  7055. */
  7056. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7057. builder.context.isHighPrecisionModelViewMatrix = true;
  7058. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  7059. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  7060. } );
  7061. } ).once() )().toVar( 'highpModelViewMatrix' );
  7062. /**
  7063. * TSL object that represents the object's model normal view in `highp` precision
  7064. * which is achieved by computing the matrix in JS and not in the shader.
  7065. *
  7066. * @type {Node<mat3>}
  7067. */
  7068. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7069. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  7070. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  7071. if ( isHighPrecisionModelViewMatrix !== true ) {
  7072. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  7073. }
  7074. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  7075. } );
  7076. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  7077. /** @module Position **/
  7078. /**
  7079. * TSL object that represents the position attribute of the current rendered object.
  7080. *
  7081. * @type {AttributeNode<vec3>}
  7082. */
  7083. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  7084. /**
  7085. * TSL object that represents the vertex position in local space of the current rendered object.
  7086. *
  7087. * @type {AttributeNode<vec3>}
  7088. */
  7089. const positionLocal = /*@__PURE__*/ positionGeometry.varying( 'positionLocal' );
  7090. /**
  7091. * TSL object that represents the previous vertex position in local space of the current rendered object.
  7092. * Used in context of {@link module:VelocityNode~VelocityNode} for rendering motion vectors.
  7093. *
  7094. * @type {AttributeNode<vec3>}
  7095. */
  7096. const positionPrevious = /*@__PURE__*/ positionGeometry.varying( 'positionPrevious' );
  7097. /**
  7098. * TSL object that represents the vertex position in world space of the current rendered object.
  7099. *
  7100. * @type {VaryingNode<vec3>}
  7101. */
  7102. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.varying( 'v_positionWorld' ).context( { needsPositionReassign: true } );
  7103. /**
  7104. * TSL object that represents the position world direction of the current rendered object.
  7105. *
  7106. * @type {Node<vec3>}
  7107. */
  7108. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).varying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' ).context( { needsPositionReassign: true } );
  7109. /**
  7110. * TSL object that represents the vertex position in view space of the current rendered object.
  7111. *
  7112. * @type {VaryingNode<vec3>}
  7113. */
  7114. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7115. return builder.context.setupPositionView();
  7116. }, 'vec3' ).once() )().varying( 'v_positionView' ).context( { needsPositionReassign: true } );
  7117. /**
  7118. * TSL object that represents the position view direction of the current rendered object.
  7119. *
  7120. * @type {VaryingNode<vec3>}
  7121. */
  7122. const positionViewDirection = /*@__PURE__*/ positionView.negate().varying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  7123. /** @module FrontFacingNode **/
  7124. /**
  7125. * This node can be used to evaluate whether a primitive is front or back facing.
  7126. *
  7127. * @augments Node
  7128. */
  7129. class FrontFacingNode extends Node {
  7130. static get type() {
  7131. return 'FrontFacingNode';
  7132. }
  7133. /**
  7134. * Constructs a new front facing node.
  7135. */
  7136. constructor() {
  7137. super( 'bool' );
  7138. /**
  7139. * This flag can be used for type testing.
  7140. *
  7141. * @type {Boolean}
  7142. * @readonly
  7143. * @default true
  7144. */
  7145. this.isFrontFacingNode = true;
  7146. }
  7147. generate( builder ) {
  7148. const { renderer, material } = builder;
  7149. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  7150. if ( material.side === BackSide ) {
  7151. return 'false';
  7152. }
  7153. }
  7154. return builder.getFrontFacing();
  7155. }
  7156. }
  7157. /**
  7158. * TSL object that represents whether a primitive is front or back facing
  7159. *
  7160. * @type {FrontFacingNode<bool>}
  7161. */
  7162. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  7163. /**
  7164. * TSL object that represents the front facing status as a number instead of a bool.
  7165. * `1` means front facing, `-1` means back facing.
  7166. *
  7167. * @type {Node<float>}
  7168. */
  7169. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  7170. /** @module Normal **/
  7171. /**
  7172. * TSL object that represents the normal attribute of the current rendered object.
  7173. *
  7174. * @type {Node<vec3>}
  7175. */
  7176. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  7177. /**
  7178. * TSL object that represents the vertex normal in local space of the current rendered object.
  7179. *
  7180. * @type {Node<vec3>}
  7181. */
  7182. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  7183. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  7184. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  7185. return vec3( 0, 1, 0 );
  7186. }
  7187. return normalGeometry;
  7188. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  7189. /**
  7190. * TSL object that represents the flat vertex normal in view space of the current rendered object.
  7191. *
  7192. * @type {Node<vec3>}
  7193. */
  7194. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  7195. /**
  7196. * TSL object that represents the vertex normal in view space of the current rendered object.
  7197. *
  7198. * @type {Node<vec3>}
  7199. */
  7200. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7201. let node;
  7202. if ( builder.material.flatShading === true ) {
  7203. node = normalFlat;
  7204. } else {
  7205. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  7206. }
  7207. return node;
  7208. }, 'vec3' ).once() )().toVar( 'normalView' );
  7209. /**
  7210. * TSL object that represents the vertex normal in world space of the current rendered object.
  7211. *
  7212. * @type {Node<vec3>}
  7213. */
  7214. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  7215. /**
  7216. * TSL object that represents the transformed vertex normal in view space of the current rendered object.
  7217. *
  7218. * @type {Node<vec3>}
  7219. */
  7220. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7221. return builder.context.setupNormal();
  7222. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  7223. /**
  7224. * TSL object that represents the transformed vertex normal in world space of the current rendered object.
  7225. *
  7226. * @type {Node<vec3>}
  7227. */
  7228. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  7229. /**
  7230. * TSL object that represents the transformed clearcoat vertex normal in view space of the current rendered object.
  7231. *
  7232. * @type {Node<vec3>}
  7233. */
  7234. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7235. return builder.context.setupClearcoatNormal();
  7236. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  7237. /**
  7238. * Transforms the normal with the given matrix.
  7239. *
  7240. * @function
  7241. * @param {Node<vec3>} normal - The normal.
  7242. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  7243. * @return {Node<vec3>} The transformed normal.
  7244. */
  7245. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  7246. const m = mat3( matrix );
  7247. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  7248. return m.mul( transformedNormal ).xyz;
  7249. } );
  7250. /**
  7251. * Transforms the given normal from local to view space.
  7252. *
  7253. * @function
  7254. * @param {Node<vec3>} normal - The normal.
  7255. * @param {NodeBuilder} builder - The current node builder.
  7256. * @return {Node<vec3>} The transformed normal.
  7257. */
  7258. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  7259. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  7260. if ( modelNormalViewMatrix !== null ) {
  7261. return modelNormalViewMatrix.transformDirection( normal );
  7262. }
  7263. //
  7264. const transformedNormal = modelNormalMatrix.mul( normal );
  7265. return cameraViewMatrix.transformDirection( transformedNormal );
  7266. } );
  7267. /** @module MaterialProperties **/
  7268. /**
  7269. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  7270. *
  7271. * @type {UniformNode<float>}
  7272. */
  7273. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  7274. /** @module ReflectVector **/
  7275. /**
  7276. * The reflect vector in view space.
  7277. *
  7278. * @type {Node<vec3>}
  7279. */
  7280. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  7281. /**
  7282. * The refract vector in view space.
  7283. *
  7284. * @type {Node<vec3>}
  7285. */
  7286. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  7287. /**
  7288. * Used for sampling cube maps when using cube reflection mapping.
  7289. *
  7290. * @type {Node<vec3>}
  7291. */
  7292. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  7293. /**
  7294. * Used for sampling cube maps when using cube refraction mapping.
  7295. *
  7296. * @type {Node<vec3>}
  7297. */
  7298. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  7299. /** @module CubeTextureNode **/
  7300. /**
  7301. * This type of uniform node represents a cube texture.
  7302. *
  7303. * @augments module:TextureNode~TextureNode
  7304. */
  7305. class CubeTextureNode extends TextureNode {
  7306. static get type() {
  7307. return 'CubeTextureNode';
  7308. }
  7309. /**
  7310. * Constructs a new cube texture node.
  7311. *
  7312. * @param {CubeTexture} value - The cube texture.
  7313. * @param {Node<vec3>?} [uvNode=null] - The uv node.
  7314. * @param {Node<int>?} [levelNode=null] - The level node.
  7315. * @param {Node<float>?} [biasNode=null] - The bias node.
  7316. */
  7317. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  7318. super( value, uvNode, levelNode, biasNode );
  7319. /**
  7320. * This flag can be used for type testing.
  7321. *
  7322. * @type {Boolean}
  7323. * @readonly
  7324. * @default true
  7325. */
  7326. this.isCubeTextureNode = true;
  7327. }
  7328. /**
  7329. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  7330. *
  7331. * @param {NodeBuilder} builder - The current node builder.
  7332. * @return {String} The input type.
  7333. */
  7334. getInputType( /*builder*/ ) {
  7335. return 'cubeTexture';
  7336. }
  7337. /**
  7338. * Returns a default uvs based on the mapping type of the cube texture.
  7339. *
  7340. * @return {Node<vec3>} The default uv attribute.
  7341. */
  7342. getDefaultUV() {
  7343. const texture = this.value;
  7344. if ( texture.mapping === CubeReflectionMapping ) {
  7345. return reflectVector;
  7346. } else if ( texture.mapping === CubeRefractionMapping ) {
  7347. return refractVector;
  7348. } else {
  7349. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  7350. return vec3( 0, 0, 0 );
  7351. }
  7352. }
  7353. /**
  7354. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  7355. * for cube textures. The uv transformation matrix is not applied to cube textures.
  7356. *
  7357. * @param {Boolean} value - The update toggle.
  7358. */
  7359. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  7360. /**
  7361. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  7362. * to modify the uv node for correct sampling.
  7363. *
  7364. * @param {NodeBuilder} builder - The current node builder.
  7365. * @param {Node} uvNode - The uv node to setup.
  7366. * @return {Node} The updated uv node.
  7367. */
  7368. setupUV( builder, uvNode ) {
  7369. const texture = this.value;
  7370. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  7371. return vec3( uvNode.x.negate(), uvNode.yz );
  7372. } else {
  7373. return uvNode;
  7374. }
  7375. }
  7376. /**
  7377. * Generates the uv code snippet.
  7378. *
  7379. * @param {NodeBuilder} builder - The current node builder.
  7380. * @param {Node} cubeUV - The uv node to generate code for.
  7381. * @return {String} The generated code snippet.
  7382. */
  7383. generateUV( builder, cubeUV ) {
  7384. return cubeUV.build( builder, 'vec3' );
  7385. }
  7386. }
  7387. /**
  7388. * TSL function for creating a cube texture node.
  7389. *
  7390. * @function
  7391. * @param {CubeTexture} value - The cube texture.
  7392. * @param {Node<vec3>?} [uvNode=null] - The uv node.
  7393. * @param {Node<int>?} [levelNode=null] - The level node.
  7394. * @param {Node<float>?} [biasNode=null] - The bias node.
  7395. * @returns {CubeTextureNode}
  7396. */
  7397. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  7398. /** @module BufferNode **/
  7399. /**
  7400. * A special type of uniform node which represents array-like data
  7401. * as uniform buffers. The access usually happens via `element()`
  7402. * which returns an instance of {@link ArrayElementNode}. For example:
  7403. *
  7404. * ```js
  7405. * const bufferNode = buffer( array, 'mat4', count );
  7406. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  7407. * ```
  7408. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  7409. * since it handles more input types and automatically cares about buffer paddings.
  7410. *
  7411. * @augments module:UniformNode~UniformNode
  7412. */
  7413. class BufferNode extends UniformNode {
  7414. static get type() {
  7415. return 'BufferNode';
  7416. }
  7417. /**
  7418. * Constructs a new buffer node.
  7419. *
  7420. * @param {Array<Number>} value - Array-like buffer data.
  7421. * @param {String} bufferType - The data type of the buffer.
  7422. * @param {Number} [bufferCount=0] - The count of buffer elements.
  7423. */
  7424. constructor( value, bufferType, bufferCount = 0 ) {
  7425. super( value, bufferType );
  7426. /**
  7427. * This flag can be used for type testing.
  7428. *
  7429. * @type {Boolean}
  7430. * @readonly
  7431. * @default true
  7432. */
  7433. this.isBufferNode = true;
  7434. /**
  7435. * The data type of the buffer.
  7436. *
  7437. * @type {String}
  7438. */
  7439. this.bufferType = bufferType;
  7440. /**
  7441. * The uniform node that holds the value of the reference node.
  7442. *
  7443. * @type {Number}
  7444. * @default 0
  7445. */
  7446. this.bufferCount = bufferCount;
  7447. }
  7448. /**
  7449. * The data type of the buffer elements.
  7450. *
  7451. * @param {NodeBuilder} builder - The current node builder.
  7452. * @return {String} The element type.
  7453. */
  7454. getElementType( builder ) {
  7455. return this.getNodeType( builder );
  7456. }
  7457. /**
  7458. * Overwrites the default implementation to return a fixed value `'buffer'`.
  7459. *
  7460. * @param {NodeBuilder} builder - The current node builder.
  7461. * @return {String} The input type.
  7462. */
  7463. getInputType( /*builder*/ ) {
  7464. return 'buffer';
  7465. }
  7466. }
  7467. /**
  7468. * TSL function for creating a buffer node.
  7469. *
  7470. * @function
  7471. * @param {Array} value - Array-like buffer data.
  7472. * @param {String} type - The data type of a buffer element.
  7473. * @param {Number} count - The count of buffer elements.
  7474. * @returns {BufferNode}
  7475. */
  7476. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  7477. /** @module UniformArrayNode **/
  7478. /**
  7479. * Represents the element access on uniform array nodes.
  7480. *
  7481. * @augments ArrayElementNode
  7482. */
  7483. class UniformArrayElementNode extends ArrayElementNode {
  7484. static get type() {
  7485. return 'UniformArrayElementNode';
  7486. }
  7487. /**
  7488. * Constructs a new buffer node.
  7489. *
  7490. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  7491. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  7492. */
  7493. constructor( uniformArrayNode, indexNode ) {
  7494. super( uniformArrayNode, indexNode );
  7495. /**
  7496. * This flag can be used for type testing.
  7497. *
  7498. * @type {Boolean}
  7499. * @readonly
  7500. * @default true
  7501. */
  7502. this.isArrayBufferElementNode = true;
  7503. }
  7504. generate( builder ) {
  7505. const snippet = super.generate( builder );
  7506. const type = this.getNodeType();
  7507. const paddedType = this.node.getPaddedType();
  7508. return builder.format( snippet, paddedType, type );
  7509. }
  7510. }
  7511. /**
  7512. * Similar to {@link module:BufferNode~BufferNode} this module represents array-like data as
  7513. * uniform buffers. Unlike {@link module:BufferNode~BufferNode}, it can handle more common
  7514. * data types in the array (e.g `three.js` primitives) and automatically
  7515. * manage buffer padding. It should be the first choice when working with
  7516. * uniforms buffers.
  7517. * ```js
  7518. * const tintColors = uniformArray( [
  7519. * new Color( 1, 0, 0 ),
  7520. * new Color( 0, 1, 0 ),
  7521. * new Color( 0, 0, 1 )
  7522. * ], 'color' );
  7523. *
  7524. * const redColor = tintColors.element( 0 );
  7525. *
  7526. * @augments module:BufferNode~BufferNode
  7527. */
  7528. class UniformArrayNode extends BufferNode {
  7529. static get type() {
  7530. return 'UniformArrayNode';
  7531. }
  7532. /**
  7533. * Constructs a new uniform array node.
  7534. *
  7535. * @param {Array<Any>} value - Array holding the buffer data.
  7536. * @param {String?} [elementType=null] - The data type of a buffer element.
  7537. */
  7538. constructor( value, elementType = null ) {
  7539. super( null );
  7540. /**
  7541. * Array holding the buffer data. Unlike {@link module:BufferNode~BufferNode}, the array can
  7542. * hold number primitives as well as three.js objects like vectors, matrices
  7543. * or colors.
  7544. *
  7545. * @type {Array<Any>}
  7546. */
  7547. this.array = value;
  7548. /**
  7549. * The data type of an array element.
  7550. *
  7551. * @type {String}
  7552. */
  7553. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  7554. /**
  7555. * The padded type. Uniform buffers must conform to a certain buffer layout
  7556. * so a separate type is computed to ensure correct buffer size.
  7557. *
  7558. * @type {String}
  7559. */
  7560. this.paddedType = this.getPaddedType();
  7561. /**
  7562. * Overwritten since uniform array nodes are updated per render.
  7563. *
  7564. * @type {String}
  7565. * @default 'render'
  7566. */
  7567. this.updateType = NodeUpdateType.RENDER;
  7568. /**
  7569. * This flag can be used for type testing.
  7570. *
  7571. * @type {Boolean}
  7572. * @readonly
  7573. * @default true
  7574. */
  7575. this.isArrayBufferNode = true;
  7576. }
  7577. /**
  7578. * This method is overwritten since the node type is inferred from the
  7579. * {@link module:UniformArrayNode~UniformArrayNode#paddedType}.
  7580. *
  7581. * @param {NodeBuilder} builder - The current node builder.
  7582. * @return {String} The node type.
  7583. */
  7584. getNodeType( /*builder*/ ) {
  7585. return this.paddedType;
  7586. }
  7587. /**
  7588. * The data type of the array elements.
  7589. *
  7590. * @param {NodeBuilder} builder - The current node builder.
  7591. * @return {String} The element type.
  7592. */
  7593. getElementType() {
  7594. return this.elementType;
  7595. }
  7596. /**
  7597. * Returns the padded type based on the element type.
  7598. *
  7599. * @return {String} The padded type.
  7600. */
  7601. getPaddedType() {
  7602. const elementType = this.elementType;
  7603. let paddedType = 'vec4';
  7604. if ( elementType === 'mat2' ) {
  7605. paddedType = 'mat2';
  7606. } else if ( /mat/.test( elementType ) === true ) {
  7607. paddedType = 'mat4';
  7608. } else if ( elementType.charAt( 0 ) === 'i' ) {
  7609. paddedType = 'ivec4';
  7610. } else if ( elementType.charAt( 0 ) === 'u' ) {
  7611. paddedType = 'uvec4';
  7612. }
  7613. return paddedType;
  7614. }
  7615. /**
  7616. * The update makes sure to correctly transfer the data from the (complex) objects
  7617. * in the array to the internal, correctly padded value buffer.
  7618. *
  7619. * @param {NodeFrame} frame - A reference to the current node frame.
  7620. */
  7621. update( /*frame*/ ) {
  7622. const { array, value } = this;
  7623. const elementType = this.elementType;
  7624. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  7625. for ( let i = 0; i < array.length; i ++ ) {
  7626. const index = i * 4;
  7627. value[ index ] = array[ i ];
  7628. }
  7629. } else if ( elementType === 'color' ) {
  7630. for ( let i = 0; i < array.length; i ++ ) {
  7631. const index = i * 4;
  7632. const vector = array[ i ];
  7633. value[ index ] = vector.r;
  7634. value[ index + 1 ] = vector.g;
  7635. value[ index + 2 ] = vector.b || 0;
  7636. //value[ index + 3 ] = vector.a || 0;
  7637. }
  7638. } else if ( elementType === 'mat2' ) {
  7639. for ( let i = 0; i < array.length; i ++ ) {
  7640. const index = i * 4;
  7641. const matrix = array[ i ];
  7642. value[ index ] = matrix.elements[ 0 ];
  7643. value[ index + 1 ] = matrix.elements[ 1 ];
  7644. value[ index + 2 ] = matrix.elements[ 2 ];
  7645. value[ index + 3 ] = matrix.elements[ 3 ];
  7646. }
  7647. } else if ( elementType === 'mat3' ) {
  7648. for ( let i = 0; i < array.length; i ++ ) {
  7649. const index = i * 16;
  7650. const matrix = array[ i ];
  7651. value[ index ] = matrix.elements[ 0 ];
  7652. value[ index + 1 ] = matrix.elements[ 1 ];
  7653. value[ index + 2 ] = matrix.elements[ 2 ];
  7654. value[ index + 4 ] = matrix.elements[ 3 ];
  7655. value[ index + 5 ] = matrix.elements[ 4 ];
  7656. value[ index + 6 ] = matrix.elements[ 5 ];
  7657. value[ index + 8 ] = matrix.elements[ 6 ];
  7658. value[ index + 9 ] = matrix.elements[ 7 ];
  7659. value[ index + 10 ] = matrix.elements[ 8 ];
  7660. value[ index + 15 ] = 1;
  7661. }
  7662. } else if ( elementType === 'mat4' ) {
  7663. for ( let i = 0; i < array.length; i ++ ) {
  7664. const index = i * 16;
  7665. const matrix = array[ i ];
  7666. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  7667. value[ index + i ] = matrix.elements[ i ];
  7668. }
  7669. }
  7670. } else {
  7671. for ( let i = 0; i < array.length; i ++ ) {
  7672. const index = i * 4;
  7673. const vector = array[ i ];
  7674. value[ index ] = vector.x;
  7675. value[ index + 1 ] = vector.y;
  7676. value[ index + 2 ] = vector.z || 0;
  7677. value[ index + 3 ] = vector.w || 0;
  7678. }
  7679. }
  7680. }
  7681. /**
  7682. * Implement the value buffer creation based on the array data.
  7683. *
  7684. * @param {NodeBuilder} builder - A reference to the current node builder.
  7685. * @return {null}
  7686. */
  7687. setup( builder ) {
  7688. const length = this.array.length;
  7689. const elementType = this.elementType;
  7690. let arrayType = Float32Array;
  7691. const paddedType = this.paddedType;
  7692. const paddedElementLength = builder.getTypeLength( paddedType );
  7693. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  7694. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  7695. this.value = new arrayType( length * paddedElementLength );
  7696. this.bufferCount = length;
  7697. this.bufferType = paddedType;
  7698. return super.setup( builder );
  7699. }
  7700. /**
  7701. * Overwrites the default `element()` method to provide element access
  7702. * based on {@link module:UniformArrayNode~UniformArrayNode}.
  7703. *
  7704. * @param {IndexNode} indexNode - The index node.
  7705. * @return {UniformArrayElementNode}
  7706. */
  7707. element( indexNode ) {
  7708. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  7709. }
  7710. }
  7711. /**
  7712. * TSL function for creating an uniform array node.
  7713. *
  7714. * @function
  7715. * @param {Array<Any>} values - Array-like data.
  7716. * @param {String} nodeType - The data type of the array elements.
  7717. * @returns {UniformArrayNode}
  7718. */
  7719. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  7720. //
  7721. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  7722. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  7723. return nodeObject( new UniformArrayNode( values, nodeType ) );
  7724. };
  7725. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  7726. /** @module ReferenceNode **/
  7727. /**
  7728. * This class is only relevant if the referenced property is array-like.
  7729. * In this case, `ReferenceElementNode` allows to refer to a specific
  7730. * element inside the data structure via an index.
  7731. *
  7732. * @augments ArrayElementNode
  7733. */
  7734. class ReferenceElementNode extends ArrayElementNode {
  7735. static get type() {
  7736. return 'ReferenceElementNode';
  7737. }
  7738. /**
  7739. * Constructs a new reference element node.
  7740. *
  7741. * @param {Node?} referenceNode - The reference node.
  7742. * @param {Node} indexNode - The index node that defines the element access.
  7743. */
  7744. constructor( referenceNode, indexNode ) {
  7745. super( referenceNode, indexNode );
  7746. /**
  7747. * Similar to {@link module:ReferenceNode~ReferenceNode#reference}, an additional
  7748. * property references to the current node.
  7749. *
  7750. * @type {Node?}
  7751. * @default null
  7752. */
  7753. this.referenceNode = referenceNode;
  7754. /**
  7755. * This flag can be used for type testing.
  7756. *
  7757. * @type {Boolean}
  7758. * @readonly
  7759. * @default true
  7760. */
  7761. this.isReferenceElementNode = true;
  7762. }
  7763. /**
  7764. * This method is overwritten since the node type is inferred from
  7765. * the uniform type of the reference node.
  7766. *
  7767. * @param {NodeBuilder} builder - The current node builder.
  7768. * @return {String} The node type.
  7769. */
  7770. getNodeType() {
  7771. return this.referenceNode.uniformType;
  7772. }
  7773. generate( builder ) {
  7774. const snippet = super.generate( builder );
  7775. const arrayType = this.referenceNode.getNodeType();
  7776. const elementType = this.getNodeType();
  7777. return builder.format( snippet, arrayType, elementType );
  7778. }
  7779. }
  7780. /**
  7781. * This type of node establishes a reference to a property of another object.
  7782. * In this way, the value of the node is automatically linked to the value of
  7783. * referenced object. Reference nodes internally represent the linked value
  7784. * as a uniform.
  7785. *
  7786. * @augments Node
  7787. */
  7788. class ReferenceNode extends Node {
  7789. static get type() {
  7790. return 'ReferenceNode';
  7791. }
  7792. /**
  7793. * Constructs a new reference node.
  7794. *
  7795. * @param {String} property - The name of the property the node refers to.
  7796. * @param {String} uniformType - The uniform type that should be used to represent the property value.
  7797. * @param {Object?} [object=null] - The object the property belongs to.
  7798. * @param {Number?} [count=null] - When the linked property is an array-like, this parameter defines its length.
  7799. */
  7800. constructor( property, uniformType, object = null, count = null ) {
  7801. super();
  7802. /**
  7803. * The name of the property the node refers to.
  7804. *
  7805. * @type {String}
  7806. */
  7807. this.property = property;
  7808. /**
  7809. * The uniform type that should be used to represent the property value.
  7810. *
  7811. * @type {String}
  7812. */
  7813. this.uniformType = uniformType;
  7814. /**
  7815. * The object the property belongs to.
  7816. *
  7817. * @type {Object?}
  7818. * @default null
  7819. */
  7820. this.object = object;
  7821. /**
  7822. * When the linked property is an array, this parameter defines its length.
  7823. *
  7824. * @type {Number?}
  7825. * @default null
  7826. */
  7827. this.count = count;
  7828. /**
  7829. * The property name might have dots so nested properties can be referred.
  7830. * The hierarchy of the names is stored inside this array.
  7831. *
  7832. * @type {Array<String>}
  7833. */
  7834. this.properties = property.split( '.' );
  7835. /**
  7836. * Points to the current referred object. This property exists next to {@link module:ReferenceNode~ReferenceNode#object}
  7837. * since the final reference might be updated from calling code.
  7838. *
  7839. * @type {Object?}
  7840. * @default null
  7841. */
  7842. this.reference = object;
  7843. /**
  7844. * The uniform node that holds the value of the reference node.
  7845. *
  7846. * @type {UniformNode}
  7847. * @default null
  7848. */
  7849. this.node = null;
  7850. /**
  7851. * The uniform group of the internal uniform.
  7852. *
  7853. * @type {UniformGroupNode}
  7854. * @default null
  7855. */
  7856. this.group = null;
  7857. /**
  7858. * An optional label of the internal uniform node.
  7859. *
  7860. * @type {String?}
  7861. * @default null
  7862. */
  7863. this.name = null;
  7864. /**
  7865. * Overwritten since reference nodes are updated per object.
  7866. *
  7867. * @type {String}
  7868. * @default 'object'
  7869. */
  7870. this.updateType = NodeUpdateType.OBJECT;
  7871. }
  7872. /**
  7873. * When the referred property is array-like, this method can be used
  7874. * to access elements via an index node.
  7875. *
  7876. * @param {IndexNode} indexNode - indexNode.
  7877. * @return {ReferenceElementNode} A reference to an element.
  7878. */
  7879. element( indexNode ) {
  7880. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  7881. }
  7882. /**
  7883. * Sets the uniform group for this reference node.
  7884. *
  7885. * @param {UniformGroupNode} group - The uniform group to set.
  7886. * @return {ReferenceNode} A reference to this node.
  7887. */
  7888. setGroup( group ) {
  7889. this.group = group;
  7890. return this;
  7891. }
  7892. /**
  7893. * Sets the label for the internal uniform.
  7894. *
  7895. * @param {String} name - The label to set.
  7896. * @return {ReferenceNode} A reference to this node.
  7897. */
  7898. label( name ) {
  7899. this.name = name;
  7900. return this;
  7901. }
  7902. /**
  7903. * Sets the node type which automatically defines the internal
  7904. * uniform type.
  7905. *
  7906. * @param {String} uniformType - The type to set.
  7907. */
  7908. setNodeType( uniformType ) {
  7909. let node = null;
  7910. if ( this.count !== null ) {
  7911. node = buffer( null, uniformType, this.count );
  7912. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  7913. node = uniformArray( null, uniformType );
  7914. } else if ( uniformType === 'texture' ) {
  7915. node = texture( null );
  7916. } else if ( uniformType === 'cubeTexture' ) {
  7917. node = cubeTexture( null );
  7918. } else {
  7919. node = uniform( null, uniformType );
  7920. }
  7921. if ( this.group !== null ) {
  7922. node.setGroup( this.group );
  7923. }
  7924. if ( this.name !== null ) node.label( this.name );
  7925. this.node = node.getSelf();
  7926. }
  7927. /**
  7928. * This method is overwritten since the node type is inferred from
  7929. * the type of the reference node.
  7930. *
  7931. * @param {NodeBuilder} builder - The current node builder.
  7932. * @return {String} The node type.
  7933. */
  7934. getNodeType( builder ) {
  7935. if ( this.node === null ) {
  7936. this.updateReference( builder );
  7937. this.updateValue();
  7938. }
  7939. return this.node.getNodeType( builder );
  7940. }
  7941. /**
  7942. * Returns the property value from the given referred object.
  7943. *
  7944. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  7945. * @return {Any} The value.
  7946. */
  7947. getValueFromReference( object = this.reference ) {
  7948. const { properties } = this;
  7949. let value = object[ properties[ 0 ] ];
  7950. for ( let i = 1; i < properties.length; i ++ ) {
  7951. value = value[ properties[ i ] ];
  7952. }
  7953. return value;
  7954. }
  7955. /**
  7956. * Allows to update the reference based on the given state. The state is only
  7957. * evaluated {@link module:ReferenceNode~ReferenceNode#object} is not set.
  7958. *
  7959. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  7960. * @return {Object} The updated reference.
  7961. */
  7962. updateReference( state ) {
  7963. this.reference = this.object !== null ? this.object : state.object;
  7964. return this.reference;
  7965. }
  7966. /**
  7967. * The output of the reference node is the internal uniform node.
  7968. *
  7969. * @param {NodeBuilder} builder - The current node builder.
  7970. * @return {UniformNode} The output node.
  7971. */
  7972. setup( /* builder */ ) {
  7973. this.updateValue();
  7974. return this.node;
  7975. }
  7976. /**
  7977. * Overwritten to to update the internal uniform value.
  7978. *
  7979. * @param {NodeFrame} frame - A reference to the current node frame.
  7980. */
  7981. update( /*frame*/ ) {
  7982. this.updateValue();
  7983. }
  7984. /**
  7985. * Retrieves the value from the referred object property and uses it
  7986. * to updated the internal uniform.
  7987. */
  7988. updateValue() {
  7989. if ( this.node === null ) this.setNodeType( this.uniformType );
  7990. const value = this.getValueFromReference();
  7991. if ( Array.isArray( value ) ) {
  7992. this.node.array = value;
  7993. } else {
  7994. this.node.value = value;
  7995. }
  7996. }
  7997. }
  7998. /**
  7999. * TSL function for creating a reference node.
  8000. *
  8001. * @function
  8002. * @param {String} name - The name of the property the node refers to.
  8003. * @param {String} type - The uniform type that should be used to represent the property value.
  8004. * @param {Object} object - The object the property belongs to.
  8005. * @returns {ReferenceNode}
  8006. */
  8007. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  8008. /**
  8009. * TSL function for creating a reference node. Use this function if you want need a reference
  8010. * to an array-like property that should be represented as a uniform buffer.
  8011. *
  8012. * @function
  8013. * @param {String} name - The name of the property the node refers to.
  8014. * @param {String} type - The uniform type that should be used to represent the property value.
  8015. * @param {Number} count - The number of value inside the array-like object.
  8016. * @param {Object} object - An array-like object the property belongs to.
  8017. * @returns {ReferenceNode}
  8018. */
  8019. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  8020. /** @module MaterialReferenceNode **/
  8021. /**
  8022. * This node is a special type of reference node which is intended
  8023. * for linking material properties with node values.
  8024. * ```js
  8025. * const opacityNode = materialReference( 'opacity', 'float', material );
  8026. * ```
  8027. * When changing `material.opacity`, the node value of `opacityNode` will
  8028. * automatically be updated.
  8029. *
  8030. * @augments module:ReferenceNode~ReferenceNode
  8031. */
  8032. class MaterialReferenceNode extends ReferenceNode {
  8033. static get type() {
  8034. return 'MaterialReferenceNode';
  8035. }
  8036. /**
  8037. * Constructs a new material reference node.
  8038. *
  8039. * @param {String} property - The name of the property the node refers to.
  8040. * @param {String} inputType - The uniform type that should be used to represent the property value.
  8041. * @param {Material?} [material=null] - The material the property belongs to. When no material is set,
  8042. * the node refers to the material of the current rendered object.
  8043. */
  8044. constructor( property, inputType, material = null ) {
  8045. super( property, inputType, material );
  8046. /**
  8047. * The material the property belongs to. When no material is set,
  8048. * the node refers to the material of the current rendered object.
  8049. *
  8050. * @type {Material?}
  8051. * @default null
  8052. */
  8053. this.material = material;
  8054. /**
  8055. * This flag can be used for type testing.
  8056. *
  8057. * @type {Boolean}
  8058. * @readonly
  8059. * @default true
  8060. */
  8061. this.isMaterialReferenceNode = true;
  8062. }
  8063. /**
  8064. * Updates the reference based on the given state. The state is only evaluated
  8065. * {@link module:MaterialReferenceNode~MaterialReferenceNode#material} is not set.
  8066. *
  8067. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  8068. * @return {Object} The updated reference.
  8069. */
  8070. updateReference( state ) {
  8071. this.reference = this.material !== null ? this.material : state.material;
  8072. return this.reference;
  8073. }
  8074. }
  8075. /**
  8076. * TSL function for creating a material reference node.
  8077. *
  8078. * @function
  8079. * @param {String} name - The name of the property the node refers to.
  8080. * @param {String} type - The uniform type that should be used to represent the property value.
  8081. * @param {Material?} [material=null] - The material the property belongs to.
  8082. * When no material is set, the node refers to the material of the current rendered object.
  8083. * @returns {MaterialReferenceNode}
  8084. */
  8085. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  8086. /** @module Tangent **/
  8087. /**
  8088. * TSL object that represents the tangent attribute of the current rendered object.
  8089. *
  8090. * @type {Node<vec4>}
  8091. */
  8092. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  8093. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  8094. builder.geometry.computeTangents();
  8095. }
  8096. return attribute( 'tangent', 'vec4' );
  8097. } )();
  8098. /**
  8099. * TSL object that represents the vertex tangent in local space of the current rendered object.
  8100. *
  8101. * @type {Node<vec3>}
  8102. */
  8103. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  8104. /**
  8105. * TSL object that represents the vertex tangent in view space of the current rendered object.
  8106. *
  8107. * @type {Node<vec3>}
  8108. */
  8109. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.varying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  8110. /**
  8111. * TSL object that represents the vertex tangent in world space of the current rendered object.
  8112. *
  8113. * @type {Node<vec3>}
  8114. */
  8115. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).varying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  8116. /**
  8117. * TSL object that represents the transformed vertex tangent in view space of the current rendered object.
  8118. *
  8119. * @type {Node<vec3>}
  8120. */
  8121. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  8122. /**
  8123. * TSL object that represents the transformed vertex tangent in world space of the current rendered object.
  8124. *
  8125. * @type {Node<vec3>}
  8126. */
  8127. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  8128. /** @module Bitangent **/
  8129. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  8130. /**
  8131. * TSL object that represents the bitangent attribute of the current rendered object.
  8132. *
  8133. * @type {Node<vec3>}
  8134. */
  8135. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  8136. /**
  8137. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  8138. *
  8139. * @type {Node<vec3>}
  8140. */
  8141. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  8142. /**
  8143. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  8144. *
  8145. * @type {Node<vec4>}
  8146. */
  8147. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  8148. /**
  8149. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  8150. *
  8151. * @type {Node<vec4>}
  8152. */
  8153. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  8154. /**
  8155. * TSL object that represents the transformed vertex bitangent in view space of the current rendered object.
  8156. *
  8157. * @type {Node<vec4>}
  8158. */
  8159. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  8160. /**
  8161. * TSL object that represents the transformed vertex bitangent in world space of the current rendered object.
  8162. *
  8163. * @type {Node<vec4>}
  8164. */
  8165. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  8166. /** @module AccessorsUtils **/
  8167. /**
  8168. * TSL object that represents the TBN matrix in view space.
  8169. *
  8170. * @type {Node<mat3>}
  8171. */
  8172. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  8173. /**
  8174. * TSL object that represents the parallax direction.
  8175. *
  8176. * @type {Node<mat3>}
  8177. */
  8178. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  8179. /**
  8180. * TSL function for computing parallax uv coordinates.
  8181. *
  8182. * @function
  8183. * @param {Node<vec2>} uv - A uv node.
  8184. * @param {Node<vec2>} scale - A scale node.
  8185. * @returns {Node<vec2>} Parallax uv coordinates.
  8186. */
  8187. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  8188. /**
  8189. * TSL function for computing bent normals.
  8190. *
  8191. * @function
  8192. * @returns {Node<vec3>} Bent normals.
  8193. */
  8194. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  8195. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  8196. let bentNormal = anisotropyB.cross( positionViewDirection );
  8197. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  8198. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  8199. return bentNormal;
  8200. } )();
  8201. /** @module NormalMapNode **/
  8202. // Normal Mapping Without Precomputed Tangents
  8203. // http://www.thetenthplanet.de/archives/1180
  8204. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  8205. const { eye_pos, surf_norm, mapN, uv } = inputs;
  8206. const q0 = eye_pos.dFdx();
  8207. const q1 = eye_pos.dFdy();
  8208. const st0 = uv.dFdx();
  8209. const st1 = uv.dFdy();
  8210. const N = surf_norm; // normalized
  8211. const q1perp = q1.cross( N );
  8212. const q0perp = N.cross( q0 );
  8213. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  8214. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  8215. const det = T.dot( T ).max( B.dot( B ) );
  8216. const scale = faceDirection.mul( det.inverseSqrt() );
  8217. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  8218. } );
  8219. /**
  8220. * This class can be used for applying normals maps to materials.
  8221. *
  8222. * ```js
  8223. * material.normalNode = normalMap( texture( normalTex ) );
  8224. * ```
  8225. *
  8226. * @augments TempNode
  8227. */
  8228. class NormalMapNode extends TempNode {
  8229. static get type() {
  8230. return 'NormalMapNode';
  8231. }
  8232. /**
  8233. * Constructs a new normal map node.
  8234. *
  8235. * @param {Node} node - Represents the normal map data.
  8236. * @param {Node?} [scaleNode=null] - Controls the intensity of the effect.
  8237. */
  8238. constructor( node, scaleNode = null ) {
  8239. super( 'vec3' );
  8240. /**
  8241. * Represents the normal map data.
  8242. *
  8243. * @type {Node}
  8244. */
  8245. this.node = node;
  8246. /**
  8247. * Controls the intensity of the effect.
  8248. *
  8249. * @type {Node?}
  8250. * @default null
  8251. */
  8252. this.scaleNode = scaleNode;
  8253. /**
  8254. * The normal map type.
  8255. *
  8256. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  8257. * @default TangentSpaceNormalMap
  8258. */
  8259. this.normalMapType = TangentSpaceNormalMap;
  8260. }
  8261. setup( builder ) {
  8262. const { normalMapType, scaleNode } = this;
  8263. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  8264. if ( scaleNode !== null ) {
  8265. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  8266. }
  8267. let outputNode = null;
  8268. if ( normalMapType === ObjectSpaceNormalMap ) {
  8269. outputNode = transformNormalToView( normalMap );
  8270. } else if ( normalMapType === TangentSpaceNormalMap ) {
  8271. const tangent = builder.hasGeometryAttribute( 'tangent' );
  8272. if ( tangent === true ) {
  8273. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  8274. } else {
  8275. outputNode = perturbNormal2Arb( {
  8276. eye_pos: positionView,
  8277. surf_norm: normalView,
  8278. mapN: normalMap,
  8279. uv: uv()
  8280. } );
  8281. }
  8282. }
  8283. return outputNode;
  8284. }
  8285. }
  8286. /**
  8287. * TSL function for creating a normal map node.
  8288. *
  8289. * @function
  8290. * @param {Node} node - Represents the normal map data.
  8291. * @param {Node?} [scaleNode=null] - Controls the intensity of the effect.
  8292. * @returns {NormalMapNode}
  8293. */
  8294. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  8295. /** @module BumpMapNode **/
  8296. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  8297. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  8298. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  8299. // It's used to preserve the same TextureNode instance
  8300. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  8301. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  8302. return vec2(
  8303. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  8304. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  8305. ).mul( bumpScale );
  8306. } );
  8307. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8308. const perturbNormalArb = Fn( ( inputs ) => {
  8309. const { surf_pos, surf_norm, dHdxy } = inputs;
  8310. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  8311. const vSigmaX = surf_pos.dFdx().normalize();
  8312. const vSigmaY = surf_pos.dFdy().normalize();
  8313. const vN = surf_norm; // normalized
  8314. const R1 = vSigmaY.cross( vN );
  8315. const R2 = vN.cross( vSigmaX );
  8316. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  8317. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  8318. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  8319. } );
  8320. /**
  8321. * This class can be used for applying bump maps to materials.
  8322. *
  8323. * ```js
  8324. * material.normalNode = bumpMap( texture( bumpTex ) );
  8325. * ```
  8326. *
  8327. * @augments TempNode
  8328. */
  8329. class BumpMapNode extends TempNode {
  8330. static get type() {
  8331. return 'BumpMapNode';
  8332. }
  8333. /**
  8334. * Constructs a new bump map node.
  8335. *
  8336. * @param {Node} textureNode - Represents the bump map data.
  8337. * @param {Node?} [scaleNode=null] - Controls the intensity of the bump effect.
  8338. */
  8339. constructor( textureNode, scaleNode = null ) {
  8340. super( 'vec3' );
  8341. /**
  8342. * Represents the bump map data.
  8343. *
  8344. * @type {Node}
  8345. */
  8346. this.textureNode = textureNode;
  8347. /**
  8348. * Controls the intensity of the bump effect.
  8349. *
  8350. * @type {Node?}
  8351. * @default null
  8352. */
  8353. this.scaleNode = scaleNode;
  8354. }
  8355. setup() {
  8356. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  8357. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  8358. return perturbNormalArb( {
  8359. surf_pos: positionView,
  8360. surf_norm: normalView,
  8361. dHdxy
  8362. } );
  8363. }
  8364. }
  8365. /**
  8366. * TSL function for creating a bump map node.
  8367. *
  8368. * @function
  8369. * @param {Node} textureNode - Represents the bump map data.
  8370. * @param {Node?} [scaleNode=null] - Controls the intensity of the bump effect.
  8371. * @returns {BumpMapNode}
  8372. */
  8373. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  8374. /** @module MaterialNode **/
  8375. const _propertyCache = new Map();
  8376. /**
  8377. * This class should simplify the node access to material properties.
  8378. * It internal uses reference nodes to make sure changes to material
  8379. * properties are automatically reflected to predefined TSL objects
  8380. * like e.g. `materialColor`.
  8381. *
  8382. * @augments Node
  8383. */
  8384. class MaterialNode extends Node {
  8385. static get type() {
  8386. return 'MaterialNode';
  8387. }
  8388. /**
  8389. * Constructs a new material node.
  8390. *
  8391. * @param {String} scope - The scope defines what kind of material property is referred by the node.
  8392. */
  8393. constructor( scope ) {
  8394. super();
  8395. /**
  8396. * The scope defines what material property is referred by the node.
  8397. *
  8398. * @type {String}
  8399. */
  8400. this.scope = scope;
  8401. }
  8402. /**
  8403. * Returns a cached reference node for the given property and type.
  8404. *
  8405. * @param {String} property - The name of the material property.
  8406. * @param {String} type - The uniform type of the property.
  8407. * @return {MaterialReferenceNode} A material reference node representing the property access.
  8408. */
  8409. getCache( property, type ) {
  8410. let node = _propertyCache.get( property );
  8411. if ( node === undefined ) {
  8412. node = materialReference( property, type );
  8413. _propertyCache.set( property, node );
  8414. }
  8415. return node;
  8416. }
  8417. /**
  8418. * Returns a float-typed material reference node for the given property name.
  8419. *
  8420. * @param {String} property - The name of the material property.
  8421. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  8422. */
  8423. getFloat( property ) {
  8424. return this.getCache( property, 'float' );
  8425. }
  8426. /**
  8427. * Returns a color-typed material reference node for the given property name.
  8428. *
  8429. * @param {String} property - The name of the material property.
  8430. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  8431. */
  8432. getColor( property ) {
  8433. return this.getCache( property, 'color' );
  8434. }
  8435. /**
  8436. * Returns a texture-typed material reference node for the given property name.
  8437. *
  8438. * @param {String} property - The name of the material property.
  8439. * @return {MaterialReferenceNode} A material reference node representing the property access.
  8440. */
  8441. getTexture( property ) {
  8442. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  8443. }
  8444. /**
  8445. * The node setup is done depending on the selected scope. Multiple material properties
  8446. * might be grouped into a single node composition if they logically belong together.
  8447. *
  8448. * @param {NodeBuilder} builder - The current node builder.
  8449. * @return {Node} The node representing the selected scope.
  8450. */
  8451. setup( builder ) {
  8452. const material = builder.context.material;
  8453. const scope = this.scope;
  8454. let node = null;
  8455. if ( scope === MaterialNode.COLOR ) {
  8456. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  8457. if ( material.map && material.map.isTexture === true ) {
  8458. node = colorNode.mul( this.getTexture( 'map' ) );
  8459. } else {
  8460. node = colorNode;
  8461. }
  8462. } else if ( scope === MaterialNode.OPACITY ) {
  8463. const opacityNode = this.getFloat( scope );
  8464. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  8465. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  8466. } else {
  8467. node = opacityNode;
  8468. }
  8469. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  8470. if ( material.specularMap && material.specularMap.isTexture === true ) {
  8471. node = this.getTexture( 'specular' ).r;
  8472. } else {
  8473. node = float( 1 );
  8474. }
  8475. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  8476. const specularIntensityNode = this.getFloat( scope );
  8477. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  8478. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  8479. } else {
  8480. node = specularIntensityNode;
  8481. }
  8482. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  8483. const specularColorNode = this.getColor( scope );
  8484. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  8485. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  8486. } else {
  8487. node = specularColorNode;
  8488. }
  8489. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  8490. const roughnessNode = this.getFloat( scope );
  8491. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  8492. node = roughnessNode.mul( this.getTexture( scope ).g );
  8493. } else {
  8494. node = roughnessNode;
  8495. }
  8496. } else if ( scope === MaterialNode.METALNESS ) {
  8497. const metalnessNode = this.getFloat( scope );
  8498. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  8499. node = metalnessNode.mul( this.getTexture( scope ).b );
  8500. } else {
  8501. node = metalnessNode;
  8502. }
  8503. } else if ( scope === MaterialNode.EMISSIVE ) {
  8504. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  8505. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  8506. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  8507. node = emissiveNode.mul( this.getTexture( scope ) );
  8508. } else {
  8509. node = emissiveNode;
  8510. }
  8511. } else if ( scope === MaterialNode.NORMAL ) {
  8512. if ( material.normalMap ) {
  8513. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  8514. node.normalMapType = material.normalMapType;
  8515. } else if ( material.bumpMap ) {
  8516. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  8517. } else {
  8518. node = normalView;
  8519. }
  8520. } else if ( scope === MaterialNode.CLEARCOAT ) {
  8521. const clearcoatNode = this.getFloat( scope );
  8522. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  8523. node = clearcoatNode.mul( this.getTexture( scope ).r );
  8524. } else {
  8525. node = clearcoatNode;
  8526. }
  8527. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  8528. const clearcoatRoughnessNode = this.getFloat( scope );
  8529. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  8530. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  8531. } else {
  8532. node = clearcoatRoughnessNode;
  8533. }
  8534. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  8535. if ( material.clearcoatNormalMap ) {
  8536. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  8537. } else {
  8538. node = normalView;
  8539. }
  8540. } else if ( scope === MaterialNode.SHEEN ) {
  8541. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  8542. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  8543. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  8544. } else {
  8545. node = sheenNode;
  8546. }
  8547. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  8548. const sheenRoughnessNode = this.getFloat( scope );
  8549. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  8550. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  8551. } else {
  8552. node = sheenRoughnessNode;
  8553. }
  8554. node = node.clamp( 0.07, 1.0 );
  8555. } else if ( scope === MaterialNode.ANISOTROPY ) {
  8556. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  8557. const anisotropyPolar = this.getTexture( scope );
  8558. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  8559. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  8560. } else {
  8561. node = materialAnisotropyVector;
  8562. }
  8563. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  8564. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  8565. if ( material.iridescenceThicknessMap ) {
  8566. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  8567. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  8568. } else {
  8569. node = iridescenceThicknessMaximum;
  8570. }
  8571. } else if ( scope === MaterialNode.TRANSMISSION ) {
  8572. const transmissionNode = this.getFloat( scope );
  8573. if ( material.transmissionMap ) {
  8574. node = transmissionNode.mul( this.getTexture( scope ).r );
  8575. } else {
  8576. node = transmissionNode;
  8577. }
  8578. } else if ( scope === MaterialNode.THICKNESS ) {
  8579. const thicknessNode = this.getFloat( scope );
  8580. if ( material.thicknessMap ) {
  8581. node = thicknessNode.mul( this.getTexture( scope ).g );
  8582. } else {
  8583. node = thicknessNode;
  8584. }
  8585. } else if ( scope === MaterialNode.IOR ) {
  8586. node = this.getFloat( scope );
  8587. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  8588. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  8589. } else if ( scope === MaterialNode.AO ) {
  8590. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  8591. } else {
  8592. const outputType = this.getNodeType( builder );
  8593. node = this.getCache( scope, outputType );
  8594. }
  8595. return node;
  8596. }
  8597. }
  8598. MaterialNode.ALPHA_TEST = 'alphaTest';
  8599. MaterialNode.COLOR = 'color';
  8600. MaterialNode.OPACITY = 'opacity';
  8601. MaterialNode.SHININESS = 'shininess';
  8602. MaterialNode.SPECULAR = 'specular';
  8603. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  8604. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  8605. MaterialNode.SPECULAR_COLOR = 'specularColor';
  8606. MaterialNode.REFLECTIVITY = 'reflectivity';
  8607. MaterialNode.ROUGHNESS = 'roughness';
  8608. MaterialNode.METALNESS = 'metalness';
  8609. MaterialNode.NORMAL = 'normal';
  8610. MaterialNode.CLEARCOAT = 'clearcoat';
  8611. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  8612. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  8613. MaterialNode.EMISSIVE = 'emissive';
  8614. MaterialNode.ROTATION = 'rotation';
  8615. MaterialNode.SHEEN = 'sheen';
  8616. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  8617. MaterialNode.ANISOTROPY = 'anisotropy';
  8618. MaterialNode.IRIDESCENCE = 'iridescence';
  8619. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  8620. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  8621. MaterialNode.IOR = 'ior';
  8622. MaterialNode.TRANSMISSION = 'transmission';
  8623. MaterialNode.THICKNESS = 'thickness';
  8624. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  8625. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  8626. MaterialNode.LINE_SCALE = 'scale';
  8627. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  8628. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  8629. MaterialNode.LINE_WIDTH = 'linewidth';
  8630. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  8631. MaterialNode.POINT_WIDTH = 'pointWidth';
  8632. MaterialNode.DISPERSION = 'dispersion';
  8633. MaterialNode.LIGHT_MAP = 'light';
  8634. MaterialNode.AO = 'ao';
  8635. /**
  8636. * TSL object that represents alpha test of the current material.
  8637. *
  8638. * @type {Node<float>}
  8639. */
  8640. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  8641. /**
  8642. * TSL object that represents the diffuse color of the current material.
  8643. * The value is composed via `color` * `map`.
  8644. *
  8645. * @type {Node<vec3>}
  8646. */
  8647. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  8648. /**
  8649. * TSL object that represents the shininess of the current material.
  8650. *
  8651. * @type {Node<float>}
  8652. */
  8653. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  8654. /**
  8655. * TSL object that represents the emissive color of the current material.
  8656. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  8657. *
  8658. * @type {Node<vec3>}
  8659. */
  8660. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  8661. /**
  8662. * TSL object that represents the opacity of the current material.
  8663. * The value is composed via `opacity` * `alphaMap`.
  8664. *
  8665. * @type {Node<float>}
  8666. */
  8667. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  8668. /**
  8669. * TSL object that represents the specular of the current material.
  8670. *
  8671. * @type {Node<vec3>}
  8672. */
  8673. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  8674. /**
  8675. * TSL object that represents the specular intensity of the current material.
  8676. * The value is composed via `specularIntensity` * `specularMap.a`.
  8677. *
  8678. * @type {Node<float>}
  8679. */
  8680. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  8681. /**
  8682. * TSL object that represents the specular color of the current material.
  8683. * The value is composed via `specularColor` * `specularMap.rgb`.
  8684. *
  8685. * @type {Node<vec3>}
  8686. */
  8687. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  8688. /**
  8689. * TSL object that represents the specular strength of the current material.
  8690. * The value is composed via `specularMap.r`.
  8691. *
  8692. * @type {Node<float>}
  8693. */
  8694. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  8695. /**
  8696. * TSL object that represents the reflectivity of the current material.
  8697. *
  8698. * @type {Node<float>}
  8699. */
  8700. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  8701. /**
  8702. * TSL object that represents the roughness of the current material.
  8703. * The value is composed via `roughness` * `roughnessMap.g`
  8704. *
  8705. * @type {Node<float>}
  8706. */
  8707. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  8708. /**
  8709. * TSL object that represents the metalness of the current material.
  8710. * The value is composed via `metalness` * `metalnessMap.b`
  8711. *
  8712. * @type {Node<float>}
  8713. */
  8714. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  8715. /**
  8716. * TSL object that represents the normal of the current material.
  8717. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  8718. *
  8719. * @type {Node<vec3>}
  8720. */
  8721. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL ).context( { getUV: null } );
  8722. /**
  8723. * TSL object that represents the clearcoat of the current material.
  8724. * The value is composed via `clearcoat` * `clearcoatMap.r`
  8725. *
  8726. * @type {Node<float>}
  8727. */
  8728. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  8729. /**
  8730. * TSL object that represents the clearcoat roughness of the current material.
  8731. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`
  8732. *
  8733. * @type {Node<float>}
  8734. */
  8735. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  8736. /**
  8737. * TSL object that represents the clearcoat normal of the current material.
  8738. * The value will be either `clearcoatNormalMap` or `normalView`.
  8739. *
  8740. * @type {Node<vec3>}
  8741. */
  8742. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL ).context( { getUV: null } );
  8743. /**
  8744. * TSL object that represents the rotation of the current sprite material.
  8745. *
  8746. * @type {Node<float>}
  8747. */
  8748. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  8749. /**
  8750. * TSL object that represents the sheen color of the current material.
  8751. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  8752. *
  8753. * @type {Node<vec3>}
  8754. */
  8755. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  8756. /**
  8757. * TSL object that represents the sheen roughness of the current material.
  8758. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a` .
  8759. *
  8760. * @type {Node<float>}
  8761. */
  8762. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  8763. /**
  8764. * TSL object that represents the anisotropy of the current material.
  8765. *
  8766. * @type {Node<vec2>}
  8767. */
  8768. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  8769. /**
  8770. * TSL object that represents the iridescence of the current material.
  8771. *
  8772. * @type {Node<float>}
  8773. */
  8774. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  8775. /**
  8776. * TSL object that represents the iridescence IOR of the current material.
  8777. *
  8778. * @type {Node<float>}
  8779. */
  8780. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  8781. /**
  8782. * TSL object that represents the iridescence thickness of the current material.
  8783. *
  8784. * @type {Node<float>}
  8785. */
  8786. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  8787. /**
  8788. * TSL object that represents the transmission of the current material.
  8789. * The value is composed via `transmission` * `transmissionMap.r`.
  8790. *
  8791. * @type {Node<float>}
  8792. */
  8793. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  8794. /**
  8795. * TSL object that represents the thickness of the current material.
  8796. * The value is composed via `thickness` * `thicknessMap.g`.
  8797. *
  8798. * @type {Node<float>}
  8799. */
  8800. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  8801. /**
  8802. * TSL object that represents the IOR of the current material.
  8803. *
  8804. * @type {Node<float>}
  8805. */
  8806. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  8807. /**
  8808. * TSL object that represents the attenuation distance of the current material.
  8809. *
  8810. * @type {Node<float>}
  8811. */
  8812. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  8813. /**
  8814. * TSL object that represents the attenuation color of the current material.
  8815. *
  8816. * @type {Node<vec3>}
  8817. */
  8818. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  8819. /**
  8820. * TSL object that represents the scale of the current dashed line material.
  8821. *
  8822. * @type {Node<float>}
  8823. */
  8824. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  8825. /**
  8826. * TSL object that represents the dash size of the current dashed line material.
  8827. *
  8828. * @type {Node<float>}
  8829. */
  8830. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  8831. /**
  8832. * TSL object that represents the gap size of the current dashed line material.
  8833. *
  8834. * @type {Node<float>}
  8835. */
  8836. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  8837. /**
  8838. * TSL object that represents the line width of the current line material.
  8839. *
  8840. * @type {Node<float>}
  8841. */
  8842. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  8843. /**
  8844. * TSL object that represents the dash offset of the current line material.
  8845. *
  8846. * @type {Node<float>}
  8847. */
  8848. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  8849. /**
  8850. * TSL object that represents the point width of the current points material.
  8851. *
  8852. * @type {Node<float>}
  8853. */
  8854. const materialPointWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_WIDTH );
  8855. /**
  8856. * TSL object that represents the dispersion of the current material.
  8857. *
  8858. * @type {Node<float>}
  8859. */
  8860. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  8861. /**
  8862. * TSL object that represents the light map of the current material.
  8863. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  8864. *
  8865. * @type {Node<vec3>}
  8866. */
  8867. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  8868. /**
  8869. * TSL object that represents the ambient occlusion map of the current material.
  8870. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  8871. *
  8872. * @type {Node<float>}
  8873. */
  8874. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  8875. /**
  8876. * TSL object that represents the anisotropy vector of the current material.
  8877. *
  8878. * @type {Node<vec2>}
  8879. */
  8880. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  8881. return frame.material;
  8882. } ).onRenderUpdate( function ( { material } ) {
  8883. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  8884. } );
  8885. /** @module ModelViewProjectionNode **/
  8886. /**
  8887. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  8888. *
  8889. * @type {VaryingNode<vec4>}
  8890. */
  8891. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  8892. return builder.context.setupModelViewProjection();
  8893. }, 'vec4' ).once() )().varying( 'v_modelViewProjection' );
  8894. /** @module IndexNode **/
  8895. /**
  8896. * This class represents shader indices of different types. The following predefined node
  8897. * objects cover frequent use cases:
  8898. *
  8899. * - `vertexIndex`: The index of a vertex within a mesh.
  8900. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  8901. * - `drawIndex`: The index of a draw call.
  8902. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  8903. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  8904. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  8905. *
  8906. * @augments Node
  8907. */
  8908. class IndexNode extends Node {
  8909. static get type() {
  8910. return 'IndexNode';
  8911. }
  8912. /**
  8913. * Constructs a new index node.
  8914. *
  8915. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  8916. */
  8917. constructor( scope ) {
  8918. super( 'uint' );
  8919. /**
  8920. * The scope of the index node.
  8921. *
  8922. * @type {String}
  8923. */
  8924. this.scope = scope;
  8925. /**
  8926. * This flag can be used for type testing.
  8927. *
  8928. * @type {Boolean}
  8929. * @readonly
  8930. * @default true
  8931. */
  8932. this.isIndexNode = true;
  8933. }
  8934. generate( builder ) {
  8935. const nodeType = this.getNodeType( builder );
  8936. const scope = this.scope;
  8937. let propertyName;
  8938. if ( scope === IndexNode.VERTEX ) {
  8939. propertyName = builder.getVertexIndex();
  8940. } else if ( scope === IndexNode.INSTANCE ) {
  8941. propertyName = builder.getInstanceIndex();
  8942. } else if ( scope === IndexNode.DRAW ) {
  8943. propertyName = builder.getDrawIndex();
  8944. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  8945. propertyName = builder.getInvocationLocalIndex();
  8946. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  8947. propertyName = builder.getInvocationSubgroupIndex();
  8948. } else if ( scope === IndexNode.SUBGROUP ) {
  8949. propertyName = builder.getSubgroupIndex();
  8950. } else {
  8951. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  8952. }
  8953. let output;
  8954. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  8955. output = propertyName;
  8956. } else {
  8957. const nodeVarying = varying( this );
  8958. output = nodeVarying.build( builder, nodeType );
  8959. }
  8960. return output;
  8961. }
  8962. }
  8963. IndexNode.VERTEX = 'vertex';
  8964. IndexNode.INSTANCE = 'instance';
  8965. IndexNode.SUBGROUP = 'subgroup';
  8966. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  8967. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  8968. IndexNode.DRAW = 'draw';
  8969. /**
  8970. * TSL object that represents the index of a vertex within a mesh.
  8971. *
  8972. * @type {IndexNode}
  8973. */
  8974. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  8975. /**
  8976. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  8977. *
  8978. * @type {IndexNode}
  8979. */
  8980. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  8981. /**
  8982. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  8983. *
  8984. * @type {IndexNode}
  8985. */
  8986. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  8987. /**
  8988. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  8989. *
  8990. * @type {IndexNode}
  8991. */
  8992. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  8993. /**
  8994. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  8995. *
  8996. * @type {IndexNode}
  8997. */
  8998. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  8999. /**
  9000. * TSL object that represents the index of a draw call.
  9001. *
  9002. * @type {IndexNode}
  9003. */
  9004. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  9005. /** @module InstanceNode **/
  9006. /**
  9007. * This node implements the vertex shader logic which is required
  9008. * when rendering 3D objects via instancing. The code makes sure
  9009. * vertex positions, normals and colors can be modified via instanced
  9010. * data.
  9011. *
  9012. * @augments Node
  9013. */
  9014. class InstanceNode extends Node {
  9015. static get type() {
  9016. return 'InstanceNode';
  9017. }
  9018. /**
  9019. * Constructs a new instance node.
  9020. *
  9021. * @param {Number} count - The number of instances.
  9022. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  9023. * @param {InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  9024. */
  9025. constructor( count, instanceMatrix, instanceColor ) {
  9026. super( 'void' );
  9027. /**
  9028. * The number of instances.
  9029. *
  9030. * @type {Number}
  9031. */
  9032. this.count = count;
  9033. /**
  9034. * Instanced buffer attribute representing the transformation of instances.
  9035. *
  9036. * @type {InstancedBufferAttribute}
  9037. */
  9038. this.instanceMatrix = instanceMatrix;
  9039. /**
  9040. * Instanced buffer attribute representing the color of instances.
  9041. *
  9042. * @type {InstancedBufferAttribute}
  9043. */
  9044. this.instanceColor = instanceColor;
  9045. /**
  9046. * The node that represents the instance matrix data.
  9047. *
  9048. * @type {Node}
  9049. */
  9050. this.instanceMatrixNode = null;
  9051. /**
  9052. * The node that represents the instance color data.
  9053. *
  9054. * @type {Node}
  9055. */
  9056. this.instanceColorNode = null;
  9057. /**
  9058. * The update type is set to `frame` since an update
  9059. * of instanced buffer data must be checked per frame.
  9060. *
  9061. * @type {String}
  9062. * @default 'frame'
  9063. */
  9064. this.updateType = NodeUpdateType.FRAME;
  9065. /**
  9066. * A reference to a buffer that is used by `instanceMatrixNode`.
  9067. *
  9068. * @type {InstancedInterleavedBuffer}
  9069. */
  9070. this.buffer = null;
  9071. /**
  9072. * A reference to a buffer that is used by `instanceColorNode`.
  9073. *
  9074. * @type {InstancedInterleavedBuffer}
  9075. */
  9076. this.bufferColor = null;
  9077. }
  9078. /**
  9079. * Setups the internal buffers and nodes and assigns the transformed vertex data
  9080. * to predefined node variables for accumulation. That follows the same patterns
  9081. * like with morph and skinning nodes.
  9082. *
  9083. * @param {NodeBuilder} builder - The current node builder.
  9084. */
  9085. setup( builder ) {
  9086. const { count, instanceMatrix, instanceColor } = this;
  9087. let { instanceMatrixNode, instanceColorNode } = this;
  9088. if ( instanceMatrixNode === null ) {
  9089. // 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.
  9090. if ( count <= 1000 ) {
  9091. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  9092. } else {
  9093. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  9094. this.buffer = buffer;
  9095. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  9096. const instanceBuffers = [
  9097. // F.Signature -> bufferAttribute( array, type, stride, offset )
  9098. bufferFn( buffer, 'vec4', 16, 0 ),
  9099. bufferFn( buffer, 'vec4', 16, 4 ),
  9100. bufferFn( buffer, 'vec4', 16, 8 ),
  9101. bufferFn( buffer, 'vec4', 16, 12 )
  9102. ];
  9103. instanceMatrixNode = mat4( ...instanceBuffers );
  9104. }
  9105. this.instanceMatrixNode = instanceMatrixNode;
  9106. }
  9107. if ( instanceColor && instanceColorNode === null ) {
  9108. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  9109. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  9110. this.bufferColor = buffer;
  9111. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  9112. this.instanceColorNode = instanceColorNode;
  9113. }
  9114. // POSITION
  9115. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  9116. positionLocal.assign( instancePosition );
  9117. // NORMAL
  9118. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  9119. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  9120. // ASSIGNS
  9121. normalLocal.assign( instanceNormal );
  9122. }
  9123. // COLOR
  9124. if ( this.instanceColorNode !== null ) {
  9125. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  9126. }
  9127. }
  9128. /**
  9129. * Checks if the internal buffers required an update.
  9130. *
  9131. * @param {NodeFrame} frame - The current node frame.
  9132. */
  9133. update( /*frame*/ ) {
  9134. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer !== null && this.instanceMatrix.version !== this.buffer.version ) {
  9135. this.buffer.version = this.instanceMatrix.version;
  9136. }
  9137. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor !== null && this.instanceColor.version !== this.bufferColor.version ) {
  9138. this.bufferColor.version = this.instanceColor.version;
  9139. }
  9140. }
  9141. }
  9142. /**
  9143. * TSL function for creating an instance node.
  9144. *
  9145. * @function
  9146. * @param {Number} count - The number of instances.
  9147. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  9148. * @param {InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  9149. * @returns {InstanceNode}
  9150. */
  9151. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  9152. /** @module InstancedMeshNode **/
  9153. /**
  9154. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  9155. * It allows an easier setup of the instance node.
  9156. *
  9157. * @augments module:InstanceNode~InstanceNode
  9158. */
  9159. class InstancedMeshNode extends InstanceNode {
  9160. static get type() {
  9161. return 'InstancedMeshNode';
  9162. }
  9163. /**
  9164. * Constructs a new instanced mesh node.
  9165. *
  9166. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  9167. */
  9168. constructor( instancedMesh ) {
  9169. const { count, instanceMatrix, instanceColor } = instancedMesh;
  9170. super( count, instanceMatrix, instanceColor );
  9171. /**
  9172. * A reference to the instanced mesh.
  9173. *
  9174. * @type {InstancedMesh}
  9175. */
  9176. this.instancedMesh = instancedMesh;
  9177. }
  9178. }
  9179. /**
  9180. * TSL function for creating an instanced mesh node.
  9181. *
  9182. * @function
  9183. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  9184. * @returns {InstancedMeshNode}
  9185. */
  9186. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode );
  9187. /** @module BatchNode **/
  9188. /**
  9189. * This node implements the vertex shader logic which is required
  9190. * when rendering 3D objects via batching. `BatchNode` must be used
  9191. * with instances of {@link BatchedMesh}.
  9192. *
  9193. * @augments Node
  9194. */
  9195. class BatchNode extends Node {
  9196. static get type() {
  9197. return 'BatchNode';
  9198. }
  9199. /**
  9200. * Constructs a new batch node.
  9201. *
  9202. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  9203. */
  9204. constructor( batchMesh ) {
  9205. super( 'void' );
  9206. /**
  9207. * A reference to batched mesh.
  9208. *
  9209. * @type {BatchedMesh}
  9210. */
  9211. this.batchMesh = batchMesh;
  9212. /**
  9213. * The batching index node.
  9214. *
  9215. * @type {IndexNode?}
  9216. * @default null
  9217. */
  9218. this.batchingIdNode = null;
  9219. }
  9220. /**
  9221. * Setups the internal buffers and nodes and assigns the transformed vertex data
  9222. * to predefined node variables for accumulation. That follows the same patterns
  9223. * like with morph and skinning nodes.
  9224. *
  9225. * @param {NodeBuilder} builder - The current node builder.
  9226. */
  9227. setup( builder ) {
  9228. if ( this.batchingIdNode === null ) {
  9229. if ( builder.getDrawIndex() === null ) {
  9230. this.batchingIdNode = instanceIndex;
  9231. } else {
  9232. this.batchingIdNode = drawIndex;
  9233. }
  9234. }
  9235. const getIndirectIndex = Fn( ( [ id ] ) => {
  9236. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  9237. const x = int( id ).modInt( int( size ) );
  9238. const y = int( id ).div( int( size ) );
  9239. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  9240. } ).setLayout( {
  9241. name: 'getIndirectIndex',
  9242. type: 'uint',
  9243. inputs: [
  9244. { name: 'id', type: 'int' }
  9245. ]
  9246. } );
  9247. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  9248. const matricesTexture = this.batchMesh._matricesTexture;
  9249. const size = textureSize( textureLoad( matricesTexture ), 0 );
  9250. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  9251. const x = j.modInt( size );
  9252. const y = j.div( int( size ) );
  9253. const batchingMatrix = mat4(
  9254. textureLoad( matricesTexture, ivec2( x, y ) ),
  9255. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  9256. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  9257. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  9258. );
  9259. const colorsTexture = this.batchMesh._colorsTexture;
  9260. if ( colorsTexture !== null ) {
  9261. const getBatchingColor = Fn( ( [ id ] ) => {
  9262. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  9263. const j = id;
  9264. const x = j.modInt( size );
  9265. const y = j.div( size );
  9266. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  9267. } ).setLayout( {
  9268. name: 'getBatchingColor',
  9269. type: 'vec3',
  9270. inputs: [
  9271. { name: 'id', type: 'int' }
  9272. ]
  9273. } );
  9274. const color = getBatchingColor( indirectId );
  9275. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  9276. }
  9277. const bm = mat3( batchingMatrix );
  9278. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  9279. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  9280. const batchingNormal = bm.mul( transformedNormal ).xyz;
  9281. normalLocal.assign( batchingNormal );
  9282. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  9283. tangentLocal.mulAssign( bm );
  9284. }
  9285. }
  9286. }
  9287. /**
  9288. * TSL function for creating a batch node.
  9289. *
  9290. * @function
  9291. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  9292. * @returns {BatchNode}
  9293. */
  9294. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  9295. /** @module SkinningNode **/
  9296. const _frameId = new WeakMap();
  9297. /**
  9298. * This node implements the vertex transformation shader logic which is required
  9299. * for skinning/skeletal animation.
  9300. *
  9301. * @augments Node
  9302. */
  9303. class SkinningNode extends Node {
  9304. static get type() {
  9305. return 'SkinningNode';
  9306. }
  9307. /**
  9308. * Constructs a new skinning node.
  9309. *
  9310. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9311. * @param {Boolean} [useReference=false] - Whether to use reference nodes for internal skinned mesh related data or not.
  9312. */
  9313. constructor( skinnedMesh, useReference = false ) {
  9314. super( 'void' );
  9315. /**
  9316. * The skinned mesh.
  9317. *
  9318. * @type {SkinnedMesh}
  9319. */
  9320. this.skinnedMesh = skinnedMesh;
  9321. /**
  9322. * Whether to use reference nodes for internal skinned mesh related data or not.
  9323. * TODO: Explain the purpose of the property.
  9324. *
  9325. * @type {Boolean}
  9326. */
  9327. this.useReference = useReference;
  9328. /**
  9329. * The update type overwritten since skinning nodes are updated per object.
  9330. *
  9331. * @type {String}
  9332. */
  9333. this.updateType = NodeUpdateType.OBJECT;
  9334. //
  9335. /**
  9336. * The skin index attribute.
  9337. *
  9338. * @type {AttributeNode}
  9339. */
  9340. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  9341. /**
  9342. * The skin weight attribute.
  9343. *
  9344. * @type {AttributeNode}
  9345. */
  9346. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  9347. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  9348. if ( useReference ) {
  9349. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  9350. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  9351. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  9352. } else {
  9353. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  9354. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  9355. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  9356. }
  9357. /**
  9358. * The bind matrix node.
  9359. *
  9360. * @type {Node<mat4>}
  9361. */
  9362. this.bindMatrixNode = bindMatrixNode;
  9363. /**
  9364. * The bind matrix inverse node.
  9365. *
  9366. * @type {Node<mat4>}
  9367. */
  9368. this.bindMatrixInverseNode = bindMatrixInverseNode;
  9369. /**
  9370. * The bind matrices as a uniform buffer node.
  9371. *
  9372. * @type {Node}
  9373. */
  9374. this.boneMatricesNode = boneMatricesNode;
  9375. /**
  9376. * The previous bind matrices as a uniform buffer node.
  9377. * Required for computing motion vectors.
  9378. *
  9379. * @type {Node?}
  9380. * @default null
  9381. */
  9382. this.previousBoneMatricesNode = null;
  9383. }
  9384. /**
  9385. * Transforms the given vertex position via skinning.
  9386. *
  9387. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  9388. * @param {Node<vec3>} [position=positionLocal] - The vertex position in local space.
  9389. * @return {Node<vec3>} The transformed vertex position.
  9390. */
  9391. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  9392. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  9393. const boneMatX = boneMatrices.element( skinIndexNode.x );
  9394. const boneMatY = boneMatrices.element( skinIndexNode.y );
  9395. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  9396. const boneMatW = boneMatrices.element( skinIndexNode.w );
  9397. // POSITION
  9398. const skinVertex = bindMatrixNode.mul( position );
  9399. const skinned = add(
  9400. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  9401. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  9402. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  9403. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  9404. );
  9405. return bindMatrixInverseNode.mul( skinned ).xyz;
  9406. }
  9407. /**
  9408. * Transforms the given vertex normal via skinning.
  9409. *
  9410. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  9411. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  9412. * @return {Node<vec3>} The transformed vertex normal.
  9413. */
  9414. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  9415. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  9416. const boneMatX = boneMatrices.element( skinIndexNode.x );
  9417. const boneMatY = boneMatrices.element( skinIndexNode.y );
  9418. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  9419. const boneMatW = boneMatrices.element( skinIndexNode.w );
  9420. // NORMAL
  9421. let skinMatrix = add(
  9422. skinWeightNode.x.mul( boneMatX ),
  9423. skinWeightNode.y.mul( boneMatY ),
  9424. skinWeightNode.z.mul( boneMatZ ),
  9425. skinWeightNode.w.mul( boneMatW )
  9426. );
  9427. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  9428. return skinMatrix.transformDirection( normal ).xyz;
  9429. }
  9430. /**
  9431. * Transforms the given vertex normal via skinning.
  9432. *
  9433. * @param {NodeBuilder} builder - The current node builder.
  9434. * @return {Node<vec3>} The skinned position from the previous frame.
  9435. */
  9436. getPreviousSkinnedPosition( builder ) {
  9437. const skinnedMesh = builder.object;
  9438. if ( this.previousBoneMatricesNode === null ) {
  9439. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  9440. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  9441. }
  9442. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  9443. }
  9444. /**
  9445. * Returns `true` if bone matrices from the previous frame are required.
  9446. *
  9447. * @param {NodeBuilder} builder - The current node builder.
  9448. * @return {Boolean} Whether bone matrices from the previous frame are required or not.
  9449. */
  9450. needsPreviousBoneMatrices( builder ) {
  9451. const mrt = builder.renderer.getMRT();
  9452. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  9453. }
  9454. /**
  9455. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  9456. *
  9457. * @param {NodeBuilder} builder - The current node builder.
  9458. */
  9459. setup( builder ) {
  9460. if ( this.needsPreviousBoneMatrices( builder ) ) {
  9461. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  9462. }
  9463. const skinPosition = this.getSkinnedPosition();
  9464. positionLocal.assign( skinPosition );
  9465. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  9466. const skinNormal = this.getSkinnedNormal();
  9467. normalLocal.assign( skinNormal );
  9468. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  9469. tangentLocal.assign( skinNormal );
  9470. }
  9471. }
  9472. }
  9473. /**
  9474. * Generates the code snippet of the skinning node.
  9475. *
  9476. * @param {NodeBuilder} builder - The current node builder.
  9477. * @param {String} output - The current output.
  9478. * @return {String} The generated code snippet.
  9479. */
  9480. generate( builder, output ) {
  9481. if ( output !== 'void' ) {
  9482. return positionLocal.build( builder, output );
  9483. }
  9484. }
  9485. /**
  9486. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  9487. *
  9488. * @param {NodeFrame} frame - The current node frame.
  9489. */
  9490. update( frame ) {
  9491. const object = this.useReference ? frame.object : this.skinnedMesh;
  9492. const skeleton = object.skeleton;
  9493. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  9494. _frameId.set( skeleton, frame.frameId );
  9495. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  9496. skeleton.update();
  9497. }
  9498. }
  9499. /**
  9500. * TSL function for creating a skinning node.
  9501. *
  9502. * @function
  9503. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9504. * @returns {SkinningNode}
  9505. */
  9506. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  9507. /**
  9508. * TSL function for creating a skinning node with reference usage.
  9509. *
  9510. * @function
  9511. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9512. * @returns {SkinningNode}
  9513. */
  9514. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  9515. /** @module LoopNode **/
  9516. /**
  9517. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  9518. * ```js
  9519. * Loop( count, ( { i } ) => {
  9520. *
  9521. * } );
  9522. * ```
  9523. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  9524. * ```js
  9525. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  9526. *
  9527. * } );
  9528. *```
  9529. * Nested loops can be defined in a compacted form:
  9530. * ```js
  9531. * Loop( 10, 5, ( { i, j } ) => {
  9532. *
  9533. * } );
  9534. * ```
  9535. * Loops that should run backwards can be defined like so:
  9536. * ```js
  9537. * Loop( { start: 10 }, () => {} );
  9538. * ```
  9539. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  9540. * @augments Node
  9541. */
  9542. class LoopNode extends Node {
  9543. static get type() {
  9544. return 'LoopNode';
  9545. }
  9546. /**
  9547. * Constructs a new loop node.
  9548. *
  9549. * @param {Array<Any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  9550. */
  9551. constructor( params = [] ) {
  9552. super();
  9553. this.params = params;
  9554. }
  9555. /**
  9556. * Returns a loop variable name based on an index. The pattern is
  9557. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  9558. *
  9559. * @param {Number} index - The index.
  9560. * @return {String} The loop variable name.
  9561. */
  9562. getVarName( index ) {
  9563. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  9564. }
  9565. /**
  9566. * Returns properties about this node.
  9567. *
  9568. * @param {NodeBuilder} builder - The current node builder.
  9569. * @return {Object} The node properties.
  9570. */
  9571. getProperties( builder ) {
  9572. const properties = builder.getNodeProperties( this );
  9573. if ( properties.stackNode !== undefined ) return properties;
  9574. //
  9575. const inputs = {};
  9576. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  9577. const param = this.params[ i ];
  9578. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  9579. const type = ( param.isNode !== true && param.type ) || 'int';
  9580. inputs[ name ] = expression( name, type );
  9581. }
  9582. const stack = builder.addStack(); // TODO: cache() it
  9583. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  9584. properties.stackNode = stack;
  9585. builder.removeStack();
  9586. return properties;
  9587. }
  9588. /**
  9589. * This method is overwritten since the node type is inferred based on the loop configuration.
  9590. *
  9591. * @param {NodeBuilder} builder - The current node builder.
  9592. * @return {String} The node type.
  9593. */
  9594. getNodeType( builder ) {
  9595. const { returnsNode } = this.getProperties( builder );
  9596. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  9597. }
  9598. setup( builder ) {
  9599. // setup properties
  9600. this.getProperties( builder );
  9601. }
  9602. generate( builder ) {
  9603. const properties = this.getProperties( builder );
  9604. const params = this.params;
  9605. const stackNode = properties.stackNode;
  9606. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  9607. const param = params[ i ];
  9608. let start = null, end = null, name = null, type = null, condition = null, update = null;
  9609. if ( param.isNode ) {
  9610. type = 'int';
  9611. name = this.getVarName( i );
  9612. start = '0';
  9613. end = param.build( builder, type );
  9614. condition = '<';
  9615. } else {
  9616. type = param.type || 'int';
  9617. name = param.name || this.getVarName( i );
  9618. start = param.start;
  9619. end = param.end;
  9620. condition = param.condition;
  9621. update = param.update;
  9622. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  9623. else if ( start && start.isNode ) start = start.build( builder, type );
  9624. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  9625. else if ( end && end.isNode ) end = end.build( builder, type );
  9626. if ( start !== undefined && end === undefined ) {
  9627. start = start + ' - 1';
  9628. end = '0';
  9629. condition = '>=';
  9630. } else if ( end !== undefined && start === undefined ) {
  9631. start = '0';
  9632. condition = '<';
  9633. }
  9634. if ( condition === undefined ) {
  9635. if ( Number( start ) > Number( end ) ) {
  9636. condition = '>=';
  9637. } else {
  9638. condition = '<';
  9639. }
  9640. }
  9641. }
  9642. const internalParam = { start, end, condition };
  9643. //
  9644. const startSnippet = internalParam.start;
  9645. const endSnippet = internalParam.end;
  9646. let declarationSnippet = '';
  9647. let conditionalSnippet = '';
  9648. let updateSnippet = '';
  9649. if ( ! update ) {
  9650. if ( type === 'int' || type === 'uint' ) {
  9651. if ( condition.includes( '<' ) ) update = '++';
  9652. else update = '--';
  9653. } else {
  9654. if ( condition.includes( '<' ) ) update = '+= 1.';
  9655. else update = '-= 1.';
  9656. }
  9657. }
  9658. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  9659. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  9660. updateSnippet += name + ' ' + update;
  9661. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  9662. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  9663. }
  9664. const stackSnippet = stackNode.build( builder, 'void' );
  9665. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  9666. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  9667. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  9668. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  9669. }
  9670. builder.addFlowTab();
  9671. return returnsSnippet;
  9672. }
  9673. }
  9674. /**
  9675. * TSL function for creating a loop node.
  9676. *
  9677. * @function
  9678. * @param {...Any} params - A list of parameters.
  9679. * @returns {LoopNode}
  9680. */
  9681. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  9682. /**
  9683. * TSL function for creating a `Continue()` expression.
  9684. *
  9685. * @function
  9686. * @returns {ExpressionNode}
  9687. */
  9688. const Continue = () => expression( 'continue' ).append();
  9689. /**
  9690. * TSL function for creating a `Break()` expression.
  9691. *
  9692. * @function
  9693. * @returns {ExpressionNode}
  9694. */
  9695. const Break = () => expression( 'break' ).append();
  9696. //
  9697. const loop = ( ...params ) => { // @deprecated, r168
  9698. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  9699. return Loop( ...params );
  9700. };
  9701. /** @module MorphNode **/
  9702. const _morphTextures = /*@__PURE__*/ new WeakMap();
  9703. const _morphVec4 = /*@__PURE__*/ new Vector4();
  9704. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  9705. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  9706. const y = texelIndex.div( width );
  9707. const x = texelIndex.sub( y.mul( width ) );
  9708. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  9709. return bufferAttrib.mul( influence );
  9710. } );
  9711. function getEntry( geometry ) {
  9712. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  9713. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  9714. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  9715. // instead of using attributes, the WebGL 2 code path encodes morph targets
  9716. // into an array of data textures. Each layer represents a single morph target.
  9717. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  9718. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  9719. let entry = _morphTextures.get( geometry );
  9720. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  9721. if ( entry !== undefined ) entry.texture.dispose();
  9722. const morphTargets = geometry.morphAttributes.position || [];
  9723. const morphNormals = geometry.morphAttributes.normal || [];
  9724. const morphColors = geometry.morphAttributes.color || [];
  9725. let vertexDataCount = 0;
  9726. if ( hasMorphPosition === true ) vertexDataCount = 1;
  9727. if ( hasMorphNormals === true ) vertexDataCount = 2;
  9728. if ( hasMorphColors === true ) vertexDataCount = 3;
  9729. let width = geometry.attributes.position.count * vertexDataCount;
  9730. let height = 1;
  9731. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  9732. if ( width > maxTextureSize ) {
  9733. height = Math.ceil( width / maxTextureSize );
  9734. width = maxTextureSize;
  9735. }
  9736. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  9737. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  9738. bufferTexture.type = FloatType;
  9739. bufferTexture.needsUpdate = true;
  9740. // fill buffer
  9741. const vertexDataStride = vertexDataCount * 4;
  9742. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  9743. const morphTarget = morphTargets[ i ];
  9744. const morphNormal = morphNormals[ i ];
  9745. const morphColor = morphColors[ i ];
  9746. const offset = width * height * 4 * i;
  9747. for ( let j = 0; j < morphTarget.count; j ++ ) {
  9748. const stride = j * vertexDataStride;
  9749. if ( hasMorphPosition === true ) {
  9750. _morphVec4.fromBufferAttribute( morphTarget, j );
  9751. buffer[ offset + stride + 0 ] = _morphVec4.x;
  9752. buffer[ offset + stride + 1 ] = _morphVec4.y;
  9753. buffer[ offset + stride + 2 ] = _morphVec4.z;
  9754. buffer[ offset + stride + 3 ] = 0;
  9755. }
  9756. if ( hasMorphNormals === true ) {
  9757. _morphVec4.fromBufferAttribute( morphNormal, j );
  9758. buffer[ offset + stride + 4 ] = _morphVec4.x;
  9759. buffer[ offset + stride + 5 ] = _morphVec4.y;
  9760. buffer[ offset + stride + 6 ] = _morphVec4.z;
  9761. buffer[ offset + stride + 7 ] = 0;
  9762. }
  9763. if ( hasMorphColors === true ) {
  9764. _morphVec4.fromBufferAttribute( morphColor, j );
  9765. buffer[ offset + stride + 8 ] = _morphVec4.x;
  9766. buffer[ offset + stride + 9 ] = _morphVec4.y;
  9767. buffer[ offset + stride + 10 ] = _morphVec4.z;
  9768. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  9769. }
  9770. }
  9771. }
  9772. entry = {
  9773. count: morphTargetsCount,
  9774. texture: bufferTexture,
  9775. stride: vertexDataCount,
  9776. size: new Vector2( width, height )
  9777. };
  9778. _morphTextures.set( geometry, entry );
  9779. function disposeTexture() {
  9780. bufferTexture.dispose();
  9781. _morphTextures.delete( geometry );
  9782. geometry.removeEventListener( 'dispose', disposeTexture );
  9783. }
  9784. geometry.addEventListener( 'dispose', disposeTexture );
  9785. }
  9786. return entry;
  9787. }
  9788. /**
  9789. * This node implements the vertex transformation shader logic which is required
  9790. * for morph target animation.
  9791. *
  9792. * @augments Node
  9793. */
  9794. class MorphNode extends Node {
  9795. static get type() {
  9796. return 'MorphNode';
  9797. }
  9798. /**
  9799. * Constructs a new morph node.
  9800. *
  9801. * @param {Mesh} mesh - The mesh holding the morph targets.
  9802. */
  9803. constructor( mesh ) {
  9804. super( 'void' );
  9805. /**
  9806. * The mesh holding the morph targets.
  9807. *
  9808. * @type {Mesh}
  9809. */
  9810. this.mesh = mesh;
  9811. /**
  9812. * A uniform node which represents the morph base influence value.
  9813. *
  9814. * @type {UniformNode<float>}
  9815. */
  9816. this.morphBaseInfluence = uniform( 1 );
  9817. /**
  9818. * The update type overwritten since morph nodes are updated per object.
  9819. *
  9820. * @type {String}
  9821. */
  9822. this.updateType = NodeUpdateType.OBJECT;
  9823. }
  9824. /**
  9825. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  9826. *
  9827. * @param {NodeBuilder} builder - The current node builder.
  9828. */
  9829. setup( builder ) {
  9830. const { geometry } = builder;
  9831. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  9832. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  9833. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  9834. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  9835. // nodes
  9836. const { texture: bufferMap, stride, size } = getEntry( geometry );
  9837. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  9838. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  9839. const width = int( size.width );
  9840. Loop( morphTargetsCount, ( { i } ) => {
  9841. const influence = float( 0 ).toVar();
  9842. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  9843. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  9844. } else {
  9845. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  9846. }
  9847. if ( hasMorphPosition === true ) {
  9848. positionLocal.addAssign( getMorph( {
  9849. bufferMap,
  9850. influence,
  9851. stride,
  9852. width,
  9853. depth: i,
  9854. offset: int( 0 )
  9855. } ) );
  9856. }
  9857. if ( hasMorphNormals === true ) {
  9858. normalLocal.addAssign( getMorph( {
  9859. bufferMap,
  9860. influence,
  9861. stride,
  9862. width,
  9863. depth: i,
  9864. offset: int( 1 )
  9865. } ) );
  9866. }
  9867. } );
  9868. }
  9869. /**
  9870. * Updates the state of the morphed mesh by updating the base influence.
  9871. *
  9872. * @param {NodeFrame} frame - The current node frame.
  9873. */
  9874. update( /*frame*/ ) {
  9875. const morphBaseInfluence = this.morphBaseInfluence;
  9876. if ( this.mesh.geometry.morphTargetsRelative ) {
  9877. morphBaseInfluence.value = 1;
  9878. } else {
  9879. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  9880. }
  9881. }
  9882. }
  9883. /**
  9884. * TSL function for creating a morph node.
  9885. *
  9886. * @function
  9887. * @param {Mesh} mesh - The mesh holding the morph targets.
  9888. * @returns {MorphNode}
  9889. */
  9890. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  9891. /**
  9892. * Base class for lighting nodes.
  9893. *
  9894. * @augments Node
  9895. */
  9896. class LightingNode extends Node {
  9897. static get type() {
  9898. return 'LightingNode';
  9899. }
  9900. /**
  9901. * Constructs a new lighting node.
  9902. */
  9903. constructor() {
  9904. super( 'vec3' );
  9905. /**
  9906. * This flag can be used for type testing.
  9907. *
  9908. * @type {Boolean}
  9909. * @readonly
  9910. * @default true
  9911. */
  9912. this.isLightingNode = true;
  9913. }
  9914. }
  9915. /**
  9916. * A generic class that can be used by nodes which contribute
  9917. * ambient occlusion to the scene. E.g. an ambient occlusion map
  9918. * node can be used as input for this module. Used in {@link NodeMaterial}.
  9919. *
  9920. * @augments LightingNode
  9921. */
  9922. class AONode extends LightingNode {
  9923. static get type() {
  9924. return 'AONode';
  9925. }
  9926. /**
  9927. * Constructs a new AO node.
  9928. *
  9929. * @param {Node<float>?} [aoNode=null] - The ambient occlusion node.
  9930. */
  9931. constructor( aoNode = null ) {
  9932. super();
  9933. /**
  9934. * The ambient occlusion node.
  9935. *
  9936. * @type {Node<float>?}
  9937. * @default null
  9938. */
  9939. this.aoNode = aoNode;
  9940. }
  9941. setup( builder ) {
  9942. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  9943. }
  9944. }
  9945. /**
  9946. * `LightingContextNode` represents an extension of the {@link module:ContextNode~ContextNode} module
  9947. * by adding lighting specific context data. It represents the runtime context of
  9948. * {@link LightsNode}.
  9949. *
  9950. * @augments ContextNode
  9951. */
  9952. class LightingContextNode extends ContextNode {
  9953. static get type() {
  9954. return 'LightingContextNode';
  9955. }
  9956. /**
  9957. * Constructs a new lighting context node.
  9958. *
  9959. * @param {LightsNode} node - The lights node.
  9960. * @param {LightingModel?} [lightingModel=null] - The current lighting model.
  9961. * @param {Node<vec3>?} [backdropNode=null] - A backdrop node.
  9962. * @param {Node<float>?} [backdropAlphaNode=null] - A backdrop alpha node.
  9963. */
  9964. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  9965. super( node );
  9966. /**
  9967. * The current lighting model.
  9968. *
  9969. * @type {LightingModel?}
  9970. * @default null
  9971. */
  9972. this.lightingModel = lightingModel;
  9973. /**
  9974. * A backdrop node.
  9975. *
  9976. * @type {Node<vec3>?}
  9977. * @default null
  9978. */
  9979. this.backdropNode = backdropNode;
  9980. /**
  9981. * A backdrop alpha node.
  9982. *
  9983. * @type {Node<float>?}
  9984. * @default null
  9985. */
  9986. this.backdropAlphaNode = backdropAlphaNode;
  9987. this._value = null;
  9988. }
  9989. /**
  9990. * Returns a lighting context object.
  9991. *
  9992. * @return {{
  9993. * radiance: Node<vec3>,
  9994. * irradiance: Node<vec3>,
  9995. * iblIrradiance: Node<vec3>,
  9996. * ambientOcclusion: Node<float>,
  9997. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  9998. * backdrop: Node<vec3>,
  9999. * backdropAlpha: Node<float>
  10000. * }} The lighting context object.
  10001. */
  10002. getContext() {
  10003. const { backdropNode, backdropAlphaNode } = this;
  10004. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  10005. directSpecular = vec3().toVar( 'directSpecular' ),
  10006. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  10007. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  10008. const reflectedLight = {
  10009. directDiffuse,
  10010. directSpecular,
  10011. indirectDiffuse,
  10012. indirectSpecular
  10013. };
  10014. const context = {
  10015. radiance: vec3().toVar( 'radiance' ),
  10016. irradiance: vec3().toVar( 'irradiance' ),
  10017. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  10018. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  10019. reflectedLight,
  10020. backdrop: backdropNode,
  10021. backdropAlpha: backdropAlphaNode
  10022. };
  10023. return context;
  10024. }
  10025. setup( builder ) {
  10026. this.value = this._value || ( this._value = this.getContext() );
  10027. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  10028. return super.setup( builder );
  10029. }
  10030. }
  10031. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  10032. /**
  10033. * A generic class that can be used by nodes which contribute
  10034. * irradiance to the scene. E.g. a light map node can be used
  10035. * as input for this module. Used in {@link NodeMaterial}.
  10036. *
  10037. * @augments LightingNode
  10038. */
  10039. class IrradianceNode extends LightingNode {
  10040. static get type() {
  10041. return 'IrradianceNode';
  10042. }
  10043. /**
  10044. * Constructs a new irradiance node.
  10045. *
  10046. * @param {Node<vec3>} node - A node contributing irradiance.
  10047. */
  10048. constructor( node ) {
  10049. super();
  10050. /**
  10051. * A node contributing irradiance.
  10052. *
  10053. * @type {Node<vec3>}
  10054. */
  10055. this.node = node;
  10056. }
  10057. setup( builder ) {
  10058. builder.context.irradiance.addAssign( this.node );
  10059. }
  10060. }
  10061. /** @module ScreenNode **/
  10062. let screenSizeVec, viewportVec;
  10063. /**
  10064. * This node provides a collection of screen related metrics.
  10065. * Depending on {@link module:ScreenNode~ScreenNode#scope}, the nodes can represent
  10066. * resolution or viewport data as well as fragment or uv coordinates.
  10067. *
  10068. * @augments Node
  10069. */
  10070. class ScreenNode extends Node {
  10071. static get type() {
  10072. return 'ScreenNode';
  10073. }
  10074. /**
  10075. * Constructs a new screen node.
  10076. *
  10077. * @param {('coordinate'|'viewport'|'size'|'uv')} scope - The node's scope.
  10078. */
  10079. constructor( scope ) {
  10080. super();
  10081. /**
  10082. * The node represents different metric depending on which scope is selected.
  10083. *
  10084. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  10085. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  10086. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  10087. * - `ScreenNode.UV`: Normalized coordinates.
  10088. *
  10089. * @type {('coordinate'|'viewport'|'size'|'uv')}
  10090. */
  10091. this.scope = scope;
  10092. /**
  10093. * This flag can be used for type testing.
  10094. *
  10095. * @type {Boolean}
  10096. * @readonly
  10097. * @default true
  10098. */
  10099. this.isViewportNode = true;
  10100. }
  10101. /**
  10102. * This method is overwritten since the node type depends on the selected scope.
  10103. *
  10104. * @return {('vec2'|'vec4')} The node type.
  10105. */
  10106. getNodeType() {
  10107. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  10108. else return 'vec2';
  10109. }
  10110. /**
  10111. * This method is overwritten since the node's update type depends on the selected scope.
  10112. *
  10113. * @return {NodeUpdateType} The update type.
  10114. */
  10115. getUpdateType() {
  10116. let updateType = NodeUpdateType.NONE;
  10117. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  10118. updateType = NodeUpdateType.RENDER;
  10119. }
  10120. this.updateType = updateType;
  10121. return updateType;
  10122. }
  10123. /**
  10124. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  10125. * from the current renderer.
  10126. *
  10127. * @param {NodeFrame} frame - A reference to the current node frame.
  10128. */
  10129. update( { renderer } ) {
  10130. const renderTarget = renderer.getRenderTarget();
  10131. if ( this.scope === ScreenNode.VIEWPORT ) {
  10132. if ( renderTarget !== null ) {
  10133. viewportVec.copy( renderTarget.viewport );
  10134. } else {
  10135. renderer.getViewport( viewportVec );
  10136. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  10137. }
  10138. } else {
  10139. if ( renderTarget !== null ) {
  10140. screenSizeVec.width = renderTarget.width;
  10141. screenSizeVec.height = renderTarget.height;
  10142. } else {
  10143. renderer.getDrawingBufferSize( screenSizeVec );
  10144. }
  10145. }
  10146. }
  10147. setup( /*builder*/ ) {
  10148. const scope = this.scope;
  10149. let output = null;
  10150. if ( scope === ScreenNode.SIZE ) {
  10151. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  10152. } else if ( scope === ScreenNode.VIEWPORT ) {
  10153. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  10154. } else {
  10155. output = vec2( screenCoordinate.div( screenSize ) );
  10156. }
  10157. return output;
  10158. }
  10159. generate( builder ) {
  10160. if ( this.scope === ScreenNode.COORDINATE ) {
  10161. let coord = builder.getFragCoord();
  10162. if ( builder.isFlipY() ) {
  10163. // follow webgpu standards
  10164. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  10165. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  10166. }
  10167. return coord;
  10168. }
  10169. return super.generate( builder );
  10170. }
  10171. }
  10172. ScreenNode.COORDINATE = 'coordinate';
  10173. ScreenNode.VIEWPORT = 'viewport';
  10174. ScreenNode.SIZE = 'size';
  10175. ScreenNode.UV = 'uv';
  10176. // Screen
  10177. /**
  10178. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  10179. *
  10180. * @type {ScreenNode<vec2>}
  10181. */
  10182. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  10183. /**
  10184. * TSL object that represents the screen resolution in physical pixel units.
  10185. *
  10186. * @type {ScreenNode<vec2>}
  10187. */
  10188. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  10189. /**
  10190. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  10191. *
  10192. * @type {ScreenNode<vec2>}
  10193. */
  10194. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  10195. // Viewport
  10196. /**
  10197. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  10198. *
  10199. * @type {ScreenNode<vec4>}
  10200. */
  10201. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  10202. /**
  10203. * TSL object that represents the viewport resolution in physical pixel units.
  10204. *
  10205. * @type {ScreenNode<vec2>}
  10206. */
  10207. const viewportSize = viewport.zw;
  10208. /**
  10209. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  10210. *
  10211. * @type {ScreenNode<vec2>}
  10212. */
  10213. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  10214. /**
  10215. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  10216. *
  10217. * @type {ScreenNode<vec2>}
  10218. */
  10219. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  10220. // Deprecated
  10221. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  10222. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  10223. return screenSize;
  10224. }, 'vec2' ).once() )();
  10225. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  10226. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  10227. return screenUV;
  10228. }, 'vec2' ).once() )();
  10229. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  10230. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  10231. return screenUV.flipY();
  10232. }, 'vec2' ).once() )();
  10233. /** @module ViewportTextureNode **/
  10234. const _size$4 = /*@__PURE__*/ new Vector2();
  10235. /**
  10236. * A special type of texture node which represents the data of the current viewport
  10237. * as a texture. The module extracts data from the current bound framebuffer with
  10238. * a copy operation so no extra render pass is required to produce the texture data
  10239. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  10240. * variety of effects like refractive or transmissive materials.
  10241. *
  10242. * @augments module:TextureNode~TextureNode
  10243. */
  10244. class ViewportTextureNode extends TextureNode {
  10245. static get type() {
  10246. return 'ViewportTextureNode';
  10247. }
  10248. /**
  10249. * Constructs a new viewport texture node.
  10250. *
  10251. * @param {Node} [uvNode=screenUV] - The uv node.
  10252. * @param {Node?} [levelNode=null] - The level node.
  10253. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10254. */
  10255. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  10256. if ( framebufferTexture === null ) {
  10257. framebufferTexture = new FramebufferTexture();
  10258. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  10259. }
  10260. super( framebufferTexture, uvNode, levelNode );
  10261. /**
  10262. * Whether to generate mipmaps or not.
  10263. *
  10264. * @type {Boolean}
  10265. * @default false
  10266. */
  10267. this.generateMipmaps = false;
  10268. /**
  10269. * This flag can be used for type testing.
  10270. *
  10271. * @type {Boolean}
  10272. * @readonly
  10273. * @default true
  10274. */
  10275. this.isOutputTextureNode = true;
  10276. /**
  10277. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  10278. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  10279. *
  10280. * @type {String}
  10281. * @default 'frame'
  10282. */
  10283. this.updateBeforeType = NodeUpdateType.FRAME;
  10284. }
  10285. updateBefore( frame ) {
  10286. const renderer = frame.renderer;
  10287. renderer.getDrawingBufferSize( _size$4 );
  10288. //
  10289. const framebufferTexture = this.value;
  10290. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  10291. framebufferTexture.image.width = _size$4.width;
  10292. framebufferTexture.image.height = _size$4.height;
  10293. framebufferTexture.needsUpdate = true;
  10294. }
  10295. //
  10296. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  10297. framebufferTexture.generateMipmaps = this.generateMipmaps;
  10298. renderer.copyFramebufferToTexture( framebufferTexture );
  10299. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  10300. }
  10301. clone() {
  10302. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  10303. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  10304. return viewportTextureNode;
  10305. }
  10306. }
  10307. /**
  10308. * TSL function for creating a viewport texture node.
  10309. *
  10310. * @function
  10311. * @param {Node} [uvNode=screenUV] - The uv node.
  10312. * @param {Node?} [levelNode=null] - The level node.
  10313. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10314. * @returns {ViewportTextureNode}
  10315. */
  10316. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  10317. /**
  10318. * TSL function for creating a viewport texture node with enabled mipmap generation.
  10319. *
  10320. * @function
  10321. * @param {Node} [uvNode=screenUV] - The uv node.
  10322. * @param {Node?} [levelNode=null] - The level node.
  10323. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10324. * @returns {ViewportTextureNode}
  10325. */
  10326. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  10327. /** @module ViewportDepthTextureNode **/
  10328. let sharedDepthbuffer = null;
  10329. /**
  10330. * Represents the depth of the current viewport as a texture. This module
  10331. * can be used in combination with viewport texture to achieve effects
  10332. * that require depth evaluation.
  10333. *
  10334. * @augments module:ViewportTextureNode~ViewportTextureNode
  10335. */
  10336. class ViewportDepthTextureNode extends ViewportTextureNode {
  10337. static get type() {
  10338. return 'ViewportDepthTextureNode';
  10339. }
  10340. /**
  10341. * Constructs a new viewport depth texture node.
  10342. *
  10343. * @param {Node} [uvNode=screenUV] - The uv node.
  10344. * @param {Node?} [levelNode=null] - The level node.
  10345. */
  10346. constructor( uvNode = screenUV, levelNode = null ) {
  10347. if ( sharedDepthbuffer === null ) {
  10348. sharedDepthbuffer = new DepthTexture();
  10349. }
  10350. super( uvNode, levelNode, sharedDepthbuffer );
  10351. }
  10352. }
  10353. /**
  10354. * TSL function for a viewport depth texture node.
  10355. *
  10356. * @function
  10357. * @param {Node} [uvNode=screenUV] - The uv node.
  10358. * @param {Node?} [levelNode=null] - The level node.
  10359. * @returns {ViewportDepthTextureNode}
  10360. */
  10361. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  10362. /** @module ViewportDepthNode **/
  10363. /**
  10364. * This node offers a collection of features in context of the depth logic in the fragment shader.
  10365. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  10366. * fragment or for depth evaluation purposes.
  10367. *
  10368. * @augments Node
  10369. */
  10370. class ViewportDepthNode extends Node {
  10371. static get type() {
  10372. return 'ViewportDepthNode';
  10373. }
  10374. /**
  10375. * Constructs a new viewport depth node.
  10376. *
  10377. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  10378. * @param {Node?} [valueNode=null] - The value node.
  10379. */
  10380. constructor( scope, valueNode = null ) {
  10381. super( 'float' );
  10382. /**
  10383. * The node behaves differently depending on which scope is selected.
  10384. *
  10385. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  10386. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  10387. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  10388. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  10389. *
  10390. * @type {('depth'|'depthBase'|'linearDepth')}
  10391. */
  10392. this.scope = scope;
  10393. /**
  10394. * Can be used to define a custom depth value.
  10395. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  10396. *
  10397. * @type {Node?}
  10398. * @default null
  10399. */
  10400. this.valueNode = valueNode;
  10401. /**
  10402. * This flag can be used for type testing.
  10403. *
  10404. * @type {Boolean}
  10405. * @readonly
  10406. * @default true
  10407. */
  10408. this.isViewportDepthNode = true;
  10409. }
  10410. generate( builder ) {
  10411. const { scope } = this;
  10412. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  10413. return builder.getFragDepth();
  10414. }
  10415. return super.generate( builder );
  10416. }
  10417. setup( { camera } ) {
  10418. const { scope } = this;
  10419. const value = this.valueNode;
  10420. let node = null;
  10421. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  10422. if ( value !== null ) {
  10423. node = depthBase().assign( value );
  10424. }
  10425. } else if ( scope === ViewportDepthNode.DEPTH ) {
  10426. if ( camera.isPerspectiveCamera ) {
  10427. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  10428. } else {
  10429. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  10430. }
  10431. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  10432. if ( value !== null ) {
  10433. if ( camera.isPerspectiveCamera ) {
  10434. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  10435. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  10436. } else {
  10437. node = value;
  10438. }
  10439. } else {
  10440. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  10441. }
  10442. }
  10443. return node;
  10444. }
  10445. }
  10446. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  10447. ViewportDepthNode.DEPTH = 'depth';
  10448. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  10449. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  10450. /**
  10451. * TSL function for converting a viewZ value to an orthographic depth value.
  10452. *
  10453. * @function
  10454. * @param {Node<float>} viewZ - The viewZ node.
  10455. * @param {Node<float>} near - The camera's near value.
  10456. * @param {Node<float>} far - The camera's far value.
  10457. * @returns {Node<float>}
  10458. */
  10459. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  10460. /**
  10461. * TSL function for converting an orthographic depth value to a viewZ value.
  10462. *
  10463. * @function
  10464. * @param {Node<float>} depth - The orthographic depth.
  10465. * @param {Node<float>} near - The camera's near value.
  10466. * @param {Node<float>} far - The camera's far value.
  10467. * @returns {Node<float>}
  10468. */
  10469. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  10470. /**
  10471. * TSL function for converting a viewZ value to a perspective depth value.
  10472. *
  10473. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  10474. *
  10475. * @function
  10476. * @param {Node<float>} viewZ - The viewZ node.
  10477. * @param {Node<float>} near - The camera's near value.
  10478. * @param {Node<float>} far - The camera's far value.
  10479. * @returns {Node<float>}
  10480. */
  10481. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  10482. /**
  10483. * TSL function for converting a perspective depth value to a viewZ value.
  10484. *
  10485. * @function
  10486. * @param {Node<float>} depth - The perspective depth.
  10487. * @param {Node<float>} near - The camera's near value.
  10488. * @param {Node<float>} far - The camera's far value.
  10489. * @returns {Node<float>}
  10490. */
  10491. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  10492. /**
  10493. * TSL function for converting a viewZ value to a logarithmic depth value.
  10494. *
  10495. * @function
  10496. * @param {Node<float>} viewZ - The viewZ node.
  10497. * @param {Node<float>} near - The camera's near value.
  10498. * @param {Node<float>} far - The camera's far value.
  10499. * @returns {Node<float>}
  10500. */
  10501. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  10502. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  10503. // The final logarithmic depth formula used here is adapted from one described in an
  10504. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  10505. // which was an improvement upon an earlier formula one described in an
  10506. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  10507. // Ulrich's formula is the following:
  10508. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  10509. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  10510. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  10511. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  10512. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  10513. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  10514. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  10515. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  10516. // be used, and ultimately Ulrich's "near plane" version was chosen.
  10517. // Outerra eventually made another improvement to their original "C-constant" variant,
  10518. // but it still does not incorporate the camera near plane (for this version,
  10519. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  10520. // Here we make 4 changes to Ulrich's formula:
  10521. // 1. Clamp the camera near plane so we don't divide by 0.
  10522. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  10523. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  10524. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  10525. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  10526. // so we do the same here, hence the 'viewZ.negate()' call.
  10527. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  10528. near = near.max( 1e-6 ).toVar();
  10529. const numerator = log2( viewZ.negate().div( near ) );
  10530. const denominator = log2( far.div( near ) );
  10531. return numerator.div( denominator );
  10532. };
  10533. /**
  10534. * TSL function for converting a logarithmic depth value to a viewZ value.
  10535. *
  10536. * @function
  10537. * @param {Node<float>} depth - The logarithmic depth.
  10538. * @param {Node<float>} near - The camera's near value.
  10539. * @param {Node<float>} far - The camera's far value.
  10540. * @returns {Node<float>}
  10541. */
  10542. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  10543. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  10544. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  10545. // a negative viewZ).
  10546. const exponent = depth.mul( log( far.div( near ) ) );
  10547. return float( Math.E ).pow( exponent ).mul( near ).negate();
  10548. };
  10549. /**
  10550. * TSL function for defining a value for the current fragment's depth.
  10551. *
  10552. * @function
  10553. * @param {Node<float>} value - The depth value to set.
  10554. * @returns {ViewportDepthNode<float>}
  10555. */
  10556. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  10557. /**
  10558. * TSL object that represents the depth value for the current fragment.
  10559. *
  10560. * @type {ViewportDepthNode}
  10561. */
  10562. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  10563. /**
  10564. * TSL function for converting a perspective depth value to linear depth.
  10565. *
  10566. * @function
  10567. * @param {Node<float>} value - The perspective depth.
  10568. * @returns {ViewportDepthNode<float>}
  10569. */
  10570. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  10571. /**
  10572. * TSL object that represents the linear (orthographic) depth value of the current fragment
  10573. *
  10574. * @type {ViewportDepthNode}
  10575. */
  10576. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  10577. depth.assign = ( value ) => depthBase( value );
  10578. /** @module BuiltinNode **/
  10579. /**
  10580. * The node allows to set values for built-in shader variables. That is
  10581. * required for features like hardware-accelerated vertex clipping.
  10582. *
  10583. * @augments Node
  10584. */
  10585. class BuiltinNode extends Node {
  10586. /**
  10587. * Constructs a new builtin node.
  10588. *
  10589. * @param {String} name - The name of the built-in shader variable.
  10590. */
  10591. constructor( name ) {
  10592. super( 'float' );
  10593. /**
  10594. * The name of the built-in shader variable.
  10595. *
  10596. * @type {String}
  10597. */
  10598. this.name = name;
  10599. /**
  10600. * This flag can be used for type testing.
  10601. *
  10602. * @type {Boolean}
  10603. * @readonly
  10604. * @default true
  10605. */
  10606. this.isBuiltinNode = true;
  10607. }
  10608. /**
  10609. * Generates the code snippet of the builtin node.
  10610. *
  10611. * @param {NodeBuilder} builder - The current node builder.
  10612. * @return {String} The generated code snippet.
  10613. */
  10614. generate( /* builder */ ) {
  10615. return this.name;
  10616. }
  10617. }
  10618. /**
  10619. * TSL function for creating a builtin node.
  10620. *
  10621. * @function
  10622. * @param {String} name - The name of the built-in shader variable.
  10623. * @returns {BuiltinNode}
  10624. */
  10625. const builtin = nodeProxy( BuiltinNode );
  10626. /** @module ClippingNode **/
  10627. /**
  10628. * ```
  10629. * This node is used in {@link NodeMaterial} to setup the clipping
  10630. * which can happen hardware-accelerated (if supported) and optionally
  10631. * use alpha-to-coverage for anti-aliasing clipped edges.
  10632. * ```
  10633. * @augments Node
  10634. */
  10635. class ClippingNode extends Node {
  10636. static get type() {
  10637. return 'ClippingNode';
  10638. }
  10639. /**
  10640. * Constructs a new clipping node.
  10641. *
  10642. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  10643. * the selected scope influences the behavior of the node and what type of code is generated.
  10644. */
  10645. constructor( scope = ClippingNode.DEFAULT ) {
  10646. super();
  10647. /**
  10648. * The node's scope. Similar to other nodes, the selected scope influences
  10649. * the behavior of the node and what type of code is generated.
  10650. *
  10651. * @type {('default'|'hardware'|'alphaToCoverage')}
  10652. */
  10653. this.scope = scope;
  10654. }
  10655. /**
  10656. * Setups the node depending on the selected scope.
  10657. *
  10658. * @param {NodeBuilder} builder - The current node builder.
  10659. * @return {Node} The result node.
  10660. */
  10661. setup( builder ) {
  10662. super.setup( builder );
  10663. const clippingContext = builder.clippingContext;
  10664. const { intersectionPlanes, unionPlanes } = clippingContext;
  10665. this.hardwareClipping = builder.material.hardwareClipping;
  10666. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  10667. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  10668. } else if ( this.scope === ClippingNode.HARDWARE ) {
  10669. return this.setupHardwareClipping( unionPlanes, builder );
  10670. } else {
  10671. return this.setupDefault( intersectionPlanes, unionPlanes );
  10672. }
  10673. }
  10674. /**
  10675. * Setups alpha to coverage.
  10676. *
  10677. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  10678. * @param {Array<Vector4>} unionPlanes - The union planes.
  10679. * @return {Node} The result node.
  10680. */
  10681. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  10682. return Fn( () => {
  10683. const distanceToPlane = float().toVar( 'distanceToPlane' );
  10684. const distanceGradient = float().toVar( 'distanceToGradient' );
  10685. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  10686. const numUnionPlanes = unionPlanes.length;
  10687. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  10688. const clippingPlanes = uniformArray( unionPlanes );
  10689. Loop( numUnionPlanes, ( { i } ) => {
  10690. const plane = clippingPlanes.element( i );
  10691. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  10692. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  10693. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  10694. } );
  10695. }
  10696. const numIntersectionPlanes = intersectionPlanes.length;
  10697. if ( numIntersectionPlanes > 0 ) {
  10698. const clippingPlanes = uniformArray( intersectionPlanes );
  10699. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  10700. Loop( numIntersectionPlanes, ( { i } ) => {
  10701. const plane = clippingPlanes.element( i );
  10702. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  10703. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  10704. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  10705. } );
  10706. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  10707. }
  10708. diffuseColor.a.mulAssign( clipOpacity );
  10709. diffuseColor.a.equal( 0.0 ).discard();
  10710. } )();
  10711. }
  10712. /**
  10713. * Setups the default clipping.
  10714. *
  10715. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  10716. * @param {Array<Vector4>} unionPlanes - The union planes.
  10717. * @return {Node} The result node.
  10718. */
  10719. setupDefault( intersectionPlanes, unionPlanes ) {
  10720. return Fn( () => {
  10721. const numUnionPlanes = unionPlanes.length;
  10722. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  10723. const clippingPlanes = uniformArray( unionPlanes );
  10724. Loop( numUnionPlanes, ( { i } ) => {
  10725. const plane = clippingPlanes.element( i );
  10726. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  10727. } );
  10728. }
  10729. const numIntersectionPlanes = intersectionPlanes.length;
  10730. if ( numIntersectionPlanes > 0 ) {
  10731. const clippingPlanes = uniformArray( intersectionPlanes );
  10732. const clipped = bool( true ).toVar( 'clipped' );
  10733. Loop( numIntersectionPlanes, ( { i } ) => {
  10734. const plane = clippingPlanes.element( i );
  10735. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  10736. } );
  10737. clipped.discard();
  10738. }
  10739. } )();
  10740. }
  10741. /**
  10742. * Setups hardware clipping.
  10743. *
  10744. * @param {Array<Vector4>} unionPlanes - The union planes.
  10745. * @param {NodeBuilder} builder - The current node builder.
  10746. * @return {Node} The result node.
  10747. */
  10748. setupHardwareClipping( unionPlanes, builder ) {
  10749. const numUnionPlanes = unionPlanes.length;
  10750. builder.enableHardwareClipping( numUnionPlanes );
  10751. return Fn( () => {
  10752. const clippingPlanes = uniformArray( unionPlanes );
  10753. const hw_clip_distances = builtin( builder.getClipDistance() );
  10754. Loop( numUnionPlanes, ( { i } ) => {
  10755. const plane = clippingPlanes.element( i );
  10756. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  10757. hw_clip_distances.element( i ).assign( distance );
  10758. } );
  10759. } )();
  10760. }
  10761. }
  10762. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  10763. ClippingNode.DEFAULT = 'default';
  10764. ClippingNode.HARDWARE = 'hardware';
  10765. /**
  10766. * TSL function for setting up the default clipping logic.
  10767. *
  10768. * @function
  10769. * @returns {ClippingNode}
  10770. */
  10771. const clipping = () => nodeObject( new ClippingNode() );
  10772. /**
  10773. * TSL function for setting up alpha to coverage.
  10774. *
  10775. * @function
  10776. * @returns {ClippingNode}
  10777. */
  10778. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  10779. /**
  10780. * TSL function for setting up hardware-based clipping.
  10781. *
  10782. * @function
  10783. * @returns {ClippingNode}
  10784. */
  10785. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  10786. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  10787. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  10788. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  10789. 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 ) ) ) ) ) );
  10790. } );
  10791. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  10792. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  10793. } );
  10794. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  10795. // Find the discretized derivatives of our coordinates
  10796. const maxDeriv = max$1(
  10797. length( dFdx( position.xyz ) ),
  10798. length( dFdy( position.xyz ) )
  10799. );
  10800. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  10801. // Find two nearest log-discretized noise scales
  10802. const pixScales = vec2(
  10803. exp2( floor( log2( pixScale ) ) ),
  10804. exp2( ceil( log2( pixScale ) ) )
  10805. );
  10806. // Compute alpha thresholds at our two noise scales
  10807. const alpha = vec2(
  10808. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  10809. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  10810. );
  10811. // Factor to interpolate lerp with
  10812. const lerpFactor = fract( log2( pixScale ) );
  10813. // Interpolate alpha threshold from noise at two scales
  10814. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  10815. // Pass into CDF to compute uniformly distrib threshold
  10816. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  10817. const cases = vec3(
  10818. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  10819. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  10820. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  10821. // Find our final, uniformly distributed alpha threshold (ατ)
  10822. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  10823. // Avoids ατ == 0. Could also do ατ =1-ατ
  10824. return clamp( threshold, 1.0e-6, 1.0 );
  10825. } ).setLayout( {
  10826. name: 'getAlphaHashThreshold',
  10827. type: 'float',
  10828. inputs: [
  10829. { name: 'position', type: 'vec3' }
  10830. ]
  10831. } );
  10832. /**
  10833. * Base class for all node materials.
  10834. *
  10835. * @augments Material
  10836. */
  10837. class NodeMaterial extends Material {
  10838. static get type() {
  10839. return 'NodeMaterial';
  10840. }
  10841. /**
  10842. * Represents the type of the node material.
  10843. *
  10844. * @type {String}
  10845. */
  10846. get type() {
  10847. return this.constructor.type;
  10848. }
  10849. set type( _value ) { /* */ }
  10850. /**
  10851. * Constructs a new node material.
  10852. */
  10853. constructor() {
  10854. super();
  10855. /**
  10856. * This flag can be used for type testing.
  10857. *
  10858. * @type {Boolean}
  10859. * @readonly
  10860. * @default true
  10861. */
  10862. this.isNodeMaterial = true;
  10863. /**
  10864. * Whether this material is affected by fog or not.
  10865. *
  10866. * @type {Boolean}
  10867. * @default true
  10868. */
  10869. this.fog = true;
  10870. /**
  10871. * Whether this material is affected by lights or not.
  10872. *
  10873. * @type {Boolean}
  10874. * @default false
  10875. */
  10876. this.lights = false;
  10877. /**
  10878. * Whether this material uses hardware clipping or not.
  10879. * This property is managed by the engine and should not be
  10880. * modified by apps.
  10881. *
  10882. * @type {Boolean}
  10883. * @default false
  10884. */
  10885. this.hardwareClipping = false;
  10886. /**
  10887. * Node materials which set their `lights` property to `true`
  10888. * are affected by all lights of the scene. Sometimes selective
  10889. * lighting is wanted which means only _some_ lights in the scene
  10890. * affect a material. This can be achieved by creating an instance
  10891. * of {@link module:LightsNode~LightsNode} with a list of selective
  10892. * lights and assign the node to this property.
  10893. *
  10894. * ```js
  10895. * const customLightsNode = lights( [ light1, light2 ] );
  10896. * material.lightsNode = customLightsNode;
  10897. * ```
  10898. *
  10899. * @type {LightsNode?}
  10900. * @default null
  10901. */
  10902. this.lightsNode = null;
  10903. /**
  10904. * The environment of node materials can be defined by an environment
  10905. * map assigned to the `envMap` property or by `Scene.environment`
  10906. * if the node material is a PBR material. This node property allows to overwrite
  10907. * the default behavior and define the environment with a custom node.
  10908. *
  10909. * ```js
  10910. * material.envNode = pmremTexture( renderTarget.texture );
  10911. * ```
  10912. *
  10913. * @type {Node<vec3>?}
  10914. * @default null
  10915. */
  10916. this.envNode = null;
  10917. /**
  10918. * The lighting of node materials might be influenced by ambient occlusion.
  10919. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  10920. * and the respective `aoMapIntensity`. This node property allows to overwrite
  10921. * the default and define the ambient occlusion with a custom node instead.
  10922. *
  10923. * If you don't want to overwrite the diffuse color but modify the existing
  10924. * values instead, use {@link module:MaterialNode.materialAO}.
  10925. *
  10926. * @type {Node<float>?}
  10927. * @default null
  10928. */
  10929. this.aoNode = null;
  10930. /**
  10931. * The diffuse color of node materials is by default inferred from the
  10932. * `color` and `map` properties. This node property allows to overwrite the default
  10933. * and define the diffuse color with a node instead.
  10934. *
  10935. * ```js
  10936. * material.colorNode = color( 0xff0000 ); // define red color
  10937. * ```
  10938. *
  10939. * If you don't want to overwrite the diffuse color but modify the existing
  10940. * values instead, use {@link module:MaterialNode.materialColor}.
  10941. *
  10942. * ```js
  10943. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  10944. * ```
  10945. *
  10946. * @type {Node<vec3>?}
  10947. * @default null
  10948. */
  10949. this.colorNode = null;
  10950. /**
  10951. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  10952. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  10953. * and define the normals with a node instead.
  10954. *
  10955. * If you don't want to overwrite the normals but modify the existing values instead,
  10956. * use {@link module:MaterialNode.materialNormal}.
  10957. *
  10958. * @type {Node<vec3>?}
  10959. * @default null
  10960. */
  10961. this.normalNode = null;
  10962. /**
  10963. * The opacity of node materials is by default inferred from the `opacity`
  10964. * and `alphaMap` properties. This node property allows to overwrite the default
  10965. * and define the opacity with a node instead.
  10966. *
  10967. * If you don't want to overwrite the normals but modify the existing
  10968. * value instead, use {@link module:MaterialNode.materialOpacity}.
  10969. *
  10970. * @type {Node<float>?}
  10971. * @default null
  10972. */
  10973. this.opacityNode = null;
  10974. /**
  10975. * This node can be used to to implement a variety of filter-like effects. The idea is
  10976. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  10977. * to create an arbitrary effect and then assign the node composition to this property.
  10978. * Everything behind the object using this material will now be affected by a filter.
  10979. *
  10980. * ```js
  10981. * const material = new NodeMaterial()
  10982. * material.transparent = true;
  10983. *
  10984. * // everything behind the object will be monochromatic
  10985. * material.backdropNode = viewportSharedTexture().rgb.saturation( 0 );
  10986. * ```
  10987. *
  10988. * Backdrop computations are part of the lighting so only lit materials can use this property.
  10989. *
  10990. * @type {Node<vec3>?}
  10991. * @default null
  10992. */
  10993. this.backdropNode = null;
  10994. /**
  10995. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  10996. *
  10997. * @type {Node<float>?}
  10998. * @default null
  10999. */
  11000. this.backdropAlphaNode = null;
  11001. /**
  11002. * The alpha test of node materials is by default inferred from the `alphaTest`
  11003. * property. This node property allows to overwrite the default and define the
  11004. * alpha test with a node instead.
  11005. *
  11006. * If you don't want to overwrite the alpha test but modify the existing
  11007. * value instead, use {@link module:MaterialNode.materialAlphaTest}.
  11008. *
  11009. * @type {Node<float>?}
  11010. * @default null
  11011. */
  11012. this.alphaTestNode = null;
  11013. /**
  11014. * The local vertex positions are computed based on multiple factors like the
  11015. * attribute data, morphing or skinning. This node property allows to overwrite
  11016. * the default and define local vertex positions with nodes instead.
  11017. *
  11018. * If you don't want to overwrite the vertex positions but modify the existing
  11019. * values instead, use {@link module:Position.positionLocal}.
  11020. *
  11021. *```js
  11022. * material.positionNode = positionLocal.add( displace );
  11023. * ```
  11024. *
  11025. * @type {Node<vec3>?}
  11026. * @default null
  11027. */
  11028. this.positionNode = null;
  11029. /**
  11030. * This node property is intended for logic which modifies geometry data once or per animation step.
  11031. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  11032. * `geometryNode` is intended as a dedicated API so there is an intended spot where goemetry modiciations
  11033. * can be implemented.
  11034. *
  11035. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  11036. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  11037. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  11038. * eventually assigned to `geometryNode`.
  11039. *
  11040. * @type {Function}
  11041. * @default null
  11042. */
  11043. this.geometryNode = null;
  11044. /**
  11045. * Allows to overwrite depth values in the fragment shader.
  11046. *
  11047. * @type {Node<float>?}
  11048. * @default null
  11049. */
  11050. this.depthNode = null;
  11051. /**
  11052. * Allows to overwrite the position used for shadow map rendering which
  11053. * is by default {@link module:Position.positionWorld}, the vertex position
  11054. * in world space.
  11055. *
  11056. * @type {Node<float>?}
  11057. * @default null
  11058. */
  11059. this.shadowPositionNode = null;
  11060. /**
  11061. * This node can be used to influence how an object using this node material
  11062. * receive shadows.
  11063. *
  11064. * ```js
  11065. * const totalShadows = float( 1 ).toVar();
  11066. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  11067. * totalShadows.mulAssign( shadow );
  11068. * //return float( 1 ); // bypass received shadows
  11069. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  11070. * } );
  11071. *
  11072. * @type {Node<vec4>?}
  11073. * @default null
  11074. */
  11075. this.receivedShadowNode = null;
  11076. /**
  11077. * This node can be used to influence how an object using this node material
  11078. * casts shadows. To apply a color to shadows, you can simply do:
  11079. *
  11080. * ```js
  11081. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  11082. * ```
  11083. *
  11084. * Which can be nice to fake colored shadows of semi-transparent objects. It
  11085. * is also common to use the property with `Fn` function so checks are performed
  11086. * per fragment.
  11087. *
  11088. * ```js
  11089. * materialCustomShadow.castShadowNode = Fn( () => {
  11090. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  11091. * return materialColor;
  11092. * } )();
  11093. * ```
  11094. *
  11095. * @type {Node<vec4>?}
  11096. * @default null
  11097. */
  11098. this.castShadowNode = null;
  11099. /**
  11100. * This node can be used to define the final output of the material.
  11101. *
  11102. * TODO: Explain the differences to `fragmentNode`.
  11103. *
  11104. * @type {Node<vec4>?}
  11105. * @default null
  11106. */
  11107. this.outputNode = null;
  11108. /**
  11109. * MRT configuration is done on renderer or pass level. This node allows to
  11110. * overwrite what values are written into MRT targets on material level. This
  11111. * can be useful for implementing selective FX features that should only affect
  11112. * specific objects.
  11113. *
  11114. * @type {MRTNode?}
  11115. * @default null
  11116. */
  11117. this.mrtNode = null;
  11118. /**
  11119. * This node property can be used if you need complete freedom in implementing
  11120. * the fragment shader. Assigning a node will replace the built-in material
  11121. * logic used in the fragment stage.
  11122. *
  11123. * @type {Node<vec4>?}
  11124. * @default null
  11125. */
  11126. this.fragmentNode = null;
  11127. /**
  11128. * This node property can be used if you need complete freedom in implementing
  11129. * the vertex shader. Assigning a node will replace the built-in material logic
  11130. * used in the vertex stage.
  11131. *
  11132. * @type {Node<vec4>?}
  11133. * @default null
  11134. */
  11135. this.vertexNode = null;
  11136. }
  11137. /**
  11138. * Allows to define a custom cache key that influence the material key computation
  11139. * for render objects.
  11140. *
  11141. * @return {String} The custom cache key.
  11142. */
  11143. customProgramCacheKey() {
  11144. return this.type + getCacheKey$1( this );
  11145. }
  11146. /**
  11147. * Builds this material with the given node builder.
  11148. *
  11149. * @param {NodeBuilder} builder - The current node builder.
  11150. */
  11151. build( builder ) {
  11152. this.setup( builder );
  11153. }
  11154. /**
  11155. * Setups a node material observer with the given builder.
  11156. *
  11157. * @param {NodeBuilder} builder - The current node builder.
  11158. * @return {NodeMaterialObserver} The node material observer.
  11159. */
  11160. setupObserver( builder ) {
  11161. return new NodeMaterialObserver( builder );
  11162. }
  11163. /**
  11164. * Setups the vertex and fragment stage of this node material.
  11165. *
  11166. * @param {NodeBuilder} builder - The current node builder.
  11167. */
  11168. setup( builder ) {
  11169. builder.context.setupNormal = () => this.setupNormal( builder );
  11170. builder.context.setupPositionView = () => this.setupPositionView( builder );
  11171. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  11172. const renderer = builder.renderer;
  11173. const renderTarget = renderer.getRenderTarget();
  11174. // < VERTEX STAGE >
  11175. builder.addStack();
  11176. const vertexNode = this.vertexNode || this.setupVertex( builder );
  11177. builder.stack.outputNode = vertexNode;
  11178. this.setupHardwareClipping( builder );
  11179. if ( this.geometryNode !== null ) {
  11180. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  11181. }
  11182. builder.addFlow( 'vertex', builder.removeStack() );
  11183. // < FRAGMENT STAGE >
  11184. builder.addStack();
  11185. let resultNode;
  11186. const clippingNode = this.setupClipping( builder );
  11187. if ( this.depthWrite === true || this.depthTest === true ) {
  11188. // only write depth if depth buffer is configured
  11189. if ( renderTarget !== null ) {
  11190. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  11191. } else {
  11192. if ( renderer.depth === true ) this.setupDepth( builder );
  11193. }
  11194. }
  11195. if ( this.fragmentNode === null ) {
  11196. this.setupDiffuseColor( builder );
  11197. this.setupVariants( builder );
  11198. const outgoingLightNode = this.setupLighting( builder );
  11199. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  11200. // force unsigned floats - useful for RenderTargets
  11201. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  11202. resultNode = this.setupOutput( builder, basicOutput );
  11203. // OUTPUT NODE
  11204. output.assign( resultNode );
  11205. //
  11206. if ( this.outputNode !== null ) resultNode = this.outputNode;
  11207. // MRT
  11208. if ( renderTarget !== null ) {
  11209. const mrt = renderer.getMRT();
  11210. const materialMRT = this.mrtNode;
  11211. if ( mrt !== null ) {
  11212. resultNode = mrt;
  11213. if ( materialMRT !== null ) {
  11214. resultNode = mrt.merge( materialMRT );
  11215. }
  11216. } else if ( materialMRT !== null ) {
  11217. resultNode = materialMRT;
  11218. }
  11219. }
  11220. } else {
  11221. let fragmentNode = this.fragmentNode;
  11222. if ( fragmentNode.isOutputStructNode !== true ) {
  11223. fragmentNode = vec4( fragmentNode );
  11224. }
  11225. resultNode = this.setupOutput( builder, fragmentNode );
  11226. }
  11227. builder.stack.outputNode = resultNode;
  11228. builder.addFlow( 'fragment', builder.removeStack() );
  11229. // < MONITOR >
  11230. builder.monitor = this.setupObserver( builder );
  11231. }
  11232. /**
  11233. * Setups the clipping node.
  11234. *
  11235. * @param {NodeBuilder} builder - The current node builder.
  11236. * @return {ClippingNode} The clipping node.
  11237. */
  11238. setupClipping( builder ) {
  11239. if ( builder.clippingContext === null ) return null;
  11240. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  11241. let result = null;
  11242. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  11243. const samples = builder.renderer.samples;
  11244. if ( this.alphaToCoverage && samples > 1 ) {
  11245. // to be added to flow when the color/alpha value has been determined
  11246. result = clippingAlpha();
  11247. } else {
  11248. builder.stack.add( clipping() );
  11249. }
  11250. }
  11251. return result;
  11252. }
  11253. /**
  11254. * Setups the hardware clipping if available on the current device.
  11255. *
  11256. * @param {NodeBuilder} builder - The current node builder.
  11257. */
  11258. setupHardwareClipping( builder ) {
  11259. this.hardwareClipping = false;
  11260. if ( builder.clippingContext === null ) return;
  11261. const candidateCount = builder.clippingContext.unionPlanes.length;
  11262. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  11263. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  11264. builder.stack.add( hardwareClipping() );
  11265. this.hardwareClipping = true;
  11266. }
  11267. return;
  11268. }
  11269. /**
  11270. * Setups the depth of this material.
  11271. *
  11272. * @param {NodeBuilder} builder - The current node builder.
  11273. */
  11274. setupDepth( builder ) {
  11275. const { renderer, camera } = builder;
  11276. // Depth
  11277. let depthNode = this.depthNode;
  11278. if ( depthNode === null ) {
  11279. const mrt = renderer.getMRT();
  11280. if ( mrt && mrt.has( 'depth' ) ) {
  11281. depthNode = mrt.get( 'depth' );
  11282. } else if ( renderer.logarithmicDepthBuffer === true ) {
  11283. if ( camera.isPerspectiveCamera ) {
  11284. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  11285. } else {
  11286. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  11287. }
  11288. }
  11289. }
  11290. if ( depthNode !== null ) {
  11291. depth.assign( depthNode ).append();
  11292. }
  11293. }
  11294. /**
  11295. * Setups the position node in view space. This method exists
  11296. * so derived node materials can modifiy the implementation e.g. sprite materials.
  11297. *
  11298. * @param {NodeBuilder} builder - The current node builder.
  11299. * @return {Node<vec3>} The position in view space.
  11300. */
  11301. setupPositionView( /*builder*/ ) {
  11302. return modelViewMatrix.mul( positionLocal ).xyz;
  11303. }
  11304. /**
  11305. * Setups the position in clip space.
  11306. *
  11307. * @param {NodeBuilder} builder - The current node builder.
  11308. * @return {Node<vec4>} The position in view space.
  11309. */
  11310. setupModelViewProjection( /*builder*/ ) {
  11311. return cameraProjectionMatrix.mul( positionView );
  11312. }
  11313. /**
  11314. * Setups the logic for the vertex stage.
  11315. *
  11316. * @param {NodeBuilder} builder - The current node builder.
  11317. * @return {Node<vec4>} The position in clip space.
  11318. */
  11319. setupVertex( builder ) {
  11320. builder.addStack();
  11321. this.setupPosition( builder );
  11322. builder.context.vertex = builder.removeStack();
  11323. return modelViewProjection;
  11324. }
  11325. /**
  11326. * Setups the computation of the position in local space.
  11327. *
  11328. * @param {NodeBuilder} builder - The current node builder.
  11329. * @return {Node<vec3>} The position in local space.
  11330. */
  11331. setupPosition( builder ) {
  11332. const { object, geometry } = builder;
  11333. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  11334. morphReference( object ).append();
  11335. }
  11336. if ( object.isSkinnedMesh === true ) {
  11337. skinningReference( object ).append();
  11338. }
  11339. if ( this.displacementMap ) {
  11340. const displacementMap = materialReference( 'displacementMap', 'texture' );
  11341. const displacementScale = materialReference( 'displacementScale', 'float' );
  11342. const displacementBias = materialReference( 'displacementBias', 'float' );
  11343. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  11344. }
  11345. if ( object.isBatchedMesh ) {
  11346. batch( object ).append();
  11347. }
  11348. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  11349. instancedMesh( object ).append();
  11350. }
  11351. if ( this.positionNode !== null ) {
  11352. positionLocal.assign( this.positionNode.context( { isPositionNodeInput: true } ) );
  11353. }
  11354. return positionLocal;
  11355. }
  11356. /**
  11357. * Setups the computation of the material's diffuse color.
  11358. *
  11359. * @param {NodeBuilder} builder - The current node builder.
  11360. * @param {BufferGeometry} geometry - The geometry.
  11361. */
  11362. setupDiffuseColor( { object, geometry } ) {
  11363. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  11364. // VERTEX COLORS
  11365. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  11366. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  11367. }
  11368. // Instanced colors
  11369. if ( object.instanceColor ) {
  11370. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  11371. colorNode = instanceColor.mul( colorNode );
  11372. }
  11373. if ( object.isBatchedMesh && object._colorsTexture ) {
  11374. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  11375. colorNode = batchColor.mul( colorNode );
  11376. }
  11377. // COLOR
  11378. diffuseColor.assign( colorNode );
  11379. // OPACITY
  11380. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  11381. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  11382. // ALPHA TEST
  11383. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  11384. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  11385. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  11386. }
  11387. // ALPHA HASH
  11388. if ( this.alphaHash === true ) {
  11389. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  11390. }
  11391. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  11392. diffuseColor.a.assign( 1.0 );
  11393. }
  11394. }
  11395. /**
  11396. * Abstract interface method that can be implemented by derived materials
  11397. * to setup material-specific node variables.
  11398. *
  11399. * @abstract
  11400. * @param {NodeBuilder} builder - The current node builder.
  11401. */
  11402. setupVariants( /*builder*/ ) {
  11403. // Interface function.
  11404. }
  11405. /**
  11406. * Setups the outgoing light node variable
  11407. *
  11408. * @return {Node<vec3>} The outgoing light node.
  11409. */
  11410. setupOutgoingLight() {
  11411. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  11412. }
  11413. /**
  11414. * Setups the normal node from the material.
  11415. *
  11416. * @return {Node<vec3>} The normal node.
  11417. */
  11418. setupNormal() {
  11419. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  11420. }
  11421. /**
  11422. * Setups the environment node from the material.
  11423. *
  11424. * @param {NodeBuilder} builder - The current node builder.
  11425. * @return {Node<vec4>} The environment node.
  11426. */
  11427. setupEnvironment( /*builder*/ ) {
  11428. let node = null;
  11429. if ( this.envNode ) {
  11430. node = this.envNode;
  11431. } else if ( this.envMap ) {
  11432. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  11433. }
  11434. return node;
  11435. }
  11436. /**
  11437. * Setups the light map node from the material.
  11438. *
  11439. * @param {NodeBuilder} builder - The current node builder.
  11440. * @return {Node<vec3>} The light map node.
  11441. */
  11442. setupLightMap( builder ) {
  11443. let node = null;
  11444. if ( builder.material.lightMap ) {
  11445. node = new IrradianceNode( materialLightMap );
  11446. }
  11447. return node;
  11448. }
  11449. /**
  11450. * Setups the lights node based on the scene, environment and material.
  11451. *
  11452. * @param {NodeBuilder} builder - The current node builder.
  11453. * @return {LightsNode} The lights node.
  11454. */
  11455. setupLights( builder ) {
  11456. const materialLightsNode = [];
  11457. //
  11458. const envNode = this.setupEnvironment( builder );
  11459. if ( envNode && envNode.isLightingNode ) {
  11460. materialLightsNode.push( envNode );
  11461. }
  11462. const lightMapNode = this.setupLightMap( builder );
  11463. if ( lightMapNode && lightMapNode.isLightingNode ) {
  11464. materialLightsNode.push( lightMapNode );
  11465. }
  11466. if ( this.aoNode !== null || builder.material.aoMap ) {
  11467. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  11468. materialLightsNode.push( new AONode( aoNode ) );
  11469. }
  11470. let lightsN = this.lightsNode || builder.lightsNode;
  11471. if ( materialLightsNode.length > 0 ) {
  11472. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  11473. }
  11474. return lightsN;
  11475. }
  11476. /**
  11477. * This method should be implemented by most derived materials
  11478. * since it defines the material's lighting model.
  11479. *
  11480. * @abstract
  11481. * @param {NodeBuilder} builder - The current node builder.
  11482. * @return {LightingModel} The lighting model.
  11483. */
  11484. setupLightingModel( /*builder*/ ) {
  11485. // Interface function.
  11486. }
  11487. /**
  11488. * Setups the outgoing light node.
  11489. *
  11490. * @param {NodeBuilder} builder - The current node builder.
  11491. * @return {Node<vec3>} The outgoing light node.
  11492. */
  11493. setupLighting( builder ) {
  11494. const { material } = builder;
  11495. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  11496. // OUTGOING LIGHT
  11497. const lights = this.lights === true || this.lightsNode !== null;
  11498. const lightsNode = lights ? this.setupLights( builder ) : null;
  11499. let outgoingLightNode = this.setupOutgoingLight( builder );
  11500. if ( lightsNode && lightsNode.getScope().hasLights ) {
  11501. const lightingModel = this.setupLightingModel( builder );
  11502. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  11503. } else if ( backdropNode !== null ) {
  11504. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  11505. }
  11506. // EMISSIVE
  11507. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  11508. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  11509. outgoingLightNode = outgoingLightNode.add( emissive );
  11510. }
  11511. return outgoingLightNode;
  11512. }
  11513. /**
  11514. * Setups the output node.
  11515. *
  11516. * @param {NodeBuilder} builder - The current node builder.
  11517. * @param {Node<vec4>} outputNode - The existing output node.
  11518. * @return {Node<vec4>} The output node.
  11519. */
  11520. setupOutput( builder, outputNode ) {
  11521. // FOG
  11522. if ( this.fog === true ) {
  11523. const fogNode = builder.fogNode;
  11524. if ( fogNode ) {
  11525. output.assign( outputNode );
  11526. outputNode = vec4( fogNode );
  11527. }
  11528. }
  11529. return outputNode;
  11530. }
  11531. /**
  11532. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  11533. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  11534. * defining all material properties of the classic type in the node type.
  11535. *
  11536. * @param {Material} material - The material to copy properties with their values to this node material.
  11537. */
  11538. setDefaultValues( material ) {
  11539. // This approach is to reuse the native refreshUniforms*
  11540. // and turn available the use of features like transmission and environment in core
  11541. for ( const property in material ) {
  11542. const value = material[ property ];
  11543. if ( this[ property ] === undefined ) {
  11544. this[ property ] = value;
  11545. if ( value && value.clone ) this[ property ] = value.clone();
  11546. }
  11547. }
  11548. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  11549. for ( const key in descriptors ) {
  11550. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  11551. descriptors[ key ].get !== undefined ) {
  11552. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  11553. }
  11554. }
  11555. }
  11556. /**
  11557. * Serializes this material to JSON.
  11558. *
  11559. * @param {(Object|String)?} meta - The meta information for serialization.
  11560. * @return {Object} The serialized node.
  11561. */
  11562. toJSON( meta ) {
  11563. const isRoot = ( meta === undefined || typeof meta === 'string' );
  11564. if ( isRoot ) {
  11565. meta = {
  11566. textures: {},
  11567. images: {},
  11568. nodes: {}
  11569. };
  11570. }
  11571. const data = Material.prototype.toJSON.call( this, meta );
  11572. const nodeChildren = getNodeChildren( this );
  11573. data.inputNodes = {};
  11574. for ( const { property, childNode } of nodeChildren ) {
  11575. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  11576. }
  11577. // TODO: Copied from Object3D.toJSON
  11578. function extractFromCache( cache ) {
  11579. const values = [];
  11580. for ( const key in cache ) {
  11581. const data = cache[ key ];
  11582. delete data.metadata;
  11583. values.push( data );
  11584. }
  11585. return values;
  11586. }
  11587. if ( isRoot ) {
  11588. const textures = extractFromCache( meta.textures );
  11589. const images = extractFromCache( meta.images );
  11590. const nodes = extractFromCache( meta.nodes );
  11591. if ( textures.length > 0 ) data.textures = textures;
  11592. if ( images.length > 0 ) data.images = images;
  11593. if ( nodes.length > 0 ) data.nodes = nodes;
  11594. }
  11595. return data;
  11596. }
  11597. /**
  11598. * Copies the properties of the given node material to this instance.
  11599. *
  11600. * @param {NodeMaterial} source - The material to copy.
  11601. * @return {NodeMaterial} A reference to this node material.
  11602. */
  11603. copy( source ) {
  11604. this.lightsNode = source.lightsNode;
  11605. this.envNode = source.envNode;
  11606. this.colorNode = source.colorNode;
  11607. this.normalNode = source.normalNode;
  11608. this.opacityNode = source.opacityNode;
  11609. this.backdropNode = source.backdropNode;
  11610. this.backdropAlphaNode = source.backdropAlphaNode;
  11611. this.alphaTestNode = source.alphaTestNode;
  11612. this.positionNode = source.positionNode;
  11613. this.geometryNode = source.geometryNode;
  11614. this.depthNode = source.depthNode;
  11615. this.shadowPositionNode = source.shadowPositionNode;
  11616. this.receivedShadowNode = source.receivedShadowNode;
  11617. this.castShadowNode = source.castShadowNode;
  11618. this.outputNode = source.outputNode;
  11619. this.mrtNode = source.mrtNode;
  11620. this.fragmentNode = source.fragmentNode;
  11621. this.vertexNode = source.vertexNode;
  11622. return super.copy( source );
  11623. }
  11624. }
  11625. const _defaultValues$e = /*@__PURE__*/ new PointsMaterial();
  11626. /**
  11627. * Unlike WebGL, WebGPU can render point primitives only with a size
  11628. * of one pixel. This type node material can be used to mimic the WebGL
  11629. * points rendering by rendering small planes via instancing.
  11630. *
  11631. * This material should be used with {@link InstancedPointsGeometry}.
  11632. *
  11633. * @augments NodeMaterial
  11634. */
  11635. class InstancedPointsNodeMaterial extends NodeMaterial {
  11636. static get type() {
  11637. return 'InstancedPointsNodeMaterial';
  11638. }
  11639. /**
  11640. * Constructs a new instanced points node material.
  11641. *
  11642. * @param {Object?} parameters - The configuration parameter.
  11643. */
  11644. constructor( parameters = {} ) {
  11645. super();
  11646. /**
  11647. * This flag can be used for type testing.
  11648. *
  11649. * @type {Boolean}
  11650. * @readonly
  11651. * @default true
  11652. */
  11653. this.isInstancedPointsNodeMaterial = true;
  11654. /**
  11655. * Whether vertex colors should be used or not. If set to `true`,
  11656. * each point instance can receive a custom color value.
  11657. *
  11658. * @type {Boolean}
  11659. * @default false
  11660. */
  11661. this.useColor = parameters.vertexColors;
  11662. /**
  11663. * The points width in pixels.
  11664. *
  11665. * @type {Number}
  11666. * @default 1
  11667. */
  11668. this.pointWidth = 1;
  11669. /**
  11670. * This node can be used to define the colors for each instance.
  11671. *
  11672. * @type {Node<vec3>?}
  11673. * @default null
  11674. */
  11675. this.pointColorNode = null;
  11676. /**
  11677. * This node can be used to define the width for each point instance.
  11678. *
  11679. * @type {Node<float>?}
  11680. * @default null
  11681. */
  11682. this.pointWidthNode = null;
  11683. this._useAlphaToCoverage = true;
  11684. this.setDefaultValues( _defaultValues$e );
  11685. this.setValues( parameters );
  11686. }
  11687. /**
  11688. * Setups the vertex and fragment stage of this node material.
  11689. *
  11690. * @param {NodeBuilder} builder - The current node builder.
  11691. */
  11692. setup( builder ) {
  11693. const { renderer } = builder;
  11694. const useAlphaToCoverage = this._useAlphaToCoverage;
  11695. const useColor = this.useColor;
  11696. this.vertexNode = Fn( () => {
  11697. const instancePosition = attribute( 'instancePosition' ).xyz;
  11698. // camera space
  11699. const mvPos = vec4( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  11700. const aspect = viewport.z.div( viewport.w );
  11701. // clip space
  11702. const clipPos = cameraProjectionMatrix.mul( mvPos );
  11703. // offset in ndc space
  11704. const offset = positionGeometry.xy.toVar();
  11705. offset.mulAssign( this.pointWidthNode ? this.pointWidthNode : materialPointWidth );
  11706. offset.assign( offset.div( viewport.z ) );
  11707. offset.y.assign( offset.y.mul( aspect ) );
  11708. // back to clip space
  11709. offset.assign( offset.mul( clipPos.w ) );
  11710. //clipPos.xy += offset;
  11711. clipPos.addAssign( vec4( offset, 0, 0 ) );
  11712. return clipPos;
  11713. } )();
  11714. this.fragmentNode = Fn( () => {
  11715. const alpha = float( 1 ).toVar();
  11716. const len2 = lengthSq( uv().mul( 2 ).sub( 1 ) );
  11717. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  11718. const dlen = float( len2.fwidth() ).toVar();
  11719. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  11720. } else {
  11721. len2.greaterThan( 1.0 ).discard();
  11722. }
  11723. let pointColorNode;
  11724. if ( this.pointColorNode ) {
  11725. pointColorNode = this.pointColorNode;
  11726. } else {
  11727. if ( useColor ) {
  11728. const instanceColor = attribute( 'instanceColor' );
  11729. pointColorNode = instanceColor.mul( materialColor );
  11730. } else {
  11731. pointColorNode = materialColor;
  11732. }
  11733. }
  11734. alpha.mulAssign( materialOpacity );
  11735. return vec4( pointColorNode, alpha );
  11736. } )();
  11737. super.setup( builder );
  11738. }
  11739. /**
  11740. * Whether alpha to coverage should be used or not.
  11741. *
  11742. * @type {Boolean}
  11743. * @default true
  11744. */
  11745. get alphaToCoverage() {
  11746. return this._useAlphaToCoverage;
  11747. }
  11748. set alphaToCoverage( value ) {
  11749. if ( this._useAlphaToCoverage !== value ) {
  11750. this._useAlphaToCoverage = value;
  11751. this.needsUpdate = true;
  11752. }
  11753. }
  11754. }
  11755. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  11756. /**
  11757. * Node material version of `LineBasicMaterial`.
  11758. *
  11759. * @augments NodeMaterial
  11760. */
  11761. class LineBasicNodeMaterial extends NodeMaterial {
  11762. static get type() {
  11763. return 'LineBasicNodeMaterial';
  11764. }
  11765. /**
  11766. * Constructs a new line basic node material.
  11767. *
  11768. * @param {Object?} parameters - The configuration parameter.
  11769. */
  11770. constructor( parameters ) {
  11771. super();
  11772. /**
  11773. * This flag can be used for type testing.
  11774. *
  11775. * @type {Boolean}
  11776. * @readonly
  11777. * @default true
  11778. */
  11779. this.isLineBasicNodeMaterial = true;
  11780. this.setDefaultValues( _defaultValues$d );
  11781. this.setValues( parameters );
  11782. }
  11783. }
  11784. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  11785. /**
  11786. * Node material version of `LineDashedMaterial`.
  11787. *
  11788. * @augments NodeMaterial
  11789. */
  11790. class LineDashedNodeMaterial extends NodeMaterial {
  11791. static get type() {
  11792. return 'LineDashedNodeMaterial';
  11793. }
  11794. /**
  11795. * Constructs a new line dashed node material.
  11796. *
  11797. * @param {Object?} parameters - The configuration parameter.
  11798. */
  11799. constructor( parameters ) {
  11800. super();
  11801. /**
  11802. * This flag can be used for type testing.
  11803. *
  11804. * @type {Boolean}
  11805. * @readonly
  11806. * @default true
  11807. */
  11808. this.isLineDashedNodeMaterial = true;
  11809. this.setDefaultValues( _defaultValues$c );
  11810. /**
  11811. * The dash offset.
  11812. *
  11813. * @type {Number}
  11814. * @default 0
  11815. */
  11816. this.dashOffset = 0;
  11817. /**
  11818. * The offset of dash materials is by default inferred from the `dashOffset`
  11819. * property. This node property allows to overwrite the default
  11820. * and define the offset with a node instead.
  11821. *
  11822. * If you don't want to overwrite the offset but modify the existing
  11823. * value instead, use {@link module:MaterialNode.materialLineDashOffset}.
  11824. *
  11825. * @type {Node<float>?}
  11826. * @default null
  11827. */
  11828. this.offsetNode = null;
  11829. /**
  11830. * The scale of dash materials is by default inferred from the `scale`
  11831. * property. This node property allows to overwrite the default
  11832. * and define the scale with a node instead.
  11833. *
  11834. * If you don't want to overwrite the scale but modify the existing
  11835. * value instead, use {@link module:MaterialNode.materialLineScale}.
  11836. *
  11837. * @type {Node<float>?}
  11838. * @default null
  11839. */
  11840. this.dashScaleNode = null;
  11841. /**
  11842. * The dash size of dash materials is by default inferred from the `dashSize`
  11843. * property. This node property allows to overwrite the default
  11844. * and define the dash size with a node instead.
  11845. *
  11846. * If you don't want to overwrite the dash size but modify the existing
  11847. * value instead, use {@link module:MaterialNode.materialLineDashSize}.
  11848. *
  11849. * @type {Node<float>?}
  11850. * @default null
  11851. */
  11852. this.dashSizeNode = null;
  11853. /**
  11854. * The gap size of dash materials is by default inferred from the `gapSize`
  11855. * property. This node property allows to overwrite the default
  11856. * and define the gap size with a node instead.
  11857. *
  11858. * If you don't want to overwrite the gap size but modify the existing
  11859. * value instead, use {@link module:MaterialNode.materialLineGapSize}.
  11860. *
  11861. * @type {Node<float>?}
  11862. * @default null
  11863. */
  11864. this.gapSizeNode = null;
  11865. this.setValues( parameters );
  11866. }
  11867. /**
  11868. * Setups the dash specific node variables.
  11869. *
  11870. * @param {NodeBuilder} builder - The current node builder.
  11871. */
  11872. setupVariants( /* builder */ ) {
  11873. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  11874. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  11875. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  11876. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  11877. dashSize.assign( dashSizeNode );
  11878. gapSize.assign( gapSizeNode );
  11879. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  11880. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  11881. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  11882. }
  11883. }
  11884. /** @module ViewportSharedTextureNode **/
  11885. let _sharedFramebuffer = null;
  11886. /**
  11887. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  11888. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  11889. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  11890. *
  11891. * @augments module:ViewportTextureNode~ViewportTextureNode
  11892. */
  11893. class ViewportSharedTextureNode extends ViewportTextureNode {
  11894. static get type() {
  11895. return 'ViewportSharedTextureNode';
  11896. }
  11897. /**
  11898. * Constructs a new viewport shared texture node.
  11899. *
  11900. * @param {Node} [uvNode=screenUV] - The uv node.
  11901. * @param {Node?} [levelNode=null] - The level node.
  11902. */
  11903. constructor( uvNode = screenUV, levelNode = null ) {
  11904. if ( _sharedFramebuffer === null ) {
  11905. _sharedFramebuffer = new FramebufferTexture();
  11906. }
  11907. super( uvNode, levelNode, _sharedFramebuffer );
  11908. }
  11909. updateReference() {
  11910. return this;
  11911. }
  11912. }
  11913. /**
  11914. * TSL function for creating a shared viewport texture node.
  11915. *
  11916. * @function
  11917. * @param {Node} [uvNode=screenUV] - The uv node.
  11918. * @param {Node?} [levelNode=null] - The level node.
  11919. * @returns {ViewportSharedTextureNode}
  11920. */
  11921. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  11922. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  11923. /**
  11924. * This node material can be used to render lines with a size larger than one
  11925. * by representing them as instanced meshes.
  11926. *
  11927. * @augments NodeMaterial
  11928. */
  11929. class Line2NodeMaterial extends NodeMaterial {
  11930. static get type() {
  11931. return 'Line2NodeMaterial';
  11932. }
  11933. /**
  11934. * Constructs a new node material for wide line rendering.
  11935. *
  11936. * @param {Object?} parameters - The configuration parameter.
  11937. */
  11938. constructor( parameters = {} ) {
  11939. super();
  11940. /**
  11941. * This flag can be used for type testing.
  11942. *
  11943. * @type {Boolean}
  11944. * @readonly
  11945. * @default true
  11946. */
  11947. this.isLine2NodeMaterial = true;
  11948. this.setDefaultValues( _defaultValues$b );
  11949. /**
  11950. * Whether vertex colors should be used or not.
  11951. *
  11952. * @type {Boolean}
  11953. * @default false
  11954. */
  11955. this.useColor = parameters.vertexColors;
  11956. /**
  11957. * The dash offset.
  11958. *
  11959. * @type {Number}
  11960. * @default 0
  11961. */
  11962. this.dashOffset = 0;
  11963. /**
  11964. * The line width.
  11965. *
  11966. * @type {Number}
  11967. * @default 0
  11968. */
  11969. this.lineWidth = 1;
  11970. /**
  11971. * Defines the lines color.
  11972. *
  11973. * @type {Node<vec3>?}
  11974. * @default null
  11975. */
  11976. this.lineColorNode = null;
  11977. /**
  11978. * Defines the offset.
  11979. *
  11980. * @type {Node<float>?}
  11981. * @default null
  11982. */
  11983. this.offsetNode = null;
  11984. /**
  11985. * Defines the dash scale.
  11986. *
  11987. * @type {Node<float>?}
  11988. * @default null
  11989. */
  11990. this.dashScaleNode = null;
  11991. /**
  11992. * Defines the dash size.
  11993. *
  11994. * @type {Node<float>?}
  11995. * @default null
  11996. */
  11997. this.dashSizeNode = null;
  11998. /**
  11999. * Defines the gap size.
  12000. *
  12001. * @type {Node<float>?}
  12002. * @default null
  12003. */
  12004. this.gapSizeNode = null;
  12005. /**
  12006. * Blending is set to `NoBlending` since transparency
  12007. * is not supported, yet.
  12008. *
  12009. * @type {Number}
  12010. * @default 0
  12011. */
  12012. this.blending = NoBlending;
  12013. this._useDash = parameters.dashed;
  12014. this._useAlphaToCoverage = true;
  12015. this._useWorldUnits = false;
  12016. this.setValues( parameters );
  12017. }
  12018. /**
  12019. * Setups the vertex and fragment stage of this node material.
  12020. *
  12021. * @param {NodeBuilder} builder - The current node builder.
  12022. */
  12023. setup( builder ) {
  12024. const { renderer } = builder;
  12025. const useAlphaToCoverage = this._useAlphaToCoverage;
  12026. const useColor = this.useColor;
  12027. const useDash = this._useDash;
  12028. const useWorldUnits = this._useWorldUnits;
  12029. const trimSegment = Fn( ( { start, end } ) => {
  12030. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  12031. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  12032. const nearEstimate = b.mul( - 0.5 ).div( a );
  12033. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  12034. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  12035. } ).setLayout( {
  12036. name: 'trimSegment',
  12037. type: 'vec4',
  12038. inputs: [
  12039. { name: 'start', type: 'vec4' },
  12040. { name: 'end', type: 'vec4' }
  12041. ]
  12042. } );
  12043. this.vertexNode = Fn( () => {
  12044. const instanceStart = attribute( 'instanceStart' );
  12045. const instanceEnd = attribute( 'instanceEnd' );
  12046. // camera space
  12047. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  12048. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  12049. if ( useDash ) {
  12050. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  12051. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  12052. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  12053. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  12054. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  12055. lineDistance = lineDistance.add( offsetNode );
  12056. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  12057. }
  12058. if ( useWorldUnits ) {
  12059. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  12060. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  12061. }
  12062. const aspect = viewport.z.div( viewport.w );
  12063. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  12064. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  12065. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  12066. // perhaps there is a more elegant solution -- WestLangley
  12067. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  12068. If( perspective, () => {
  12069. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  12070. end.assign( trimSegment( { start: start, end: end } ) );
  12071. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  12072. start.assign( trimSegment( { start: end, end: start } ) );
  12073. } );
  12074. } );
  12075. // clip space
  12076. const clipStart = cameraProjectionMatrix.mul( start );
  12077. const clipEnd = cameraProjectionMatrix.mul( end );
  12078. // ndc space
  12079. const ndcStart = clipStart.xyz.div( clipStart.w );
  12080. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  12081. // direction
  12082. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  12083. // account for clip-space aspect ratio
  12084. dir.x.assign( dir.x.mul( aspect ) );
  12085. dir.assign( dir.normalize() );
  12086. const clip = vec4().toVar();
  12087. if ( useWorldUnits ) {
  12088. // get the offset direction as perpendicular to the view vector
  12089. const worldDir = end.xyz.sub( start.xyz ).normalize();
  12090. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  12091. const worldUp = worldDir.cross( tmpFwd ).normalize();
  12092. const worldFwd = worldDir.cross( worldUp );
  12093. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  12094. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  12095. // height offset
  12096. const hw = materialLineWidth.mul( 0.5 );
  12097. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  12098. // don't extend the line if we're rendering dashes because we
  12099. // won't be rendering the endcaps
  12100. if ( ! useDash ) {
  12101. // cap extension
  12102. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  12103. // add width to the box
  12104. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  12105. // endcaps
  12106. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  12107. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  12108. } );
  12109. }
  12110. // project the worldpos
  12111. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  12112. // shift the depth of the projected points so the line
  12113. // segments overlap neatly
  12114. const clipPose = vec3().toVar();
  12115. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  12116. clip.z.assign( clipPose.z.mul( clip.w ) );
  12117. } else {
  12118. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  12119. // undo aspect ratio adjustment
  12120. dir.x.assign( dir.x.div( aspect ) );
  12121. offset.x.assign( offset.x.div( aspect ) );
  12122. // sign flip
  12123. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  12124. // endcaps
  12125. If( positionGeometry.y.lessThan( 0.0 ), () => {
  12126. offset.assign( offset.sub( dir ) );
  12127. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  12128. offset.assign( offset.add( dir ) );
  12129. } );
  12130. // adjust for linewidth
  12131. offset.assign( offset.mul( materialLineWidth ) );
  12132. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  12133. offset.assign( offset.div( viewport.w ) );
  12134. // select end
  12135. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  12136. // back to clip space
  12137. offset.assign( offset.mul( clip.w ) );
  12138. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  12139. }
  12140. return clip;
  12141. } )();
  12142. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  12143. const p13 = p1.sub( p3 );
  12144. const p43 = p4.sub( p3 );
  12145. const p21 = p2.sub( p1 );
  12146. const d1343 = p13.dot( p43 );
  12147. const d4321 = p43.dot( p21 );
  12148. const d1321 = p13.dot( p21 );
  12149. const d4343 = p43.dot( p43 );
  12150. const d2121 = p21.dot( p21 );
  12151. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  12152. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  12153. const mua = numer.div( denom ).clamp();
  12154. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  12155. return vec2( mua, mub );
  12156. } );
  12157. this.colorNode = Fn( () => {
  12158. const vUv = uv();
  12159. if ( useDash ) {
  12160. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  12161. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  12162. dashSize.assign( dashSizeNode );
  12163. gapSize.assign( gapSizeNode );
  12164. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  12165. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  12166. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  12167. }
  12168. const alpha = float( 1 ).toVar( 'alpha' );
  12169. if ( useWorldUnits ) {
  12170. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  12171. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  12172. // Find the closest points on the view ray and the line segment
  12173. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  12174. const lineDir = worldEnd.sub( worldStart );
  12175. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  12176. const p1 = worldStart.add( lineDir.mul( params.x ) );
  12177. const p2 = rayEnd.mul( params.y );
  12178. const delta = p1.sub( p2 );
  12179. const len = delta.length();
  12180. const norm = len.div( materialLineWidth );
  12181. if ( ! useDash ) {
  12182. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  12183. const dnorm = norm.fwidth();
  12184. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  12185. } else {
  12186. norm.greaterThan( 0.5 ).discard();
  12187. }
  12188. }
  12189. } else {
  12190. // round endcaps
  12191. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  12192. const a = vUv.x;
  12193. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  12194. const len2 = a.mul( a ).add( b.mul( b ) );
  12195. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  12196. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  12197. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  12198. } );
  12199. } else {
  12200. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  12201. const a = vUv.x;
  12202. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  12203. const len2 = a.mul( a ).add( b.mul( b ) );
  12204. len2.greaterThan( 1.0 ).discard();
  12205. } );
  12206. }
  12207. }
  12208. let lineColorNode;
  12209. if ( this.lineColorNode ) {
  12210. lineColorNode = this.lineColorNode;
  12211. } else {
  12212. if ( useColor ) {
  12213. const instanceColorStart = attribute( 'instanceColorStart' );
  12214. const instanceColorEnd = attribute( 'instanceColorEnd' );
  12215. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  12216. lineColorNode = instanceColor.mul( materialColor );
  12217. } else {
  12218. lineColorNode = materialColor;
  12219. }
  12220. }
  12221. return vec4( lineColorNode, alpha );
  12222. } )();
  12223. if ( this.transparent ) {
  12224. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12225. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  12226. }
  12227. super.setup( builder );
  12228. }
  12229. /**
  12230. * Whether the lines should sized in world units or not.
  12231. * When set to `false` the unit is pixel.
  12232. *
  12233. * @type {Boolean}
  12234. * @default false
  12235. */
  12236. get worldUnits() {
  12237. return this._useWorldUnits;
  12238. }
  12239. set worldUnits( value ) {
  12240. if ( this._useWorldUnits !== value ) {
  12241. this._useWorldUnits = value;
  12242. this.needsUpdate = true;
  12243. }
  12244. }
  12245. /**
  12246. * Whether the lines should be dashed or not.
  12247. *
  12248. * @type {Boolean}
  12249. * @default false
  12250. */
  12251. get dashed() {
  12252. return this._useDash;
  12253. }
  12254. set dashed( value ) {
  12255. if ( this._useDash !== value ) {
  12256. this._useDash = value;
  12257. this.needsUpdate = true;
  12258. }
  12259. }
  12260. /**
  12261. * Whether alpha to coverage should be used or not.
  12262. *
  12263. * @type {Boolean}
  12264. * @default true
  12265. */
  12266. get alphaToCoverage() {
  12267. return this._useAlphaToCoverage;
  12268. }
  12269. set alphaToCoverage( value ) {
  12270. if ( this._useAlphaToCoverage !== value ) {
  12271. this._useAlphaToCoverage = value;
  12272. this.needsUpdate = true;
  12273. }
  12274. }
  12275. }
  12276. /** @module Packing **/
  12277. /**
  12278. * Packs a direction vector into a color value.
  12279. *
  12280. * @method
  12281. * @param {Node<vec3>} node - The direction to pack.
  12282. * @return {Node<vec3>} The color.
  12283. */
  12284. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  12285. /**
  12286. * Unpacks a color value into a direction vector.
  12287. *
  12288. * @method
  12289. * @param {Node<vec3>} node - The color to unpack.
  12290. * @return {Node<vec3>} The direction.
  12291. */
  12292. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  12293. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  12294. /**
  12295. * Node material version of `MeshNormalMaterial`.
  12296. *
  12297. * @augments NodeMaterial
  12298. */
  12299. class MeshNormalNodeMaterial extends NodeMaterial {
  12300. static get type() {
  12301. return 'MeshNormalNodeMaterial';
  12302. }
  12303. /**
  12304. * Constructs a new mesh normal node material.
  12305. *
  12306. * @param {Object?} parameters - The configuration parameter.
  12307. */
  12308. constructor( parameters ) {
  12309. super();
  12310. /**
  12311. * This flag can be used for type testing.
  12312. *
  12313. * @type {Boolean}
  12314. * @readonly
  12315. * @default true
  12316. */
  12317. this.isMeshNormalNodeMaterial = true;
  12318. this.setDefaultValues( _defaultValues$a );
  12319. this.setValues( parameters );
  12320. }
  12321. /**
  12322. * Overwrites the default implementation by computing the diffuse color
  12323. * based on the normal data.
  12324. */
  12325. setupDiffuseColor() {
  12326. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12327. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  12328. }
  12329. }
  12330. /** @module EquirectUVNode **/
  12331. /**
  12332. * Can be used to compute texture coordinates for projecting an
  12333. * equirectangular texture onto a mesh for using it as the scene's
  12334. * background.
  12335. *
  12336. * ```js
  12337. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  12338. * ```
  12339. *
  12340. * @augments TempNode
  12341. */
  12342. class EquirectUVNode extends TempNode {
  12343. static get type() {
  12344. return 'EquirectUVNode';
  12345. }
  12346. /**
  12347. * Constructs a new equirect uv node.
  12348. *
  12349. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  12350. */
  12351. constructor( dirNode = positionWorldDirection ) {
  12352. super( 'vec2' );
  12353. /**
  12354. * A direction vector for sampling why is by default `positionWorldDirection`.
  12355. *
  12356. * @type {Node<vec3>}
  12357. */
  12358. this.dirNode = dirNode;
  12359. }
  12360. setup() {
  12361. const dir = this.dirNode;
  12362. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  12363. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  12364. return vec2( u, v );
  12365. }
  12366. }
  12367. /**
  12368. * TSL function for creating an equirect uv node.
  12369. *
  12370. * @function
  12371. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  12372. * @returns {EquirectUVNode}
  12373. */
  12374. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  12375. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  12376. /**
  12377. * This class represents a cube render target. It is a special version
  12378. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  12379. *
  12380. * @augments WebGLCubeRenderTarget
  12381. */
  12382. class CubeRenderTarget extends WebGLCubeRenderTarget {
  12383. constructor( size = 1, options = {} ) {
  12384. super( size, options );
  12385. this.isCubeRenderTarget = true;
  12386. }
  12387. /**
  12388. * Converts the given equirectangular texture to a cube map.
  12389. *
  12390. * @param {Renderer} renderer - The renderer.
  12391. * @param {Texture} texture - The equirectangular texture.
  12392. * @return {CubeRenderTarget} A reference to this cube render target.
  12393. */
  12394. fromEquirectangularTexture( renderer, texture$1 ) {
  12395. const currentMinFilter = texture$1.minFilter;
  12396. const currentGenerateMipmaps = texture$1.generateMipmaps;
  12397. texture$1.generateMipmaps = true;
  12398. this.texture.type = texture$1.type;
  12399. this.texture.colorSpace = texture$1.colorSpace;
  12400. this.texture.generateMipmaps = texture$1.generateMipmaps;
  12401. this.texture.minFilter = texture$1.minFilter;
  12402. this.texture.magFilter = texture$1.magFilter;
  12403. const geometry = new BoxGeometry( 5, 5, 5 );
  12404. const uvNode = equirectUV( positionWorldDirection );
  12405. const material = new NodeMaterial();
  12406. material.colorNode = texture( texture$1, uvNode, 0 );
  12407. material.side = BackSide;
  12408. material.blending = NoBlending;
  12409. const mesh = new Mesh( geometry, material );
  12410. const scene = new Scene();
  12411. scene.add( mesh );
  12412. // Avoid blurred poles
  12413. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  12414. const camera = new CubeCamera( 1, 10, this );
  12415. const currentMRT = renderer.getMRT();
  12416. renderer.setMRT( null );
  12417. camera.update( renderer, scene );
  12418. renderer.setMRT( currentMRT );
  12419. texture$1.minFilter = currentMinFilter;
  12420. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  12421. mesh.geometry.dispose();
  12422. mesh.material.dispose();
  12423. return this;
  12424. }
  12425. }
  12426. /** @module CubeMapNode **/
  12427. const _cache$1 = new WeakMap();
  12428. /**
  12429. * This node can be used to automatically convert environment maps in the
  12430. * equirectangular format into the cube map format.
  12431. *
  12432. * @augments TempNode
  12433. */
  12434. class CubeMapNode extends TempNode {
  12435. static get type() {
  12436. return 'CubeMapNode';
  12437. }
  12438. /**
  12439. * Constructs a new cube map node.
  12440. *
  12441. * @param {Node} envNode - The node representing the environment map.
  12442. */
  12443. constructor( envNode ) {
  12444. super( 'vec3' );
  12445. /**
  12446. * The node representing the environment map.
  12447. *
  12448. * @type {Node}
  12449. */
  12450. this.envNode = envNode;
  12451. /**
  12452. * A reference to the internal cube texture.
  12453. *
  12454. * @private
  12455. * @type {CubeTexture}
  12456. * @default null
  12457. */
  12458. this._cubeTexture = null;
  12459. /**
  12460. * A reference to the internal cube texture node.
  12461. *
  12462. * @private
  12463. * @type {CubeTextureNode}
  12464. */
  12465. this._cubeTextureNode = cubeTexture();
  12466. const defaultTexture = new CubeTexture();
  12467. defaultTexture.isRenderTargetTexture = true;
  12468. /**
  12469. * A default cube texture that acts as a placeholder.
  12470. * It is used when the conversion from equirectangular to cube
  12471. * map has not finished yet for a given texture.
  12472. *
  12473. * @private
  12474. * @type {CubeTexture}
  12475. */
  12476. this._defaultTexture = defaultTexture;
  12477. /**
  12478. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  12479. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  12480. *
  12481. * @type {String}
  12482. * @default 'render'
  12483. */
  12484. this.updateBeforeType = NodeUpdateType.RENDER;
  12485. }
  12486. updateBefore( frame ) {
  12487. const { renderer, material } = frame;
  12488. const envNode = this.envNode;
  12489. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  12490. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  12491. if ( texture && texture.isTexture ) {
  12492. const mapping = texture.mapping;
  12493. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  12494. // check for converted cubemap map
  12495. if ( _cache$1.has( texture ) ) {
  12496. const cubeMap = _cache$1.get( texture );
  12497. mapTextureMapping( cubeMap, texture.mapping );
  12498. this._cubeTexture = cubeMap;
  12499. } else {
  12500. // create cube map from equirectangular map
  12501. const image = texture.image;
  12502. if ( isEquirectangularMapReady$1( image ) ) {
  12503. const renderTarget = new CubeRenderTarget( image.height );
  12504. renderTarget.fromEquirectangularTexture( renderer, texture );
  12505. mapTextureMapping( renderTarget.texture, texture.mapping );
  12506. this._cubeTexture = renderTarget.texture;
  12507. _cache$1.set( texture, renderTarget.texture );
  12508. texture.addEventListener( 'dispose', onTextureDispose );
  12509. } else {
  12510. // default cube texture as fallback when equirectangular texture is not yet loaded
  12511. this._cubeTexture = this._defaultTexture;
  12512. }
  12513. }
  12514. //
  12515. this._cubeTextureNode.value = this._cubeTexture;
  12516. } else {
  12517. // envNode already refers to a cube map
  12518. this._cubeTextureNode = this.envNode;
  12519. }
  12520. }
  12521. }
  12522. }
  12523. setup( builder ) {
  12524. this.updateBefore( builder );
  12525. return this._cubeTextureNode;
  12526. }
  12527. }
  12528. /**
  12529. * Returns true if the given equirectangular image has been fully loaded
  12530. * and is ready for further processing.
  12531. *
  12532. * @private
  12533. * @param {Image} image - The equirectangular image to check.
  12534. * @return {Boolean} Whether the image is ready or not.
  12535. */
  12536. function isEquirectangularMapReady$1( image ) {
  12537. if ( image === null || image === undefined ) return false;
  12538. return image.height > 0;
  12539. }
  12540. /**
  12541. * This function is executed when `dispose()` is called on the equirectangular
  12542. * texture. In this case, the generated cube map with its render target
  12543. * is deleted as well.
  12544. *
  12545. * @private
  12546. * @param {Object} event - The event object.
  12547. */
  12548. function onTextureDispose( event ) {
  12549. const texture = event.target;
  12550. texture.removeEventListener( 'dispose', onTextureDispose );
  12551. const renderTarget = _cache$1.get( texture );
  12552. if ( renderTarget !== undefined ) {
  12553. _cache$1.delete( texture );
  12554. renderTarget.dispose();
  12555. }
  12556. }
  12557. /**
  12558. * This function makes sure the generated cube map uses the correct
  12559. * texture mapping that corresponds to the equirectangular original.
  12560. *
  12561. * @private
  12562. * @param {Texture} texture - The cube texture.
  12563. * @param {Number} mapping - The original texture mapping.
  12564. */
  12565. function mapTextureMapping( texture, mapping ) {
  12566. if ( mapping === EquirectangularReflectionMapping ) {
  12567. texture.mapping = CubeReflectionMapping;
  12568. } else if ( mapping === EquirectangularRefractionMapping ) {
  12569. texture.mapping = CubeRefractionMapping;
  12570. }
  12571. }
  12572. /**
  12573. * TSL function for creating a cube map node.
  12574. *
  12575. * @function
  12576. * @param {Node} envNode - The node representing the environment map.
  12577. * @returns {CubeMapNode}
  12578. */
  12579. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  12580. /**
  12581. * Represents a basic model for Image-based lighting (IBL). The environment
  12582. * is defined via environment maps in the equirectangular or cube map format.
  12583. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  12584. * or {@link MeshPhongNodeMaterial}.
  12585. *
  12586. * @augments LightingNode
  12587. */
  12588. class BasicEnvironmentNode extends LightingNode {
  12589. static get type() {
  12590. return 'BasicEnvironmentNode';
  12591. }
  12592. /**
  12593. * Constructs a new basic environment node.
  12594. *
  12595. * @param {Node} [envNode=null] - A node representing the environment.
  12596. */
  12597. constructor( envNode = null ) {
  12598. super();
  12599. /**
  12600. * A node representing the environment.
  12601. *
  12602. * @type {Node}
  12603. * @default null
  12604. */
  12605. this.envNode = envNode;
  12606. }
  12607. setup( builder ) {
  12608. // environment property is used in the finish() method of BasicLightingModel
  12609. builder.context.environment = cubeMapNode( this.envNode );
  12610. }
  12611. }
  12612. /**
  12613. * A specific version of {@link IrradianceNode} that is only relevant
  12614. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  12615. * requires a special scaling factor for the light map.
  12616. *
  12617. * @augments LightingNode
  12618. */
  12619. class BasicLightMapNode extends LightingNode {
  12620. static get type() {
  12621. return 'BasicLightMapNode';
  12622. }
  12623. /**
  12624. * Constructs a new basic light map node.
  12625. *
  12626. * @param {Node<vec3>?} [lightMapNode=null] - The light map node.
  12627. */
  12628. constructor( lightMapNode = null ) {
  12629. super();
  12630. /**
  12631. * The light map node.
  12632. *
  12633. * @type {Node<vec3>?}
  12634. */
  12635. this.lightMapNode = lightMapNode;
  12636. }
  12637. setup( builder ) {
  12638. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  12639. const RECIPROCAL_PI = float( 1 / Math.PI );
  12640. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  12641. }
  12642. }
  12643. /**
  12644. * Abstract class for implementing lighting models. The module defines
  12645. * multiple methods that concrete lighting models can implement. These
  12646. * methods are executed at different points during the light evaluation
  12647. * process.
  12648. */
  12649. class LightingModel {
  12650. /**
  12651. * This method is intended for setting up lighting model and context data
  12652. * which are later used in the evaluation process.
  12653. *
  12654. * @abstract
  12655. * @param {ContextNode} input - The current node context.
  12656. * @param {StackNode} stack - The current stack.
  12657. * @param {NodeBuilder} builder - The current node builder.
  12658. */
  12659. start( /*input, stack, builder*/ ) { }
  12660. /**
  12661. * This method is intended for executing final tasks like final updates
  12662. * to the outgoing light.
  12663. *
  12664. * @abstract
  12665. * @param {ContextNode} input - The current node context.
  12666. * @param {StackNode} stack - The current stack.
  12667. * @param {NodeBuilder} builder - The current node builder.
  12668. */
  12669. finish( /*input, stack, builder*/ ) { }
  12670. /**
  12671. * This method is intended for implementing the direct light term and
  12672. * executed during the build process of directional, point and spot light nodes.
  12673. *
  12674. * @abstract
  12675. * @param {Object} input - The input data.
  12676. * @param {StackNode} stack - The current stack.
  12677. * @param {NodeBuilder} builder - The current node builder.
  12678. */
  12679. direct( /*input, stack, builder*/ ) { }
  12680. /**
  12681. * This method is intended for implementing the direct light term for
  12682. * rect area light nodes.
  12683. *
  12684. * @abstract
  12685. * @param {Object} input - The input data.
  12686. * @param {StackNode} stack - The current stack.
  12687. * @param {NodeBuilder} builder - The current node builder.
  12688. */
  12689. directRectArea( /*input, stack, builder*/ ) {}
  12690. /**
  12691. * This method is intended for implementing the indirect light term.
  12692. *
  12693. * @abstract
  12694. * @param {ContextNode} input - The current node context.
  12695. * @param {StackNode} stack - The current stack.
  12696. * @param {NodeBuilder} builder - The current node builder.
  12697. */
  12698. indirect( /*input, stack, builder*/ ) { }
  12699. /**
  12700. * This method is intended for implementing the ambient occlusion term.
  12701. * Unlike other methods, this method must be called manually by the lighting
  12702. * model in its indirect term.
  12703. *
  12704. * @abstract
  12705. * @param {ContextNode} input - The current node context.
  12706. * @param {StackNode} stack - The current stack.
  12707. * @param {NodeBuilder} builder - The current node builder.
  12708. */
  12709. ambientOcclusion( /*input, stack, builder*/ ) { }
  12710. }
  12711. /**
  12712. * Represents the lighting model for unlit materials. The only light contribution
  12713. * is baked indirect lighting modulated with ambient occlusion and the material's
  12714. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  12715. *
  12716. * @augments LightingModel
  12717. */
  12718. class BasicLightingModel extends LightingModel {
  12719. /**
  12720. * Constructs a new basic lighting model.
  12721. */
  12722. constructor() {
  12723. super();
  12724. }
  12725. /**
  12726. * Implements the baked indirect lighting with its modulation.
  12727. *
  12728. * @param {ContextNode} context - The current node context.
  12729. * @param {StackNode} stack - The current stack.
  12730. * @param {NodeBuilder} builder - The current node builder.
  12731. */
  12732. indirect( context, stack, builder ) {
  12733. const ambientOcclusion = context.ambientOcclusion;
  12734. const reflectedLight = context.reflectedLight;
  12735. const irradianceLightMap = builder.context.irradianceLightMap;
  12736. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  12737. // accumulation (baked indirect lighting only)
  12738. if ( irradianceLightMap ) {
  12739. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  12740. } else {
  12741. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  12742. }
  12743. // modulation
  12744. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  12745. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  12746. }
  12747. /**
  12748. * Implements the environment mapping.
  12749. *
  12750. * @param {ContextNode} context - The current node context.
  12751. * @param {StackNode} stack - The current stack.
  12752. * @param {NodeBuilder} builder - The current node builder.
  12753. */
  12754. finish( context, stack, builder ) {
  12755. const material = builder.material;
  12756. const outgoingLight = context.outgoingLight;
  12757. const envNode = builder.context.environment;
  12758. if ( envNode ) {
  12759. switch ( material.combine ) {
  12760. case MultiplyOperation:
  12761. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  12762. break;
  12763. case MixOperation:
  12764. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  12765. break;
  12766. case AddOperation:
  12767. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  12768. break;
  12769. default:
  12770. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  12771. break;
  12772. }
  12773. }
  12774. }
  12775. }
  12776. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  12777. /**
  12778. * Node material version of `MeshBasicMaterial`.
  12779. *
  12780. * @augments NodeMaterial
  12781. */
  12782. class MeshBasicNodeMaterial extends NodeMaterial {
  12783. static get type() {
  12784. return 'MeshBasicNodeMaterial';
  12785. }
  12786. /**
  12787. * Constructs a new mesh basic node material.
  12788. *
  12789. * @param {Object?} parameters - The configuration parameter.
  12790. */
  12791. constructor( parameters ) {
  12792. super();
  12793. /**
  12794. * This flag can be used for type testing.
  12795. *
  12796. * @type {Boolean}
  12797. * @readonly
  12798. * @default true
  12799. */
  12800. this.isMeshBasicNodeMaterial = true;
  12801. /**
  12802. * Although the basic material is by definition unlit, we set
  12803. * this property to `true` since we use a lighting model to compute
  12804. * the outgoing light of the fragment shader.
  12805. *
  12806. * @type {Boolean}
  12807. * @default true
  12808. */
  12809. this.lights = true;
  12810. this.setDefaultValues( _defaultValues$9 );
  12811. this.setValues( parameters );
  12812. }
  12813. /**
  12814. * Basic materials are not affected by normal and bump maps so we
  12815. * return by default {@link module:Normal.normalView}.
  12816. *
  12817. * @return {Node<vec3>} The normal node.
  12818. */
  12819. setupNormal() {
  12820. return normalView; // see #28839
  12821. }
  12822. /**
  12823. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  12824. * to implement the default environment mapping.
  12825. *
  12826. * @param {NodeBuilder} builder - The current node builder.
  12827. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  12828. */
  12829. setupEnvironment( builder ) {
  12830. const envNode = super.setupEnvironment( builder );
  12831. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  12832. }
  12833. /**
  12834. * This method must be overwriten since light maps are evaluated
  12835. * with a special scaling factor for basic materials.
  12836. *
  12837. * @param {NodeBuilder} builder - The current node builder.
  12838. * @return {BasicLightMapNode<vec3>?} The light map node.
  12839. */
  12840. setupLightMap( builder ) {
  12841. let node = null;
  12842. if ( builder.material.lightMap ) {
  12843. node = new BasicLightMapNode( materialLightMap );
  12844. }
  12845. return node;
  12846. }
  12847. /**
  12848. * The material overwrites this method because `lights` is set to `true` but
  12849. * we still want to return the diffuse color as the outgoing light.
  12850. *
  12851. * @return {Node<vec3>} The outgoing light node.
  12852. */
  12853. setupOutgoingLight() {
  12854. return diffuseColor.rgb;
  12855. }
  12856. /**
  12857. * Setups the lighting model.
  12858. *
  12859. * @return {BasicLightingModel} The lighting model.
  12860. */
  12861. setupLightingModel() {
  12862. return new BasicLightingModel();
  12863. }
  12864. }
  12865. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  12866. // Original approximation by Christophe Schlick '94
  12867. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  12868. // Optimized variant (presented by Epic at SIGGRAPH '13)
  12869. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  12870. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  12871. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  12872. } ); // validated
  12873. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  12874. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  12875. } ); // validated
  12876. const G_BlinnPhong_Implicit = () => float( 0.25 );
  12877. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  12878. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  12879. } );
  12880. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  12881. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  12882. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  12883. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  12884. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  12885. const G = G_BlinnPhong_Implicit();
  12886. const D = D_BlinnPhong( { dotNH } );
  12887. return F.mul( G ).mul( D );
  12888. } );
  12889. /**
  12890. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  12891. *
  12892. * @augments BasicLightingModel
  12893. */
  12894. class PhongLightingModel extends BasicLightingModel {
  12895. /**
  12896. * Constructs a new phong lighting model.
  12897. *
  12898. * @param {Boolean} [specular=true] - Whether specular is supported or not.
  12899. */
  12900. constructor( specular = true ) {
  12901. super();
  12902. /**
  12903. * Whether specular is supported or not. Set this to `false` if you are
  12904. * looking for a Lambert-like material meaning a material for non-shiny
  12905. * surfaces, without specular highlights.
  12906. *
  12907. * @type {Boolean}
  12908. * @default true
  12909. */
  12910. this.specular = specular;
  12911. }
  12912. /**
  12913. * Implements the direct lighting. The specular portion is optional an can be controlled
  12914. * with the {@link PhongLightingModel#specular} flag.
  12915. *
  12916. * @param {Object} input - The input data.
  12917. * @param {StackNode} stack - The current stack.
  12918. * @param {NodeBuilder} builder - The current node builder.
  12919. */
  12920. direct( { lightDirection, lightColor, reflectedLight } ) {
  12921. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  12922. const irradiance = dotNL.mul( lightColor );
  12923. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  12924. if ( this.specular === true ) {
  12925. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  12926. }
  12927. }
  12928. /**
  12929. * Implements the indirect lighting.
  12930. *
  12931. * @param {ContextNode} input - The current node context.
  12932. * @param {StackNode} stack - The current stack.
  12933. * @param {NodeBuilder} builder - The current node builder.
  12934. */
  12935. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  12936. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  12937. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  12938. }
  12939. }
  12940. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  12941. /**
  12942. * Node material version of `MeshLambertMaterial`.
  12943. *
  12944. * @augments NodeMaterial
  12945. */
  12946. class MeshLambertNodeMaterial extends NodeMaterial {
  12947. static get type() {
  12948. return 'MeshLambertNodeMaterial';
  12949. }
  12950. /**
  12951. * Constructs a new mesh lambert node material.
  12952. *
  12953. * @param {Object?} parameters - The configuration parameter.
  12954. */
  12955. constructor( parameters ) {
  12956. super();
  12957. /**
  12958. * This flag can be used for type testing.
  12959. *
  12960. * @type {Boolean}
  12961. * @readonly
  12962. * @default true
  12963. */
  12964. this.isMeshLambertNodeMaterial = true;
  12965. /**
  12966. * Set to `true` because lambert materials react on lights.
  12967. *
  12968. * @type {Boolean}
  12969. * @default true
  12970. */
  12971. this.lights = true;
  12972. this.setDefaultValues( _defaultValues$8 );
  12973. this.setValues( parameters );
  12974. }
  12975. /**
  12976. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  12977. * to implement the default environment mapping.
  12978. *
  12979. * @param {NodeBuilder} builder - The current node builder.
  12980. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  12981. */
  12982. setupEnvironment( builder ) {
  12983. const envNode = super.setupEnvironment( builder );
  12984. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  12985. }
  12986. /**
  12987. * Setups the lighting model.
  12988. *
  12989. * @return {PhongLightingModel} The lighting model.
  12990. */
  12991. setupLightingModel( /*builder*/ ) {
  12992. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  12993. }
  12994. }
  12995. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  12996. /**
  12997. * Node material version of `MeshPhongMaterial`.
  12998. *
  12999. * @augments NodeMaterial
  13000. */
  13001. class MeshPhongNodeMaterial extends NodeMaterial {
  13002. static get type() {
  13003. return 'MeshPhongNodeMaterial';
  13004. }
  13005. /**
  13006. * Constructs a new mesh lambert node material.
  13007. *
  13008. * @param {Object?} parameters - The configuration parameter.
  13009. */
  13010. constructor( parameters ) {
  13011. super();
  13012. /**
  13013. * This flag can be used for type testing.
  13014. *
  13015. * @type {Boolean}
  13016. * @readonly
  13017. * @default true
  13018. */
  13019. this.isMeshPhongNodeMaterial = true;
  13020. /**
  13021. * Set to `true` because phong materials react on lights.
  13022. *
  13023. * @type {Boolean}
  13024. * @default true
  13025. */
  13026. this.lights = true;
  13027. /**
  13028. * The shininess of phong materials is by default inferred from the `shininess`
  13029. * property. This node property allows to overwrite the default
  13030. * and define the shininess with a node instead.
  13031. *
  13032. * If you don't want to overwrite the shininess but modify the existing
  13033. * value instead, use {@link module:MaterialNode.materialShininess}.
  13034. *
  13035. * @type {Node<float>?}
  13036. * @default null
  13037. */
  13038. this.shininessNode = null;
  13039. /**
  13040. * The specular color of phong materials is by default inferred from the
  13041. * `specular` property. This node property allows to overwrite the default
  13042. * and define the specular color with a node instead.
  13043. *
  13044. * If you don't want to overwrite the specular color but modify the existing
  13045. * value instead, use {@link module:MaterialNode.materialSpecular}.
  13046. *
  13047. * @type {Node<vec3>?}
  13048. * @default null
  13049. */
  13050. this.specularNode = null;
  13051. this.setDefaultValues( _defaultValues$7 );
  13052. this.setValues( parameters );
  13053. }
  13054. /**
  13055. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  13056. * to implement the default environment mapping.
  13057. *
  13058. * @param {NodeBuilder} builder - The current node builder.
  13059. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  13060. */
  13061. setupEnvironment( builder ) {
  13062. const envNode = super.setupEnvironment( builder );
  13063. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  13064. }
  13065. /**
  13066. * Setups the lighting model.
  13067. *
  13068. * @return {PhongLightingModel} The lighting model.
  13069. */
  13070. setupLightingModel( /*builder*/ ) {
  13071. return new PhongLightingModel();
  13072. }
  13073. /**
  13074. * Setups the phong specific node variables.
  13075. *
  13076. * @param {NodeBuilder} builder - The current node builder.
  13077. */
  13078. setupVariants( /*builder*/ ) {
  13079. // SHININESS
  13080. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  13081. shininess.assign( shininessNode );
  13082. // SPECULAR COLOR
  13083. const specularNode = this.specularNode || materialSpecular;
  13084. specularColor.assign( specularNode );
  13085. }
  13086. copy( source ) {
  13087. this.shininessNode = source.shininessNode;
  13088. this.specularNode = source.specularNode;
  13089. return super.copy( source );
  13090. }
  13091. }
  13092. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  13093. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  13094. return float( 0 );
  13095. }
  13096. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  13097. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  13098. return geometryRoughness;
  13099. } );
  13100. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  13101. const { roughness } = inputs;
  13102. const geometryRoughness = getGeometryRoughness();
  13103. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  13104. roughnessFactor = roughnessFactor.add( geometryRoughness );
  13105. roughnessFactor = roughnessFactor.min( 1.0 );
  13106. return roughnessFactor;
  13107. } );
  13108. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  13109. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  13110. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  13111. const a2 = alpha.pow2();
  13112. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  13113. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  13114. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  13115. } ).setLayout( {
  13116. name: 'V_GGX_SmithCorrelated',
  13117. type: 'float',
  13118. inputs: [
  13119. { name: 'alpha', type: 'float' },
  13120. { name: 'dotNL', type: 'float' },
  13121. { name: 'dotNV', type: 'float' }
  13122. ]
  13123. } ); // validated
  13124. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  13125. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  13126. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  13127. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  13128. const v = div( 0.5, gv.add( gl ) );
  13129. return v.saturate();
  13130. } ).setLayout( {
  13131. name: 'V_GGX_SmithCorrelated_Anisotropic',
  13132. type: 'float',
  13133. inputs: [
  13134. { name: 'alphaT', type: 'float', qualifier: 'in' },
  13135. { name: 'alphaB', type: 'float', qualifier: 'in' },
  13136. { name: 'dotTV', type: 'float', qualifier: 'in' },
  13137. { name: 'dotBV', type: 'float', qualifier: 'in' },
  13138. { name: 'dotTL', type: 'float', qualifier: 'in' },
  13139. { name: 'dotBL', type: 'float', qualifier: 'in' },
  13140. { name: 'dotNV', type: 'float', qualifier: 'in' },
  13141. { name: 'dotNL', type: 'float', qualifier: 'in' }
  13142. ]
  13143. } );
  13144. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  13145. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  13146. // alpha is "roughness squared" in Disney’s reparameterization
  13147. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  13148. const a2 = alpha.pow2();
  13149. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  13150. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  13151. } ).setLayout( {
  13152. name: 'D_GGX',
  13153. type: 'float',
  13154. inputs: [
  13155. { name: 'alpha', type: 'float' },
  13156. { name: 'dotNH', type: 'float' }
  13157. ]
  13158. } ); // validated
  13159. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  13160. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  13161. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  13162. const a2 = alphaT.mul( alphaB );
  13163. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  13164. const v2 = v.dot( v );
  13165. const w2 = a2.div( v2 );
  13166. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  13167. } ).setLayout( {
  13168. name: 'D_GGX_Anisotropic',
  13169. type: 'float',
  13170. inputs: [
  13171. { name: 'alphaT', type: 'float', qualifier: 'in' },
  13172. { name: 'alphaB', type: 'float', qualifier: 'in' },
  13173. { name: 'dotNH', type: 'float', qualifier: 'in' },
  13174. { name: 'dotTH', type: 'float', qualifier: 'in' },
  13175. { name: 'dotBH', type: 'float', qualifier: 'in' }
  13176. ]
  13177. } );
  13178. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  13179. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  13180. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  13181. const normalView = inputs.normalView || transformedNormalView;
  13182. const alpha = roughness.pow2(); // UE4's roughness
  13183. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13184. const dotNL = normalView.dot( lightDirection ).clamp();
  13185. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13186. const dotNH = normalView.dot( halfDir ).clamp();
  13187. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  13188. let F = F_Schlick( { f0, f90, dotVH } );
  13189. let V, D;
  13190. if ( defined( USE_IRIDESCENCE ) ) {
  13191. F = iridescence.mix( F, f );
  13192. }
  13193. if ( defined( USE_ANISOTROPY ) ) {
  13194. const dotTL = anisotropyT.dot( lightDirection );
  13195. const dotTV = anisotropyT.dot( positionViewDirection );
  13196. const dotTH = anisotropyT.dot( halfDir );
  13197. const dotBL = anisotropyB.dot( lightDirection );
  13198. const dotBV = anisotropyB.dot( positionViewDirection );
  13199. const dotBH = anisotropyB.dot( halfDir );
  13200. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  13201. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  13202. } else {
  13203. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  13204. D = D_GGX( { alpha, dotNH } );
  13205. }
  13206. return F.mul( V ).mul( D );
  13207. } ); // validated
  13208. // Analytical approximation of the DFG LUT, one half of the
  13209. // split-sum approximation used in indirect specular lighting.
  13210. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  13211. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  13212. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  13213. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  13214. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  13215. const r = roughness.mul( c0 ).add( c1 );
  13216. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  13217. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  13218. return fab;
  13219. } ).setLayout( {
  13220. name: 'DFGApprox',
  13221. type: 'vec2',
  13222. inputs: [
  13223. { name: 'roughness', type: 'float' },
  13224. { name: 'dotNV', type: 'vec3' }
  13225. ]
  13226. } );
  13227. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  13228. const { dotNV, specularColor, specularF90, roughness } = inputs;
  13229. const fab = DFGApprox( { dotNV, roughness } );
  13230. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  13231. } );
  13232. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  13233. const x = dotVH.oneMinus().saturate();
  13234. const x2 = x.mul( x );
  13235. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  13236. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  13237. } ).setLayout( {
  13238. name: 'Schlick_to_F0',
  13239. type: 'vec3',
  13240. inputs: [
  13241. { name: 'f', type: 'vec3' },
  13242. { name: 'f90', type: 'float' },
  13243. { name: 'dotVH', type: 'float' }
  13244. ]
  13245. } );
  13246. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  13247. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  13248. const alpha = roughness.pow2();
  13249. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  13250. const invAlpha = float( 1.0 ).div( alpha );
  13251. const cos2h = dotNH.pow2();
  13252. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  13253. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  13254. } ).setLayout( {
  13255. name: 'D_Charlie',
  13256. type: 'float',
  13257. inputs: [
  13258. { name: 'roughness', type: 'float' },
  13259. { name: 'dotNH', type: 'float' }
  13260. ]
  13261. } );
  13262. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  13263. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  13264. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  13265. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  13266. } ).setLayout( {
  13267. name: 'V_Neubelt',
  13268. type: 'float',
  13269. inputs: [
  13270. { name: 'dotNV', type: 'float' },
  13271. { name: 'dotNL', type: 'float' }
  13272. ]
  13273. } );
  13274. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  13275. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13276. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  13277. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  13278. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  13279. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  13280. const V = V_Neubelt( { dotNV, dotNL } );
  13281. return sheen.mul( D ).mul( V );
  13282. } );
  13283. // Rect Area Light
  13284. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  13285. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  13286. // code: https://github.com/selfshadow/ltc_code/
  13287. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  13288. const LUT_SIZE = 64.0;
  13289. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  13290. const LUT_BIAS = 0.5 / LUT_SIZE;
  13291. const dotNV = N.dot( V ).saturate();
  13292. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  13293. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  13294. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  13295. return uv;
  13296. } ).setLayout( {
  13297. name: 'LTC_Uv',
  13298. type: 'vec2',
  13299. inputs: [
  13300. { name: 'N', type: 'vec3' },
  13301. { name: 'V', type: 'vec3' },
  13302. { name: 'roughness', type: 'float' }
  13303. ]
  13304. } );
  13305. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  13306. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  13307. // An approximation of the form factor of a horizon-clipped rectangle.
  13308. const l = f.length();
  13309. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  13310. } ).setLayout( {
  13311. name: 'LTC_ClippedSphereFormFactor',
  13312. type: 'float',
  13313. inputs: [
  13314. { name: 'f', type: 'vec3' }
  13315. ]
  13316. } );
  13317. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  13318. const x = v1.dot( v2 );
  13319. const y = x.abs().toVar();
  13320. // rational polynomial approximation to theta / sin( theta ) / 2PI
  13321. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  13322. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  13323. const v = a.div( b );
  13324. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  13325. return v1.cross( v2 ).mul( theta_sintheta );
  13326. } ).setLayout( {
  13327. name: 'LTC_EdgeVectorFormFactor',
  13328. type: 'vec3',
  13329. inputs: [
  13330. { name: 'v1', type: 'vec3' },
  13331. { name: 'v2', type: 'vec3' }
  13332. ]
  13333. } );
  13334. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  13335. // bail if point is on back side of plane of light
  13336. // assumes ccw winding order of light vertices
  13337. const v1 = p1.sub( p0 ).toVar();
  13338. const v2 = p3.sub( p0 ).toVar();
  13339. const lightNormal = v1.cross( v2 );
  13340. const result = vec3().toVar();
  13341. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  13342. // construct orthonormal basis around N
  13343. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  13344. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  13345. // compute transform
  13346. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  13347. // transform rect
  13348. // & project rect onto sphere
  13349. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  13350. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  13351. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  13352. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  13353. // calculate vector form factor
  13354. const vectorFormFactor = vec3( 0 ).toVar();
  13355. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  13356. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  13357. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  13358. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  13359. // adjust for horizon clipping
  13360. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  13361. } );
  13362. return result;
  13363. } ).setLayout( {
  13364. name: 'LTC_Evaluate',
  13365. type: 'vec3',
  13366. inputs: [
  13367. { name: 'N', type: 'vec3' },
  13368. { name: 'V', type: 'vec3' },
  13369. { name: 'P', type: 'vec3' },
  13370. { name: 'mInv', type: 'mat3' },
  13371. { name: 'p0', type: 'vec3' },
  13372. { name: 'p1', type: 'vec3' },
  13373. { name: 'p2', type: 'vec3' },
  13374. { name: 'p3', type: 'vec3' }
  13375. ]
  13376. } );
  13377. /** @module TextureBicubic **/
  13378. // Mipped Bicubic Texture Filtering by N8
  13379. // https://www.shadertoy.com/view/Dl2SDW
  13380. const bC = 1.0 / 6.0;
  13381. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  13382. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  13383. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  13384. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  13385. const g0 = ( a ) => w0( a ).add( w1( a ) );
  13386. const g1 = ( a ) => w2( a ).add( w3( a ) );
  13387. // h0 and h1 are the two offset functions
  13388. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  13389. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  13390. const bicubic = ( textureNode, texelSize, lod ) => {
  13391. const uv = textureNode.uvNode;
  13392. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  13393. const iuv = floor( uvScaled );
  13394. const fuv = fract( uvScaled );
  13395. const g0x = g0( fuv.x );
  13396. const g1x = g1( fuv.x );
  13397. const h0x = h0( fuv.x );
  13398. const h1x = h1( fuv.x );
  13399. const h0y = h0( fuv.y );
  13400. const h1y = h1( fuv.y );
  13401. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  13402. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  13403. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  13404. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  13405. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  13406. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  13407. return a.add( b );
  13408. };
  13409. /**
  13410. * Applies mipped bicubic texture filtering to the given texture node.
  13411. *
  13412. * @method
  13413. * @param {TextureNode} textureNode - The texture node that should be filtered.
  13414. * @param {Node<float>} [lodNode=float(3)] - Defines the LOD to sample from.
  13415. * @return {Node} The filtered texture sample.
  13416. */
  13417. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  13418. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  13419. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  13420. const fLodSizeInv = div( 1.0, fLodSize );
  13421. const cLodSizeInv = div( 1.0, cLodSize );
  13422. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  13423. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  13424. return fract( lodNode ).mix( fSample, cSample );
  13425. } );
  13426. //
  13427. // Transmission
  13428. //
  13429. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  13430. // Direction of refracted light.
  13431. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  13432. // Compute rotation-independent scaling of the model matrix.
  13433. const modelScale = vec3(
  13434. length( modelMatrix[ 0 ].xyz ),
  13435. length( modelMatrix[ 1 ].xyz ),
  13436. length( modelMatrix[ 2 ].xyz )
  13437. );
  13438. // The thickness is specified in local space.
  13439. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  13440. } ).setLayout( {
  13441. name: 'getVolumeTransmissionRay',
  13442. type: 'vec3',
  13443. inputs: [
  13444. { name: 'n', type: 'vec3' },
  13445. { name: 'v', type: 'vec3' },
  13446. { name: 'thickness', type: 'float' },
  13447. { name: 'ior', type: 'float' },
  13448. { name: 'modelMatrix', type: 'mat4' }
  13449. ]
  13450. } );
  13451. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  13452. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  13453. // an IOR of 1.5 results in the default amount of microfacet refraction.
  13454. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  13455. } ).setLayout( {
  13456. name: 'applyIorToRoughness',
  13457. type: 'float',
  13458. inputs: [
  13459. { name: 'roughness', type: 'float' },
  13460. { name: 'ior', type: 'float' }
  13461. ]
  13462. } );
  13463. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  13464. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  13465. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  13466. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  13467. const transmissionSample = vTexture.sample( fragCoord );
  13468. //const transmissionSample = viewportMipTexture( fragCoord );
  13469. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  13470. return textureBicubic( transmissionSample, lod );
  13471. } );
  13472. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  13473. If( attenuationDistance.notEqual( 0 ), () => {
  13474. // Compute light attenuation using Beer's law.
  13475. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  13476. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  13477. return transmittance;
  13478. } );
  13479. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  13480. return vec3( 1.0 );
  13481. } ).setLayout( {
  13482. name: 'volumeAttenuation',
  13483. type: 'vec3',
  13484. inputs: [
  13485. { name: 'transmissionDistance', type: 'float' },
  13486. { name: 'attenuationColor', type: 'vec3' },
  13487. { name: 'attenuationDistance', type: 'float' }
  13488. ]
  13489. } );
  13490. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  13491. let transmittedLight, transmittance;
  13492. if ( dispersion ) {
  13493. transmittedLight = vec4().toVar();
  13494. transmittance = vec3().toVar();
  13495. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  13496. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  13497. Loop( { start: 0, end: 3 }, ( { i } ) => {
  13498. const ior = iors.element( i );
  13499. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  13500. const refractedRayExit = position.add( transmissionRay );
  13501. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  13502. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  13503. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  13504. refractionCoords.addAssign( 1.0 );
  13505. refractionCoords.divAssign( 2.0 );
  13506. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  13507. // Sample framebuffer to get pixel the refracted ray hits.
  13508. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  13509. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  13510. transmittedLight.a.addAssign( transmissionSample.a );
  13511. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  13512. } );
  13513. transmittedLight.a.divAssign( 3.0 );
  13514. } else {
  13515. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  13516. const refractedRayExit = position.add( transmissionRay );
  13517. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  13518. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  13519. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  13520. refractionCoords.addAssign( 1.0 );
  13521. refractionCoords.divAssign( 2.0 );
  13522. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  13523. // Sample framebuffer to get pixel the refracted ray hits.
  13524. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  13525. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  13526. }
  13527. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  13528. const dotNV = n.dot( v ).clamp();
  13529. // Get the specular component.
  13530. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  13531. dotNV,
  13532. specularColor,
  13533. specularF90,
  13534. roughness
  13535. } ) );
  13536. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  13537. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  13538. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  13539. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  13540. } );
  13541. //
  13542. // Iridescence
  13543. //
  13544. // XYZ to linear-sRGB color space
  13545. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  13546. 3.2404542, - 0.9692660, 0.0556434,
  13547. - 1.5371385, 1.8760108, - 0.2040259,
  13548. - 0.4985314, 0.0415560, 1.0572252
  13549. );
  13550. // Assume air interface for top
  13551. // Note: We don't handle the case fresnel0 == 1
  13552. const Fresnel0ToIor = ( fresnel0 ) => {
  13553. const sqrtF0 = fresnel0.sqrt();
  13554. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  13555. };
  13556. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  13557. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  13558. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  13559. };
  13560. // Fresnel equations for dielectric/dielectric interfaces.
  13561. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  13562. // Evaluation XYZ sensitivity curves in Fourier space
  13563. const evalSensitivity = ( OPD, shift ) => {
  13564. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  13565. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  13566. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  13567. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  13568. 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() );
  13569. 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() );
  13570. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  13571. const rgb = XYZ_TO_REC709.mul( xyz );
  13572. return rgb;
  13573. };
  13574. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  13575. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  13576. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  13577. // Evaluate the cosTheta on the base layer (Snell law)
  13578. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  13579. // Handle TIR:
  13580. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  13581. If( cosTheta2Sq.lessThan( 0 ), () => {
  13582. return vec3( 1.0 );
  13583. } );
  13584. const cosTheta2 = cosTheta2Sq.sqrt();
  13585. // First interface
  13586. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  13587. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  13588. //const R21 = R12;
  13589. const T121 = R12.oneMinus();
  13590. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  13591. const phi21 = float( Math.PI ).sub( phi12 );
  13592. // Second interface
  13593. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  13594. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  13595. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  13596. const phi23 = vec3(
  13597. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  13598. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  13599. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  13600. );
  13601. // Phase shift
  13602. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  13603. const phi = vec3( phi21 ).add( phi23 );
  13604. // Compound terms
  13605. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  13606. const r123 = R123.sqrt();
  13607. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  13608. // Reflectance term for m = 0 (DC term amplitude)
  13609. const C0 = R12.add( Rs );
  13610. const I = C0.toVar();
  13611. // Reflectance term for m > 0 (pairs of diracs)
  13612. const Cm = Rs.sub( T121 ).toVar();
  13613. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  13614. Cm.mulAssign( r123 );
  13615. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  13616. I.addAssign( Cm.mul( Sm ) );
  13617. } );
  13618. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  13619. return I.max( vec3( 0.0 ) );
  13620. } ).setLayout( {
  13621. name: 'evalIridescence',
  13622. type: 'vec3',
  13623. inputs: [
  13624. { name: 'outsideIOR', type: 'float' },
  13625. { name: 'eta2', type: 'float' },
  13626. { name: 'cosTheta1', type: 'float' },
  13627. { name: 'thinFilmThickness', type: 'float' },
  13628. { name: 'baseF0', type: 'vec3' }
  13629. ]
  13630. } );
  13631. //
  13632. // Sheen
  13633. //
  13634. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  13635. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  13636. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  13637. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  13638. const dotNV = normal.dot( viewDir ).saturate();
  13639. const r2 = roughness.pow2();
  13640. const a = select(
  13641. roughness.lessThan( 0.25 ),
  13642. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  13643. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  13644. );
  13645. const b = select(
  13646. roughness.lessThan( 0.25 ),
  13647. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  13648. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  13649. );
  13650. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  13651. return DG.mul( 1.0 / Math.PI ).saturate();
  13652. } );
  13653. const clearcoatF0 = vec3( 0.04 );
  13654. const clearcoatF90 = float( 1 );
  13655. /**
  13656. * Represents the lighting model for a PBR material.
  13657. *
  13658. * @augments LightingModel
  13659. */
  13660. class PhysicalLightingModel extends LightingModel {
  13661. /**
  13662. * Constructs a new physical lighting model.
  13663. *
  13664. * @param {Boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  13665. * @param {Boolean} [sheen=false] - Whether sheen is supported or not.
  13666. * @param {Boolean} [iridescence=false] - Whether iridescence is supported or not.
  13667. * @param {Boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  13668. * @param {Boolean} [transmission=false] - Whether transmission is supported or not.
  13669. * @param {Boolean} [dispersion=false] - Whether dispersion is supported or not.
  13670. */
  13671. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  13672. super();
  13673. /**
  13674. * Whether clearcoat is supported or not.
  13675. *
  13676. * @type {Boolean}
  13677. * @default false
  13678. */
  13679. this.clearcoat = clearcoat;
  13680. /**
  13681. * Whether sheen is supported or not.
  13682. *
  13683. * @type {Boolean}
  13684. * @default false
  13685. */
  13686. this.sheen = sheen;
  13687. /**
  13688. * Whether iridescence is supported or not.
  13689. *
  13690. * @type {Boolean}
  13691. * @default false
  13692. */
  13693. this.iridescence = iridescence;
  13694. /**
  13695. * Whether anisotropy is supported or not.
  13696. *
  13697. * @type {Boolean}
  13698. * @default false
  13699. */
  13700. this.anisotropy = anisotropy;
  13701. /**
  13702. * Whether transmission is supported or not.
  13703. *
  13704. * @type {Boolean}
  13705. * @default false
  13706. */
  13707. this.transmission = transmission;
  13708. /**
  13709. * Whether dispersion is supported or not.
  13710. *
  13711. * @type {Boolean}
  13712. * @default false
  13713. */
  13714. this.dispersion = dispersion;
  13715. /**
  13716. * The clear coat radiance.
  13717. *
  13718. * @type {Node?}
  13719. * @default null
  13720. */
  13721. this.clearcoatRadiance = null;
  13722. /**
  13723. * The clear coat specular direct.
  13724. *
  13725. * @type {Node?}
  13726. * @default null
  13727. */
  13728. this.clearcoatSpecularDirect = null;
  13729. /**
  13730. * The clear coat specular indirect.
  13731. *
  13732. * @type {Node?}
  13733. * @default null
  13734. */
  13735. this.clearcoatSpecularIndirect = null;
  13736. /**
  13737. * The sheen specular direct.
  13738. *
  13739. * @type {Node?}
  13740. * @default null
  13741. */
  13742. this.sheenSpecularDirect = null;
  13743. /**
  13744. * The sheen specular indirect.
  13745. *
  13746. * @type {Node?}
  13747. * @default null
  13748. */
  13749. this.sheenSpecularIndirect = null;
  13750. /**
  13751. * The iridescence Fresnel.
  13752. *
  13753. * @type {Node?}
  13754. * @default null
  13755. */
  13756. this.iridescenceFresnel = null;
  13757. /**
  13758. * The iridescence F0.
  13759. *
  13760. * @type {Node?}
  13761. * @default null
  13762. */
  13763. this.iridescenceF0 = null;
  13764. }
  13765. /**
  13766. * Depending on what features are requested, the method prepares certain node variables
  13767. * which are later used for lighting computations.
  13768. *
  13769. * @param {ContextNode} context - The current node context.
  13770. */
  13771. start( context ) {
  13772. if ( this.clearcoat === true ) {
  13773. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  13774. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  13775. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  13776. }
  13777. if ( this.sheen === true ) {
  13778. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  13779. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  13780. }
  13781. if ( this.iridescence === true ) {
  13782. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  13783. this.iridescenceFresnel = evalIridescence( {
  13784. outsideIOR: float( 1.0 ),
  13785. eta2: iridescenceIOR,
  13786. cosTheta1: dotNVi,
  13787. thinFilmThickness: iridescenceThickness,
  13788. baseF0: specularColor
  13789. } );
  13790. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  13791. }
  13792. if ( this.transmission === true ) {
  13793. const position = positionWorld;
  13794. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  13795. const n = transformedNormalWorld;
  13796. context.backdrop = getIBLVolumeRefraction(
  13797. n,
  13798. v,
  13799. roughness,
  13800. diffuseColor,
  13801. specularColor,
  13802. specularF90, // specularF90
  13803. position, // positionWorld
  13804. modelWorldMatrix, // modelMatrix
  13805. cameraViewMatrix, // viewMatrix
  13806. cameraProjectionMatrix, // projMatrix
  13807. ior,
  13808. thickness,
  13809. attenuationColor,
  13810. attenuationDistance,
  13811. this.dispersion ? dispersion : null
  13812. );
  13813. context.backdropAlpha = transmission;
  13814. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  13815. }
  13816. }
  13817. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  13818. // Approximates multi-scattering in order to preserve energy.
  13819. // http://www.jcgt.org/published/0008/01/03/
  13820. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  13821. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13822. const fab = DFGApprox( { roughness, dotNV } );
  13823. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  13824. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  13825. const Ess = fab.x.add( fab.y );
  13826. const Ems = Ess.oneMinus();
  13827. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  13828. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  13829. singleScatter.addAssign( FssEss );
  13830. multiScatter.addAssign( Fms.mul( Ems ) );
  13831. }
  13832. /**
  13833. * Implements the direct light.
  13834. *
  13835. * @param {Object} input - The input data.
  13836. * @param {StackNode} stack - The current stack.
  13837. * @param {NodeBuilder} builder - The current node builder.
  13838. */
  13839. direct( { lightDirection, lightColor, reflectedLight } ) {
  13840. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  13841. const irradiance = dotNL.mul( lightColor );
  13842. if ( this.sheen === true ) {
  13843. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  13844. }
  13845. if ( this.clearcoat === true ) {
  13846. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  13847. const ccIrradiance = dotNLcc.mul( lightColor );
  13848. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  13849. }
  13850. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  13851. 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 } ) ) );
  13852. }
  13853. /**
  13854. * This method is intended for implementing the direct light term for
  13855. * rect area light nodes.
  13856. *
  13857. * @param {Object} input - The input data.
  13858. * @param {StackNode} stack - The current stack.
  13859. * @param {NodeBuilder} builder - The current node builder.
  13860. */
  13861. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  13862. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  13863. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  13864. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  13865. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  13866. const N = transformedNormalView;
  13867. const V = positionViewDirection;
  13868. const P = positionView.toVar();
  13869. const uv = LTC_Uv( { N, V, roughness } );
  13870. const t1 = ltc_1.sample( uv ).toVar();
  13871. const t2 = ltc_2.sample( uv ).toVar();
  13872. const mInv = mat3(
  13873. vec3( t1.x, 0, t1.y ),
  13874. vec3( 0, 1, 0 ),
  13875. vec3( t1.z, 0, t1.w )
  13876. ).toVar();
  13877. // LTC Fresnel Approximation by Stephen Hill
  13878. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  13879. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  13880. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  13881. 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 } ) ) );
  13882. }
  13883. /**
  13884. * Implements the indirect lighting.
  13885. *
  13886. * @param {ContextNode} context - The current node context.
  13887. * @param {StackNode} stack - The current stack.
  13888. * @param {NodeBuilder} builder - The current node builder.
  13889. */
  13890. indirect( context, stack, builder ) {
  13891. this.indirectDiffuse( context, stack, builder );
  13892. this.indirectSpecular( context, stack, builder );
  13893. this.ambientOcclusion( context, stack, builder );
  13894. }
  13895. /**
  13896. * Implements the indirect diffuse term.
  13897. *
  13898. * @param {ContextNode} input - The current node context.
  13899. * @param {StackNode} stack - The current stack.
  13900. * @param {NodeBuilder} builder - The current node builder.
  13901. */
  13902. indirectDiffuse( { irradiance, reflectedLight } ) {
  13903. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  13904. }
  13905. /**
  13906. * Implements the indirect specular term.
  13907. *
  13908. * @param {ContextNode} input - The current node context.
  13909. * @param {StackNode} stack - The current stack.
  13910. * @param {NodeBuilder} builder - The current node builder.
  13911. */
  13912. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  13913. if ( this.sheen === true ) {
  13914. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  13915. sheen,
  13916. IBLSheenBRDF( {
  13917. normal: transformedNormalView,
  13918. viewDir: positionViewDirection,
  13919. roughness: sheenRoughness
  13920. } )
  13921. ) );
  13922. }
  13923. if ( this.clearcoat === true ) {
  13924. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  13925. const clearcoatEnv = EnvironmentBRDF( {
  13926. dotNV: dotNVcc,
  13927. specularColor: clearcoatF0,
  13928. specularF90: clearcoatF90,
  13929. roughness: clearcoatRoughness
  13930. } );
  13931. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  13932. }
  13933. // Both indirect specular and indirect diffuse light accumulate here
  13934. const singleScattering = vec3().toVar( 'singleScattering' );
  13935. const multiScattering = vec3().toVar( 'multiScattering' );
  13936. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  13937. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  13938. const totalScattering = singleScattering.add( multiScattering );
  13939. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  13940. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  13941. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  13942. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  13943. }
  13944. /**
  13945. * Implements the ambient occlusion term.
  13946. *
  13947. * @param {ContextNode} input - The current node context.
  13948. * @param {StackNode} stack - The current stack.
  13949. * @param {NodeBuilder} builder - The current node builder.
  13950. */
  13951. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  13952. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13953. const aoNV = dotNV.add( ambientOcclusion );
  13954. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  13955. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  13956. if ( this.clearcoat === true ) {
  13957. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  13958. }
  13959. if ( this.sheen === true ) {
  13960. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  13961. }
  13962. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  13963. reflectedLight.indirectSpecular.mulAssign( aoNode );
  13964. }
  13965. /**
  13966. * Used for final lighting accumulations depending on the requested features.
  13967. *
  13968. * @param {ContextNode} context - The current node context.
  13969. * @param {StackNode} stack - The current stack.
  13970. * @param {NodeBuilder} builder - The current node builder.
  13971. */
  13972. finish( context ) {
  13973. const { outgoingLight } = context;
  13974. if ( this.clearcoat === true ) {
  13975. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  13976. const Fcc = F_Schlick( {
  13977. dotVH: dotNVcc,
  13978. f0: clearcoatF0,
  13979. f90: clearcoatF90
  13980. } );
  13981. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  13982. outgoingLight.assign( clearcoatLight );
  13983. }
  13984. if ( this.sheen === true ) {
  13985. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  13986. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  13987. outgoingLight.assign( sheenLight );
  13988. }
  13989. }
  13990. }
  13991. // These defines must match with PMREMGenerator
  13992. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  13993. const cubeUV_m0 = /*@__PURE__*/ float( - 2.0 );
  13994. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  13995. const cubeUV_m1 = /*@__PURE__*/ float( - 1.0 );
  13996. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  13997. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  13998. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  13999. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  14000. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  14001. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  14002. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  14003. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  14004. // These shader functions convert between the UV coordinates of a single face of
  14005. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  14006. // sampling a textureCube (not generally normalized ).
  14007. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  14008. const absDirection = vec3( abs( direction ) ).toVar();
  14009. const face = float( - 1.0 ).toVar();
  14010. If( absDirection.x.greaterThan( absDirection.z ), () => {
  14011. If( absDirection.x.greaterThan( absDirection.y ), () => {
  14012. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  14013. } ).Else( () => {
  14014. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  14015. } );
  14016. } ).Else( () => {
  14017. If( absDirection.z.greaterThan( absDirection.y ), () => {
  14018. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  14019. } ).Else( () => {
  14020. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  14021. } );
  14022. } );
  14023. return face;
  14024. } ).setLayout( {
  14025. name: 'getFace',
  14026. type: 'float',
  14027. inputs: [
  14028. { name: 'direction', type: 'vec3' }
  14029. ]
  14030. } );
  14031. // RH coordinate system; PMREM face-indexing convention
  14032. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  14033. const uv = vec2().toVar();
  14034. If( face.equal( 0.0 ), () => {
  14035. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  14036. } ).ElseIf( face.equal( 1.0 ), () => {
  14037. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  14038. } ).ElseIf( face.equal( 2.0 ), () => {
  14039. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  14040. } ).ElseIf( face.equal( 3.0 ), () => {
  14041. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  14042. } ).ElseIf( face.equal( 4.0 ), () => {
  14043. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  14044. } ).Else( () => {
  14045. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  14046. } );
  14047. return mul( 0.5, uv.add( 1.0 ) );
  14048. } ).setLayout( {
  14049. name: 'getUV',
  14050. type: 'vec2',
  14051. inputs: [
  14052. { name: 'direction', type: 'vec3' },
  14053. { name: 'face', type: 'float' }
  14054. ]
  14055. } );
  14056. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  14057. const mip = float( 0.0 ).toVar();
  14058. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  14059. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  14060. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  14061. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  14062. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  14063. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  14064. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  14065. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  14066. } ).Else( () => {
  14067. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  14068. } );
  14069. return mip;
  14070. } ).setLayout( {
  14071. name: 'roughnessToMip',
  14072. type: 'float',
  14073. inputs: [
  14074. { name: 'roughness', type: 'float' }
  14075. ]
  14076. } );
  14077. // RH coordinate system; PMREM face-indexing convention
  14078. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  14079. const uv = uv_immutable.toVar();
  14080. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  14081. const direction = vec3( uv, 1.0 ).toVar();
  14082. If( face.equal( 0.0 ), () => {
  14083. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  14084. } ).ElseIf( face.equal( 1.0 ), () => {
  14085. direction.assign( direction.xzy );
  14086. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  14087. } ).ElseIf( face.equal( 2.0 ), () => {
  14088. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  14089. } ).ElseIf( face.equal( 3.0 ), () => {
  14090. direction.assign( direction.zyx );
  14091. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  14092. } ).ElseIf( face.equal( 4.0 ), () => {
  14093. direction.assign( direction.xzy );
  14094. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  14095. } ).ElseIf( face.equal( 5.0 ), () => {
  14096. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  14097. } );
  14098. return direction;
  14099. } ).setLayout( {
  14100. name: 'getDirection',
  14101. type: 'vec3',
  14102. inputs: [
  14103. { name: 'uv', type: 'vec2' },
  14104. { name: 'face', type: 'float' }
  14105. ]
  14106. } );
  14107. //
  14108. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  14109. const roughness = float( roughness_immutable );
  14110. const sampleDir = vec3( sampleDir_immutable );
  14111. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  14112. const mipF = fract( mip );
  14113. const mipInt = floor( mip );
  14114. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  14115. If( mipF.notEqual( 0.0 ), () => {
  14116. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  14117. color0.assign( mix( color0, color1, mipF ) );
  14118. } );
  14119. return color0;
  14120. } );
  14121. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  14122. const mipInt = float( mipInt_immutable ).toVar();
  14123. const direction = vec3( direction_immutable );
  14124. const face = float( getFace( direction ) ).toVar();
  14125. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  14126. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  14127. const faceSize = float( exp2( mipInt ) ).toVar();
  14128. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  14129. If( face.greaterThan( 2.0 ), () => {
  14130. uv.y.addAssign( faceSize );
  14131. face.subAssign( 3.0 );
  14132. } );
  14133. uv.x.addAssign( face.mul( faceSize ) );
  14134. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  14135. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  14136. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  14137. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  14138. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  14139. } );
  14140. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  14141. const cosTheta = cos( theta );
  14142. // Rodrigues' axis-angle rotation
  14143. const sampleDirection = outputDirection.mul( cosTheta )
  14144. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  14145. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  14146. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  14147. } );
  14148. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  14149. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  14150. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  14151. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  14152. } );
  14153. axis.assign( normalize( axis ) );
  14154. const gl_FragColor = vec3().toVar();
  14155. 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 } ) ) );
  14156. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  14157. If( i.greaterThanEqual( samples ), () => {
  14158. Break();
  14159. } );
  14160. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  14161. 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 } ) ) );
  14162. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14163. } );
  14164. return vec4( gl_FragColor, 1 );
  14165. } );
  14166. /** @module PMREMNode **/
  14167. let _generator = null;
  14168. const _cache = new WeakMap();
  14169. /**
  14170. * Generates the cubeUV size based on the given image height.
  14171. *
  14172. * @private
  14173. * @param {Number} imageHeight - The image height.
  14174. * @return {{texelWidth: Number,texelHeight: Number, maxMip: Number}} The result object.
  14175. */
  14176. function _generateCubeUVSize( imageHeight ) {
  14177. const maxMip = Math.log2( imageHeight ) - 2;
  14178. const texelHeight = 1.0 / imageHeight;
  14179. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  14180. return { texelWidth, texelHeight, maxMip };
  14181. }
  14182. /**
  14183. * Generates a PMREM from the given texture .
  14184. *
  14185. * @private
  14186. * @param {Texture} texture - The texture to create the PMREM for.
  14187. * @return {Texture} The PMREM.
  14188. */
  14189. function _getPMREMFromTexture( texture ) {
  14190. let cacheTexture = _cache.get( texture );
  14191. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  14192. if ( pmremVersion !== texture.pmremVersion ) {
  14193. const image = texture.image;
  14194. if ( texture.isCubeTexture ) {
  14195. if ( isCubeMapReady( image ) ) {
  14196. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  14197. } else {
  14198. return null;
  14199. }
  14200. } else {
  14201. if ( isEquirectangularMapReady( image ) ) {
  14202. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  14203. } else {
  14204. return null;
  14205. }
  14206. }
  14207. cacheTexture.pmremVersion = texture.pmremVersion;
  14208. _cache.set( texture, cacheTexture );
  14209. }
  14210. return cacheTexture.texture;
  14211. }
  14212. /**
  14213. * This node represents a PMREM which is a special type of preprocessed
  14214. * environment map intended for PBR materials.
  14215. *
  14216. * ```js
  14217. * const material = new MeshStandardNodeMaterial();
  14218. * material.envNode = pmremTexture( envMap );
  14219. * ```
  14220. *
  14221. * @augments TempNode
  14222. */
  14223. class PMREMNode extends TempNode {
  14224. static get type() {
  14225. return 'PMREMNode';
  14226. }
  14227. /**
  14228. * Constructs a new function overloading node.
  14229. *
  14230. * @param {Texture} value - The input texture.
  14231. * @param {Node<vec2>} [uvNode=null] - The uv node.
  14232. * @param {Node<float>} [levelNode=null] - The level node.
  14233. */
  14234. constructor( value, uvNode = null, levelNode = null ) {
  14235. super( 'vec3' );
  14236. /**
  14237. * Reference to the input texture.
  14238. *
  14239. * @private
  14240. * @type {Texture}
  14241. */
  14242. this._value = value;
  14243. /**
  14244. * Reference to the generated PMREM.
  14245. *
  14246. * @private
  14247. * @type {Texture | null}
  14248. * @default null
  14249. */
  14250. this._pmrem = null;
  14251. /**
  14252. * The uv node.
  14253. *
  14254. * @type {Node<vec2>}
  14255. */
  14256. this.uvNode = uvNode;
  14257. /**
  14258. * The level node.
  14259. *
  14260. * @type {Node<float>}
  14261. */
  14262. this.levelNode = levelNode;
  14263. /**
  14264. * Reference to a PMREM generator.
  14265. *
  14266. * @private
  14267. * @type {PMREMGenerator}
  14268. * @default null
  14269. */
  14270. this._generator = null;
  14271. const defaultTexture = new Texture();
  14272. defaultTexture.isRenderTargetTexture = true;
  14273. /**
  14274. * The texture node holding the generated PMREM.
  14275. *
  14276. * @private
  14277. * @type {TextureNode}
  14278. */
  14279. this._texture = texture( defaultTexture );
  14280. /**
  14281. * A uniform representing the PMREM's width.
  14282. *
  14283. * @private
  14284. * @type {UniformNode<float>}
  14285. */
  14286. this._width = uniform( 0 );
  14287. /**
  14288. * A uniform representing the PMREM's height.
  14289. *
  14290. * @private
  14291. * @type {UniformNode<float>}
  14292. */
  14293. this._height = uniform( 0 );
  14294. /**
  14295. * A uniform representing the PMREM's max Mip.
  14296. *
  14297. * @private
  14298. * @type {UniformNode<float>}
  14299. */
  14300. this._maxMip = uniform( 0 );
  14301. /**
  14302. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  14303. *
  14304. * @type {String}
  14305. * @default 'render'
  14306. */
  14307. this.updateBeforeType = NodeUpdateType.RENDER;
  14308. }
  14309. set value( value ) {
  14310. this._value = value;
  14311. this._pmrem = null;
  14312. }
  14313. /**
  14314. * The node's texture value.
  14315. *
  14316. * @type {Texture}
  14317. */
  14318. get value() {
  14319. return this._value;
  14320. }
  14321. /**
  14322. * Uses the given PMREM texture to update internal values.
  14323. *
  14324. * @param {Texture} texture - The PMREM texture.
  14325. */
  14326. updateFromTexture( texture ) {
  14327. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  14328. this._texture.value = texture;
  14329. this._width.value = cubeUVSize.texelWidth;
  14330. this._height.value = cubeUVSize.texelHeight;
  14331. this._maxMip.value = cubeUVSize.maxMip;
  14332. }
  14333. updateBefore() {
  14334. let pmrem = this._pmrem;
  14335. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  14336. const texture = this._value;
  14337. if ( pmremVersion !== texture.pmremVersion ) {
  14338. if ( texture.isPMREMTexture === true ) {
  14339. pmrem = texture;
  14340. } else {
  14341. pmrem = _getPMREMFromTexture( texture );
  14342. }
  14343. if ( pmrem !== null ) {
  14344. this._pmrem = pmrem;
  14345. this.updateFromTexture( pmrem );
  14346. }
  14347. }
  14348. }
  14349. setup( builder ) {
  14350. if ( _generator === null ) {
  14351. _generator = builder.createPMREMGenerator();
  14352. }
  14353. //
  14354. this.updateBefore( builder );
  14355. //
  14356. let uvNode = this.uvNode;
  14357. if ( uvNode === null && builder.context.getUV ) {
  14358. uvNode = builder.context.getUV( this );
  14359. }
  14360. //
  14361. const texture = this.value;
  14362. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  14363. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  14364. }
  14365. uvNode = vec3( uvNode.x, uvNode.y.negate(), uvNode.z );
  14366. //
  14367. let levelNode = this.levelNode;
  14368. if ( levelNode === null && builder.context.getTextureLevel ) {
  14369. levelNode = builder.context.getTextureLevel( this );
  14370. }
  14371. //
  14372. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  14373. }
  14374. }
  14375. /**
  14376. * Returns `true` if the given cube map image has been fully loaded.
  14377. *
  14378. * @private
  14379. * @param {Array<(Image|Object)>} image - The cube map image.
  14380. * @return {Boolean} Whether the given cube map is ready or not.
  14381. */
  14382. function isCubeMapReady( image ) {
  14383. if ( image === null || image === undefined ) return false;
  14384. let count = 0;
  14385. const length = 6;
  14386. for ( let i = 0; i < length; i ++ ) {
  14387. if ( image[ i ] !== undefined ) count ++;
  14388. }
  14389. return count === length;
  14390. }
  14391. /**
  14392. * Returns `true` if the given equirectangular image has been fully loaded.
  14393. *
  14394. * @private
  14395. * @param {(Image|Object)} image - The equirectangular image.
  14396. * @return {Boolean} Whether the given cube map is ready or not.
  14397. */
  14398. function isEquirectangularMapReady( image ) {
  14399. if ( image === null || image === undefined ) return false;
  14400. return image.height > 0;
  14401. }
  14402. /**
  14403. * TSL function for creating a PMREM node.
  14404. *
  14405. * @function
  14406. * @param {Texture} value - The input texture.
  14407. * @param {Node<vec2>} [uvNode=null] - The uv node.
  14408. * @param {Node<float>} [levelNode=null] - The level node.
  14409. * @returns {PMREMNode}
  14410. */
  14411. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  14412. const _envNodeCache = new WeakMap();
  14413. /**
  14414. * Represents a physical model for Image-based lighting (IBL). The environment
  14415. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  14416. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  14417. *
  14418. * @augments LightingNode
  14419. */
  14420. class EnvironmentNode extends LightingNode {
  14421. static get type() {
  14422. return 'EnvironmentNode';
  14423. }
  14424. /**
  14425. * Constructs a new environment node.
  14426. *
  14427. * @param {Node} [envNode=null] - A node representing the environment.
  14428. */
  14429. constructor( envNode = null ) {
  14430. super();
  14431. /**
  14432. * A node representing the environment.
  14433. *
  14434. * @type {Node?}
  14435. * @default null
  14436. */
  14437. this.envNode = envNode;
  14438. }
  14439. setup( builder ) {
  14440. const { material } = builder;
  14441. let envNode = this.envNode;
  14442. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  14443. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  14444. let cacheEnvNode = _envNodeCache.get( value );
  14445. if ( cacheEnvNode === undefined ) {
  14446. cacheEnvNode = pmremTexture( value );
  14447. _envNodeCache.set( value, cacheEnvNode );
  14448. }
  14449. envNode = cacheEnvNode;
  14450. }
  14451. //
  14452. const envMap = material.envMap;
  14453. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  14454. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  14455. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  14456. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  14457. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  14458. const isolateRadiance = cache( radiance );
  14459. const isolateIrradiance = cache( irradiance );
  14460. //
  14461. builder.context.radiance.addAssign( isolateRadiance );
  14462. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  14463. //
  14464. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  14465. if ( clearcoatRadiance ) {
  14466. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  14467. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  14468. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  14469. }
  14470. }
  14471. }
  14472. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  14473. let reflectVec = null;
  14474. return {
  14475. getUV: () => {
  14476. if ( reflectVec === null ) {
  14477. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  14478. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  14479. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  14480. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  14481. }
  14482. return reflectVec;
  14483. },
  14484. getTextureLevel: () => {
  14485. return roughnessNode;
  14486. }
  14487. };
  14488. };
  14489. const createIrradianceContext = ( normalWorldNode ) => {
  14490. return {
  14491. getUV: () => {
  14492. return normalWorldNode;
  14493. },
  14494. getTextureLevel: () => {
  14495. return float( 1.0 );
  14496. }
  14497. };
  14498. };
  14499. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  14500. /**
  14501. * Node material version of `MeshStandardMaterial`.
  14502. *
  14503. * @augments NodeMaterial
  14504. */
  14505. class MeshStandardNodeMaterial extends NodeMaterial {
  14506. static get type() {
  14507. return 'MeshStandardNodeMaterial';
  14508. }
  14509. /**
  14510. * Constructs a new mesh standard node material.
  14511. *
  14512. * @param {Object?} parameters - The configuration parameter.
  14513. */
  14514. constructor( parameters ) {
  14515. super();
  14516. /**
  14517. * This flag can be used for type testing.
  14518. *
  14519. * @type {Boolean}
  14520. * @readonly
  14521. * @default true
  14522. */
  14523. this.isMeshStandardNodeMaterial = true;
  14524. /**
  14525. * Set to `true` because standard materials react on lights.
  14526. *
  14527. * @type {Boolean}
  14528. * @default true
  14529. */
  14530. this.lights = true;
  14531. /**
  14532. * The emissive color of standard materials is by default inferred from the `emissive`,
  14533. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  14534. * overwrite the default and define the emissive color with a node instead.
  14535. *
  14536. * If you don't want to overwrite the emissive color but modify the existing
  14537. * value instead, use {@link module:MaterialNode.materialEmissive}.
  14538. *
  14539. * @type {Node<vec3>?}
  14540. * @default null
  14541. */
  14542. this.emissiveNode = null;
  14543. /**
  14544. * The metalness of standard materials is by default inferred from the `metalness`,
  14545. * and `metalnessMap` properties. This node property allows to
  14546. * overwrite the default and define the metalness with a node instead.
  14547. *
  14548. * If you don't want to overwrite the metalness but modify the existing
  14549. * value instead, use {@link module:MaterialNode.materialMetalness}.
  14550. *
  14551. * @type {Node<float>?}
  14552. * @default null
  14553. */
  14554. this.metalnessNode = null;
  14555. /**
  14556. * The roughness of standard materials is by default inferred from the `roughness`,
  14557. * and `roughnessMap` properties. This node property allows to
  14558. * overwrite the default and define the roughness with a node instead.
  14559. *
  14560. * If you don't want to overwrite the roughness but modify the existing
  14561. * value instead, use {@link module:MaterialNode.materialRoughness}.
  14562. *
  14563. * @type {Node<float>?}
  14564. * @default null
  14565. */
  14566. this.roughnessNode = null;
  14567. this.setDefaultValues( _defaultValues$6 );
  14568. this.setValues( parameters );
  14569. }
  14570. /**
  14571. * Overwritten since this type of material uses {@link EnvironmentNode}
  14572. * to implement the PBR (PMREM based) environment mapping. Besides, the
  14573. * method honors `Scene.environment`.
  14574. *
  14575. * @param {NodeBuilder} builder - The current node builder.
  14576. * @return {EnvironmentNode<vec3>?} The environment node.
  14577. */
  14578. setupEnvironment( builder ) {
  14579. let envNode = super.setupEnvironment( builder );
  14580. if ( envNode === null && builder.environmentNode ) {
  14581. envNode = builder.environmentNode;
  14582. }
  14583. return envNode ? new EnvironmentNode( envNode ) : null;
  14584. }
  14585. /**
  14586. * Setups the lighting model.
  14587. *
  14588. * @return {PhysicalLightingModel} The lighting model.
  14589. */
  14590. setupLightingModel( /*builder*/ ) {
  14591. return new PhysicalLightingModel();
  14592. }
  14593. /**
  14594. * Setups the specular related node variables.
  14595. */
  14596. setupSpecular() {
  14597. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  14598. specularColor.assign( specularColorNode );
  14599. specularF90.assign( 1.0 );
  14600. }
  14601. /**
  14602. * Setups the standard specific node variables.
  14603. *
  14604. * @param {NodeBuilder} builder - The current node builder.
  14605. */
  14606. setupVariants() {
  14607. // METALNESS
  14608. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  14609. metalness.assign( metalnessNode );
  14610. // ROUGHNESS
  14611. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  14612. roughnessNode = getRoughness( { roughness: roughnessNode } );
  14613. roughness.assign( roughnessNode );
  14614. // SPECULAR COLOR
  14615. this.setupSpecular();
  14616. // DIFFUSE COLOR
  14617. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  14618. }
  14619. copy( source ) {
  14620. this.emissiveNode = source.emissiveNode;
  14621. this.metalnessNode = source.metalnessNode;
  14622. this.roughnessNode = source.roughnessNode;
  14623. return super.copy( source );
  14624. }
  14625. }
  14626. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  14627. /**
  14628. * Node material version of `MeshPhysicalMaterial`.
  14629. *
  14630. * @augments MeshStandardNodeMaterial
  14631. */
  14632. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  14633. static get type() {
  14634. return 'MeshPhysicalNodeMaterial';
  14635. }
  14636. /**
  14637. * Constructs a new mesh physical node material.
  14638. *
  14639. * @param {Object?} parameters - The configuration parameter.
  14640. */
  14641. constructor( parameters ) {
  14642. super();
  14643. /**
  14644. * This flag can be used for type testing.
  14645. *
  14646. * @type {Boolean}
  14647. * @readonly
  14648. * @default true
  14649. */
  14650. this.isMeshPhysicalNodeMaterial = true;
  14651. /**
  14652. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  14653. * and `clearcoatMap` properties. This node property allows to overwrite the default
  14654. * and define the clearcoat with a node instead.
  14655. *
  14656. * If you don't want to overwrite the clearcoat but modify the existing
  14657. * value instead, use {@link module:MaterialNode.materialClearcoat}.
  14658. *
  14659. * @type {Node<float>?}
  14660. * @default null
  14661. */
  14662. this.clearcoatNode = null;
  14663. /**
  14664. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  14665. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  14666. * and define the clearcoat roughness with a node instead.
  14667. *
  14668. * If you don't want to overwrite the clearcoat roughness but modify the existing
  14669. * value instead, use {@link module:MaterialNode.materialClearcoatRoughness}.
  14670. *
  14671. * @type {Node<float>?}
  14672. * @default null
  14673. */
  14674. this.clearcoatRoughnessNode = null;
  14675. /**
  14676. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  14677. * property. This node property allows to overwrite the default
  14678. * and define the clearcoat normal with a node instead.
  14679. *
  14680. * If you don't want to overwrite the clearcoat normal but modify the existing
  14681. * value instead, use {@link module:MaterialNode.materialClearcoatNormal}.
  14682. *
  14683. * @type {Node<vec3>?}
  14684. * @default null
  14685. */
  14686. this.clearcoatNormalNode = null;
  14687. /**
  14688. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  14689. * and `sheenColorMap` properties. This node property allows to overwrite the default
  14690. * and define the sheen with a node instead.
  14691. *
  14692. * If you don't want to overwrite the sheen but modify the existing
  14693. * value instead, use {@link module:MaterialNode.materialSheen}.
  14694. *
  14695. * @type {Node<vec3>?}
  14696. * @default null
  14697. */
  14698. this.sheenNode = null;
  14699. /**
  14700. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  14701. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  14702. * and define the sheen roughness with a node instead.
  14703. *
  14704. * If you don't want to overwrite the sheen roughness but modify the existing
  14705. * value instead, use {@link module:MaterialNode.materialSheenRoughness}.
  14706. *
  14707. * @type {Node<float>?}
  14708. * @default null
  14709. */
  14710. this.sheenRoughnessNode = null;
  14711. /**
  14712. * The iridescence of physical materials is by default inferred from the `iridescence`
  14713. * property. This node property allows to overwrite the default
  14714. * and define the iridescence with a node instead.
  14715. *
  14716. * If you don't want to overwrite the iridescence but modify the existing
  14717. * value instead, use {@link module:MaterialNode.materialIridescence}.
  14718. *
  14719. * @type {Node<float>?}
  14720. * @default null
  14721. */
  14722. this.iridescenceNode = null;
  14723. /**
  14724. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  14725. * property. This node property allows to overwrite the default
  14726. * and define the iridescence IOR with a node instead.
  14727. *
  14728. * If you don't want to overwrite the iridescence IOR but modify the existing
  14729. * value instead, use {@link module:MaterialNode.materialIridescenceIOR}.
  14730. *
  14731. * @type {Node<float>?}
  14732. * @default null
  14733. */
  14734. this.iridescenceIORNode = null;
  14735. /**
  14736. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  14737. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  14738. * and define the iridescence thickness with a node instead.
  14739. *
  14740. * If you don't want to overwrite the iridescence thickness but modify the existing
  14741. * value instead, use {@link module:MaterialNode.materialIridescenceThickness}.
  14742. *
  14743. * @type {Node<float>?}
  14744. * @default null
  14745. */
  14746. this.iridescenceThicknessNode = null;
  14747. /**
  14748. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  14749. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  14750. * and define the specular intensity with a node instead.
  14751. *
  14752. * If you don't want to overwrite the specular intensity but modify the existing
  14753. * value instead, use {@link module:MaterialNode.materialSpecularIntensity}.
  14754. *
  14755. * @type {Node<float>?}
  14756. * @default null
  14757. */
  14758. this.specularIntensityNode = null;
  14759. /**
  14760. * The specular color of physical materials is by default inferred from the `specularColor`
  14761. * and `specularColorMap` properties. This node property allows to overwrite the default
  14762. * and define the specular color with a node instead.
  14763. *
  14764. * If you don't want to overwrite the specular color but modify the existing
  14765. * value instead, use {@link module:MaterialNode.materialSpecularColor}.
  14766. *
  14767. * @type {Node<vec3>?}
  14768. * @default null
  14769. */
  14770. this.specularColorNode = null;
  14771. /**
  14772. * The ior of physical materials is by default inferred from the `ior`
  14773. * property. This node property allows to overwrite the default
  14774. * and define the ior with a node instead.
  14775. *
  14776. * If you don't want to overwrite the ior but modify the existing
  14777. * value instead, use {@link module:MaterialNode.materialIOR}.
  14778. *
  14779. * @type {Node<float>?}
  14780. * @default null
  14781. */
  14782. this.iorNode = null;
  14783. /**
  14784. * The transmission of physical materials is by default inferred from the `transmission` and
  14785. * `transmissionMap` properties. This node property allows to overwrite the default
  14786. * and define the transmission with a node instead.
  14787. *
  14788. * If you don't want to overwrite the transmission but modify the existing
  14789. * value instead, use {@link module:MaterialNode.materialTransmission}.
  14790. *
  14791. * @type {Node<float>?}
  14792. * @default null
  14793. */
  14794. this.transmissionNode = null;
  14795. /**
  14796. * The thickness of physical materials is by default inferred from the `thickness` and
  14797. * `thicknessMap` properties. This node property allows to overwrite the default
  14798. * and define the thickness with a node instead.
  14799. *
  14800. * If you don't want to overwrite the thickness but modify the existing
  14801. * value instead, use {@link module:MaterialNode.materialThickness}.
  14802. *
  14803. * @type {Node<float>?}
  14804. * @default null
  14805. */
  14806. this.thicknessNode = null;
  14807. /**
  14808. * The attenuation distance of physical materials is by default inferred from the
  14809. * `attenuationDistance` property. This node property allows to overwrite the default
  14810. * and define the attenuation distance with a node instead.
  14811. *
  14812. * If you don't want to overwrite the attenuation distance but modify the existing
  14813. * value instead, use {@link module:MaterialNode.materialAttenuationDistance}.
  14814. *
  14815. * @type {Node<float>?}
  14816. * @default null
  14817. */
  14818. this.attenuationDistanceNode = null;
  14819. /**
  14820. * The attenuation color of physical materials is by default inferred from the
  14821. * `attenuationColor` property. This node property allows to overwrite the default
  14822. * and define the attenuation color with a node instead.
  14823. *
  14824. * If you don't want to overwrite the attenuation color but modify the existing
  14825. * value instead, use {@link module:MaterialNode.materialAttenuationColor}.
  14826. *
  14827. * @type {Node<vec3>?}
  14828. * @default null
  14829. */
  14830. this.attenuationColorNode = null;
  14831. /**
  14832. * The dispersion of physical materials is by default inferred from the
  14833. * `dispersion` property. This node property allows to overwrite the default
  14834. * and define the dispersion with a node instead.
  14835. *
  14836. * If you don't want to overwrite the dispersion but modify the existing
  14837. * value instead, use {@link module:MaterialNode.materialDispersion}.
  14838. *
  14839. * @type {Node<float>?}
  14840. * @default null
  14841. */
  14842. this.dispersionNode = null;
  14843. /**
  14844. * The anisotropy of physical materials is by default inferred from the
  14845. * `anisotropy` property. This node property allows to overwrite the default
  14846. * and define the anisotropy with a node instead.
  14847. *
  14848. * If you don't want to overwrite the anisotropy but modify the existing
  14849. * value instead, use {@link module:MaterialNode.materialAnisotropy}.
  14850. *
  14851. * @type {Node<float>?}
  14852. * @default null
  14853. */
  14854. this.anisotropyNode = null;
  14855. this.setDefaultValues( _defaultValues$5 );
  14856. this.setValues( parameters );
  14857. }
  14858. /**
  14859. * Whether the lighting model should use clearcoat or not.
  14860. *
  14861. * @type {Boolean}
  14862. * @default true
  14863. */
  14864. get useClearcoat() {
  14865. return this.clearcoat > 0 || this.clearcoatNode !== null;
  14866. }
  14867. /**
  14868. * Whether the lighting model should use iridescence or not.
  14869. *
  14870. * @type {Boolean}
  14871. * @default true
  14872. */
  14873. get useIridescence() {
  14874. return this.iridescence > 0 || this.iridescenceNode !== null;
  14875. }
  14876. /**
  14877. * Whether the lighting model should use sheen or not.
  14878. *
  14879. * @type {Boolean}
  14880. * @default true
  14881. */
  14882. get useSheen() {
  14883. return this.sheen > 0 || this.sheenNode !== null;
  14884. }
  14885. /**
  14886. * Whether the lighting model should use anisotropy or not.
  14887. *
  14888. * @type {Boolean}
  14889. * @default true
  14890. */
  14891. get useAnisotropy() {
  14892. return this.anisotropy > 0 || this.anisotropyNode !== null;
  14893. }
  14894. /**
  14895. * Whether the lighting model should use transmission or not.
  14896. *
  14897. * @type {Boolean}
  14898. * @default true
  14899. */
  14900. get useTransmission() {
  14901. return this.transmission > 0 || this.transmissionNode !== null;
  14902. }
  14903. /**
  14904. * Whether the lighting model should use dispersion or not.
  14905. *
  14906. * @type {Boolean}
  14907. * @default true
  14908. */
  14909. get useDispersion() {
  14910. return this.dispersion > 0 || this.dispersionNode !== null;
  14911. }
  14912. /**
  14913. * Setups the specular related node variables.
  14914. */
  14915. setupSpecular() {
  14916. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  14917. ior.assign( iorNode );
  14918. 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 ) );
  14919. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  14920. }
  14921. /**
  14922. * Setups the lighting model.
  14923. *
  14924. * @return {PhysicalLightingModel} The lighting model.
  14925. */
  14926. setupLightingModel( /*builder*/ ) {
  14927. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  14928. }
  14929. /**
  14930. * Setups the physical specific node variables.
  14931. *
  14932. * @param {NodeBuilder} builder - The current node builder.
  14933. */
  14934. setupVariants( builder ) {
  14935. super.setupVariants( builder );
  14936. // CLEARCOAT
  14937. if ( this.useClearcoat ) {
  14938. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  14939. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  14940. clearcoat.assign( clearcoatNode );
  14941. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  14942. }
  14943. // SHEEN
  14944. if ( this.useSheen ) {
  14945. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  14946. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  14947. sheen.assign( sheenNode );
  14948. sheenRoughness.assign( sheenRoughnessNode );
  14949. }
  14950. // IRIDESCENCE
  14951. if ( this.useIridescence ) {
  14952. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  14953. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  14954. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  14955. iridescence.assign( iridescenceNode );
  14956. iridescenceIOR.assign( iridescenceIORNode );
  14957. iridescenceThickness.assign( iridescenceThicknessNode );
  14958. }
  14959. // ANISOTROPY
  14960. if ( this.useAnisotropy ) {
  14961. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  14962. anisotropy.assign( anisotropyV.length() );
  14963. If( anisotropy.equal( 0.0 ), () => {
  14964. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  14965. } ).Else( () => {
  14966. anisotropyV.divAssign( vec2( anisotropy ) );
  14967. anisotropy.assign( anisotropy.saturate() );
  14968. } );
  14969. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  14970. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  14971. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  14972. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  14973. }
  14974. // TRANSMISSION
  14975. if ( this.useTransmission ) {
  14976. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  14977. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  14978. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  14979. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  14980. transmission.assign( transmissionNode );
  14981. thickness.assign( thicknessNode );
  14982. attenuationDistance.assign( attenuationDistanceNode );
  14983. attenuationColor.assign( attenuationColorNode );
  14984. if ( this.useDispersion ) {
  14985. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  14986. dispersion.assign( dispersionNode );
  14987. }
  14988. }
  14989. }
  14990. /**
  14991. * Setups the clearcoat normal node.
  14992. *
  14993. * @return {Node<vec3>} The clearcoat noraml.
  14994. */
  14995. setupClearcoatNormal() {
  14996. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  14997. }
  14998. setup( builder ) {
  14999. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  15000. super.setup( builder );
  15001. }
  15002. copy( source ) {
  15003. this.clearcoatNode = source.clearcoatNode;
  15004. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  15005. this.clearcoatNormalNode = source.clearcoatNormalNode;
  15006. this.sheenNode = source.sheenNode;
  15007. this.sheenRoughnessNode = source.sheenRoughnessNode;
  15008. this.iridescenceNode = source.iridescenceNode;
  15009. this.iridescenceIORNode = source.iridescenceIORNode;
  15010. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  15011. this.specularIntensityNode = source.specularIntensityNode;
  15012. this.specularColorNode = source.specularColorNode;
  15013. this.transmissionNode = source.transmissionNode;
  15014. this.thicknessNode = source.thicknessNode;
  15015. this.attenuationDistanceNode = source.attenuationDistanceNode;
  15016. this.attenuationColorNode = source.attenuationColorNode;
  15017. this.dispersionNode = source.dispersionNode;
  15018. this.anisotropyNode = source.anisotropyNode;
  15019. return super.copy( source );
  15020. }
  15021. }
  15022. /** @module MeshSSSNodeMaterial **/
  15023. /**
  15024. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  15025. *
  15026. * @augments PhysicalLightingModel
  15027. */
  15028. class SSSLightingModel extends PhysicalLightingModel {
  15029. /**
  15030. * Constructs a new physical lighting model.
  15031. *
  15032. * @param {Boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  15033. * @param {Boolean} [sheen=false] - Whether sheen is supported or not.
  15034. * @param {Boolean} [iridescence=false] - Whether iridescence is supported or not.
  15035. * @param {Boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  15036. * @param {Boolean} [transmission=false] - Whether transmission is supported or not.
  15037. * @param {Boolean} [dispersion=false] - Whether dispersion is supported or not.
  15038. * @param {Boolean} [sss=false] - Whether SSS is supported or not.
  15039. */
  15040. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  15041. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  15042. /**
  15043. * Whether the lighting model should use SSS or not.
  15044. *
  15045. * @type {Boolean}
  15046. * @default false
  15047. */
  15048. this.useSSS = sss;
  15049. }
  15050. /**
  15051. * Extends the default implementation with a SSS term.
  15052. *
  15053. * Reference: [Approximating Translucency for a Fast, Cheap and Convincing Subsurface Scattering Look]{@link https://colinbarrebrisebois.com/2011/03/07/gdc-2011-approximating-translucency-for-a-fast-cheap-and-convincing-subsurface-scattering-look/}
  15054. *
  15055. * @param {Object} input - The input data.
  15056. * @param {StackNode} stack - The current stack.
  15057. * @param {NodeBuilder} builder - The current node builder.
  15058. */
  15059. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  15060. if ( this.useSSS === true ) {
  15061. const material = builder.material;
  15062. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  15063. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  15064. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  15065. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  15066. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  15067. }
  15068. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  15069. }
  15070. }
  15071. /**
  15072. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  15073. * that implements a Subsurface scattering (SSS) term.
  15074. *
  15075. * @augments MeshPhysicalNodeMaterial
  15076. */
  15077. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  15078. static get type() {
  15079. return 'MeshSSSNodeMaterial';
  15080. }
  15081. /**
  15082. * Constructs a new mesh SSS node material.
  15083. *
  15084. * @param {Object?} parameters - The configuration parameter.
  15085. */
  15086. constructor( parameters ) {
  15087. super( parameters );
  15088. /**
  15089. * Represents the thickness color.
  15090. *
  15091. * @type {Node<vec3>?}
  15092. * @default null
  15093. */
  15094. this.thicknessColorNode = null;
  15095. /**
  15096. * Represents the distortion factor.
  15097. *
  15098. * @type {Node<float>?}
  15099. */
  15100. this.thicknessDistortionNode = float( 0.1 );
  15101. /**
  15102. * Represents the thickness ambient factor.
  15103. *
  15104. * @type {Node<float>?}
  15105. */
  15106. this.thicknessAmbientNode = float( 0.0 );
  15107. /**
  15108. * Represents the thickness attenuation.
  15109. *
  15110. * @type {Node<float>?}
  15111. */
  15112. this.thicknessAttenuationNode = float( .1 );
  15113. /**
  15114. * Represents the thickness power.
  15115. *
  15116. * @type {Node<float>?}
  15117. */
  15118. this.thicknessPowerNode = float( 2.0 );
  15119. /**
  15120. * Represents the thickness scale.
  15121. *
  15122. * @type {Node<float>?}
  15123. */
  15124. this.thicknessScaleNode = float( 10.0 );
  15125. }
  15126. /**
  15127. * Whether the lighting model should use SSS or not.
  15128. *
  15129. * @type {Boolean}
  15130. * @default true
  15131. */
  15132. get useSSS() {
  15133. return this.thicknessColorNode !== null;
  15134. }
  15135. /**
  15136. * Setups the lighting model.
  15137. *
  15138. * @return {SSSLightingModel} The lighting model.
  15139. */
  15140. setupLightingModel( /*builder*/ ) {
  15141. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  15142. }
  15143. copy( source ) {
  15144. this.thicknessColorNode = source.thicknessColorNode;
  15145. this.thicknessDistortionNode = source.thicknessDistortionNode;
  15146. this.thicknessAmbientNode = source.thicknessAmbientNode;
  15147. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  15148. this.thicknessPowerNode = source.thicknessPowerNode;
  15149. this.thicknessScaleNode = source.thicknessScaleNode;
  15150. return super.copy( source );
  15151. }
  15152. }
  15153. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  15154. // dotNL will be from -1.0 to 1.0
  15155. const dotNL = normal.dot( lightDirection );
  15156. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  15157. if ( builder.material.gradientMap ) {
  15158. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  15159. return vec3( gradientMap.r );
  15160. } else {
  15161. const fw = coord.fwidth().mul( 0.5 );
  15162. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  15163. }
  15164. } );
  15165. /**
  15166. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  15167. *
  15168. * @augments LightingModel
  15169. */
  15170. class ToonLightingModel extends LightingModel {
  15171. /**
  15172. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  15173. * reduced to a small number of discrete shades to create a comic-like, flat look.
  15174. *
  15175. * @param {Object} input - The input data.
  15176. * @param {StackNode} stack - The current stack.
  15177. * @param {NodeBuilder} builder - The current node builder.
  15178. */
  15179. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  15180. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  15181. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  15182. }
  15183. /**
  15184. * Implements the indirect lighting.
  15185. *
  15186. * @param {ContextNode} input - The current node context.
  15187. * @param {StackNode} stack - The current stack.
  15188. * @param {NodeBuilder} builder - The current node builder.
  15189. */
  15190. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  15191. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  15192. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15193. }
  15194. }
  15195. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  15196. /**
  15197. * Node material version of `MeshToonMaterial`.
  15198. *
  15199. * @augments NodeMaterial
  15200. */
  15201. class MeshToonNodeMaterial extends NodeMaterial {
  15202. static get type() {
  15203. return 'MeshToonNodeMaterial';
  15204. }
  15205. /**
  15206. * Constructs a new mesh toon node material.
  15207. *
  15208. * @param {Object?} parameters - The configuration parameter.
  15209. */
  15210. constructor( parameters ) {
  15211. super();
  15212. /**
  15213. * This flag can be used for type testing.
  15214. *
  15215. * @type {Boolean}
  15216. * @readonly
  15217. * @default true
  15218. */
  15219. this.isMeshToonNodeMaterial = true;
  15220. /**
  15221. * Set to `true` because toon materials react on lights.
  15222. *
  15223. * @type {Boolean}
  15224. * @default true
  15225. */
  15226. this.lights = true;
  15227. this.setDefaultValues( _defaultValues$4 );
  15228. this.setValues( parameters );
  15229. }
  15230. /**
  15231. * Setups the lighting model.
  15232. *
  15233. * @return {ToonLightingModel} The lighting model.
  15234. */
  15235. setupLightingModel( /*builder*/ ) {
  15236. return new ToonLightingModel();
  15237. }
  15238. }
  15239. /** @module MatcapUVNode **/
  15240. /**
  15241. * Can be used to compute texture coordinates for projecting a
  15242. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  15243. *
  15244. * @augments TempNode
  15245. */
  15246. class MatcapUVNode extends TempNode {
  15247. static get type() {
  15248. return 'MatcapUVNode';
  15249. }
  15250. /**
  15251. * Constructs a new matcap uv node.
  15252. */
  15253. constructor() {
  15254. super( 'vec2' );
  15255. }
  15256. setup() {
  15257. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  15258. const y = positionViewDirection.cross( x );
  15259. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  15260. }
  15261. }
  15262. /**
  15263. * TSL function for creating a matcap uv node.
  15264. *
  15265. * @function
  15266. * @returns {MatcapUVNode}
  15267. */
  15268. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  15269. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  15270. /**
  15271. * Node material version of `MeshMatcapMaterial`.
  15272. *
  15273. * @augments NodeMaterial
  15274. */
  15275. class MeshMatcapNodeMaterial extends NodeMaterial {
  15276. static get type() {
  15277. return 'MeshMatcapNodeMaterial';
  15278. }
  15279. /**
  15280. * Constructs a new mesh normal node material.
  15281. *
  15282. * @param {Object?} parameters - The configuration parameter.
  15283. */
  15284. constructor( parameters ) {
  15285. super();
  15286. /**
  15287. * This flag can be used for type testing.
  15288. *
  15289. * @type {Boolean}
  15290. * @readonly
  15291. * @default true
  15292. */
  15293. this.isMeshMatcapNodeMaterial = true;
  15294. this.setDefaultValues( _defaultValues$3 );
  15295. this.setValues( parameters );
  15296. }
  15297. /**
  15298. * Setups the matcap specific node variables.
  15299. *
  15300. * @param {NodeBuilder} builder - The current node builder.
  15301. */
  15302. setupVariants( builder ) {
  15303. const uv = matcapUV;
  15304. let matcapColor;
  15305. if ( builder.material.matcap ) {
  15306. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  15307. } else {
  15308. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  15309. }
  15310. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  15311. }
  15312. }
  15313. const _defaultValues$2 = /*@__PURE__*/ new PointsMaterial();
  15314. /**
  15315. * Node material version of `PointsMaterial`.
  15316. *
  15317. * Since WebGPU can render point primitives only with a size of one pixel,
  15318. * this material type does not evaluate the `size` and `sizeAttenuation`
  15319. * property of `PointsMaterial`. Use {@link InstancedPointsNodeMaterial}
  15320. * instead if you need points with a size larger than one pixel.
  15321. *
  15322. * @augments NodeMaterial
  15323. */
  15324. class PointsNodeMaterial extends NodeMaterial {
  15325. static get type() {
  15326. return 'PointsNodeMaterial';
  15327. }
  15328. /**
  15329. * Constructs a new points node material.
  15330. *
  15331. * @param {Object?} parameters - The configuration parameter.
  15332. */
  15333. constructor( parameters ) {
  15334. super();
  15335. /**
  15336. * This flag can be used for type testing.
  15337. *
  15338. * @type {Boolean}
  15339. * @readonly
  15340. * @default true
  15341. */
  15342. this.isPointsNodeMaterial = true;
  15343. this.setDefaultValues( _defaultValues$2 );
  15344. this.setValues( parameters );
  15345. }
  15346. }
  15347. /** @module RotateNode **/
  15348. /**
  15349. * Applies a rotation to the given position node.
  15350. *
  15351. * @augments TempNode
  15352. */
  15353. class RotateNode extends TempNode {
  15354. static get type() {
  15355. return 'RotateNode';
  15356. }
  15357. /**
  15358. * Constructs a new rotate node.
  15359. *
  15360. * @param {Node} positionNode - The position node.
  15361. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  15362. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15363. */
  15364. constructor( positionNode, rotationNode ) {
  15365. super();
  15366. /**
  15367. * The position node.
  15368. *
  15369. * @type {Node}
  15370. */
  15371. this.positionNode = positionNode;
  15372. /**
  15373. * Represents the rotation that is applied to the position node.
  15374. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15375. *
  15376. * @type {Node}
  15377. */
  15378. this.rotationNode = rotationNode;
  15379. }
  15380. /**
  15381. * The type of the {@link RotateNode#positionNode} defines the node's type.
  15382. *
  15383. * @param {NodeBuilder} builder - The current node builder.
  15384. * @return {String} The node's type.
  15385. */
  15386. getNodeType( builder ) {
  15387. return this.positionNode.getNodeType( builder );
  15388. }
  15389. setup( builder ) {
  15390. const { rotationNode, positionNode } = this;
  15391. const nodeType = this.getNodeType( builder );
  15392. if ( nodeType === 'vec2' ) {
  15393. const cosAngle = rotationNode.cos();
  15394. const sinAngle = rotationNode.sin();
  15395. const rotationMatrix = mat2(
  15396. cosAngle, sinAngle,
  15397. sinAngle.negate(), cosAngle
  15398. );
  15399. return rotationMatrix.mul( positionNode );
  15400. } else {
  15401. const rotation = rotationNode;
  15402. 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 ) );
  15403. 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 ) );
  15404. 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 ) );
  15405. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  15406. }
  15407. }
  15408. }
  15409. /**
  15410. * TSL function for creating a rotate node.
  15411. *
  15412. * @function
  15413. * @param {Node} positionNode - The position node.
  15414. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  15415. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15416. * @returns {RotateNode}
  15417. */
  15418. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  15419. const _defaultValues$1 = /*@__PURE__*/ new SpriteMaterial();
  15420. /**
  15421. * Node material version of `SpriteMaterial`.
  15422. *
  15423. * @augments NodeMaterial
  15424. */
  15425. class SpriteNodeMaterial extends NodeMaterial {
  15426. static get type() {
  15427. return 'SpriteNodeMaterial';
  15428. }
  15429. /**
  15430. * Constructs a new sprite node material.
  15431. *
  15432. * @param {Object?} parameters - The configuration parameter.
  15433. */
  15434. constructor( parameters ) {
  15435. super();
  15436. /**
  15437. * This flag can be used for type testing.
  15438. *
  15439. * @type {Boolean}
  15440. * @readonly
  15441. * @default true
  15442. */
  15443. this.isSpriteNodeMaterial = true;
  15444. this._useSizeAttenuation = true;
  15445. /**
  15446. * This property makes it possible to define the position of the sprite with a
  15447. * node. That can be useful when the material is used with instanced rendering
  15448. * and node data are defined with an instanced attribute node:
  15449. * ```js
  15450. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  15451. * material.positionNode = instancedBufferAttribute( positionAttribute );
  15452. * ```
  15453. * Another possibility is to compute the instanced data with a compute shader:
  15454. * ```js
  15455. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  15456. * particleMaterial.positionNode = positionBuffer.toAttribute();
  15457. * ```
  15458. *
  15459. * @type {Node<vec2>?}
  15460. * @default null
  15461. */
  15462. this.positionNode = null;
  15463. /**
  15464. * The rotation of sprite materials is by default inferred from the `rotation`,
  15465. * property. This node property allows to overwrite the default and define
  15466. * the rotation with a node instead.
  15467. *
  15468. * If you don't want to overwrite the rotation but modify the existing
  15469. * value instead, use {@link module:MaterialNode.materialRotation}.
  15470. *
  15471. * @type {Node<float>?}
  15472. * @default null
  15473. */
  15474. this.rotationNode = null;
  15475. /**
  15476. * This node property provides an additional way to scale sprites next to
  15477. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  15478. * is multiplied with the scale value of this node in the vertex shader.
  15479. *
  15480. * @type {Node<vec2>?}
  15481. * @default null
  15482. */
  15483. this.scaleNode = null;
  15484. this.setDefaultValues( _defaultValues$1 );
  15485. this.setValues( parameters );
  15486. }
  15487. /**
  15488. * Setups the position node in view space. This method implements
  15489. * the sprite specific vertex shader.
  15490. *
  15491. * @param {NodeBuilder} builder - The current node builder.
  15492. * @return {Node<vec3>} The position in view space.
  15493. */
  15494. setupPositionView( builder ) {
  15495. const { object, camera } = builder;
  15496. const sizeAttenuation = this.sizeAttenuation;
  15497. const { positionNode, rotationNode, scaleNode } = this;
  15498. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  15499. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  15500. if ( scaleNode !== null ) {
  15501. scale = scale.mul( scaleNode );
  15502. }
  15503. if ( sizeAttenuation === false ) {
  15504. if ( camera.isPerspectiveCamera ) {
  15505. scale = scale.mul( mvPosition.z.negate() );
  15506. } else {
  15507. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  15508. scale = scale.mul( orthoScale.mul( 2 ) );
  15509. }
  15510. }
  15511. let alignedPosition = positionGeometry.xy;
  15512. if ( object.center && object.center.isVector2 === true ) {
  15513. const center = reference$1( 'center', 'vec2', object );
  15514. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  15515. }
  15516. alignedPosition = alignedPosition.mul( scale );
  15517. const rotation = float( rotationNode || materialRotation );
  15518. const rotatedPosition = rotate( alignedPosition, rotation );
  15519. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  15520. }
  15521. copy( source ) {
  15522. this.positionNode = source.positionNode;
  15523. this.rotationNode = source.rotationNode;
  15524. this.scaleNode = source.scaleNode;
  15525. return super.copy( source );
  15526. }
  15527. /**
  15528. * Whether to use size attenuation or not.
  15529. *
  15530. * @type {Boolean}
  15531. * @default true
  15532. */
  15533. get sizeAttenuation() {
  15534. return this._useSizeAttenuation;
  15535. }
  15536. set sizeAttenuation( value ) {
  15537. if ( this._useSizeAttenuation !== value ) {
  15538. this._useSizeAttenuation = value;
  15539. this.needsUpdate = true;
  15540. }
  15541. }
  15542. }
  15543. /**
  15544. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  15545. *
  15546. * @augments LightingModel
  15547. */
  15548. class ShadowMaskModel extends LightingModel {
  15549. /**
  15550. * Constructs a new shadow mask model.
  15551. */
  15552. constructor() {
  15553. super();
  15554. /**
  15555. * The shadow mask node.
  15556. *
  15557. * @type {Node}
  15558. */
  15559. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  15560. }
  15561. /**
  15562. * Only used to save the shadow mask.
  15563. *
  15564. * @param {Object} input - The input data.
  15565. */
  15566. direct( { shadowMask } ) {
  15567. this.shadowNode.mulAssign( shadowMask );
  15568. }
  15569. /**
  15570. * Uses the shadow mask to produce the final color.
  15571. *
  15572. * @param {ContextNode} context - The current node context.
  15573. */
  15574. finish( context ) {
  15575. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  15576. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  15577. }
  15578. }
  15579. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  15580. /**
  15581. * Node material version of `ShadowMaterial`.
  15582. *
  15583. * @augments NodeMaterial
  15584. */
  15585. class ShadowNodeMaterial extends NodeMaterial {
  15586. static get type() {
  15587. return 'ShadowNodeMaterial';
  15588. }
  15589. /**
  15590. * Constructs a new shadow node material.
  15591. *
  15592. * @param {Object?} parameters - The configuration parameter.
  15593. */
  15594. constructor( parameters ) {
  15595. super();
  15596. /**
  15597. * This flag can be used for type testing.
  15598. *
  15599. * @type {Boolean}
  15600. * @readonly
  15601. * @default true
  15602. */
  15603. this.isShadowNodeMaterial = true;
  15604. /**
  15605. * Set to `true` because so it's possible to implement
  15606. * the shadow mask effect.
  15607. *
  15608. * @type {Boolean}
  15609. * @default true
  15610. */
  15611. this.lights = true;
  15612. this.setDefaultValues( _defaultValues );
  15613. this.setValues( parameters );
  15614. }
  15615. /**
  15616. * Setups the lighting model.
  15617. *
  15618. * @return {ShadowMaskModel} The lighting model.
  15619. */
  15620. setupLightingModel( /*builder*/ ) {
  15621. return new ShadowMaskModel();
  15622. }
  15623. }
  15624. /** @module Texture3DNode **/
  15625. const normal = Fn( ( { texture, uv } ) => {
  15626. const epsilon = 0.0001;
  15627. const ret = vec3().toVar();
  15628. If( uv.x.lessThan( epsilon ), () => {
  15629. ret.assign( vec3( 1, 0, 0 ) );
  15630. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  15631. ret.assign( vec3( 0, 1, 0 ) );
  15632. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  15633. ret.assign( vec3( 0, 0, 1 ) );
  15634. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  15635. ret.assign( vec3( - 1, 0, 0 ) );
  15636. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  15637. ret.assign( vec3( 0, - 1, 0 ) );
  15638. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  15639. ret.assign( vec3( 0, 0, - 1 ) );
  15640. } ).Else( () => {
  15641. const step = 0.01;
  15642. const x = texture.sample( uv.add( vec3( - step, 0.0, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( step, 0.0, 0.0 ) ) ).r );
  15643. const y = texture.sample( uv.add( vec3( 0.0, - step, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, step, 0.0 ) ) ).r );
  15644. const z = texture.sample( uv.add( vec3( 0.0, 0.0, - step ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, 0.0, step ) ) ).r );
  15645. ret.assign( vec3( x, y, z ) );
  15646. } );
  15647. return ret.normalize();
  15648. } );
  15649. /**
  15650. * This type of uniform node represents a 3D texture.
  15651. *
  15652. * @augments module:TextureNode~TextureNode
  15653. */
  15654. class Texture3DNode extends TextureNode {
  15655. static get type() {
  15656. return 'Texture3DNode';
  15657. }
  15658. /**
  15659. * Constructs a new 3D texture node.
  15660. *
  15661. * @param {Data3DTexture} value - The 3D texture.
  15662. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  15663. * @param {Node<int>?} [levelNode=null] - The level node.
  15664. */
  15665. constructor( value, uvNode = null, levelNode = null ) {
  15666. super( value, uvNode, levelNode );
  15667. /**
  15668. * This flag can be used for type testing.
  15669. *
  15670. * @type {Boolean}
  15671. * @readonly
  15672. * @default true
  15673. */
  15674. this.isTexture3DNode = true;
  15675. }
  15676. /**
  15677. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  15678. *
  15679. * @param {NodeBuilder} builder - The current node builder.
  15680. * @return {String} The input type.
  15681. */
  15682. getInputType( /*builder*/ ) {
  15683. return 'texture3D';
  15684. }
  15685. /**
  15686. * Returns a default uv node which is in context of 3D textures a three-dimensional
  15687. * uv node.
  15688. *
  15689. * @return {Node<vec3>} The default uv node.
  15690. */
  15691. getDefaultUV() {
  15692. return vec3( 0.5, 0.5, 0.5 );
  15693. }
  15694. /**
  15695. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  15696. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  15697. *
  15698. * @param {Boolean} value - The update toggle.
  15699. */
  15700. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  15701. /**
  15702. * Overwrites the default implementation to return the unmodified uv node.
  15703. *
  15704. * @param {NodeBuilder} builder - The current node builder.
  15705. * @param {Node} uvNode - The uv node to setup.
  15706. * @return {Node} The unmodified uv node.
  15707. */
  15708. setupUV( builder, uvNode ) {
  15709. const texture = this.value;
  15710. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  15711. if ( this.sampler ) {
  15712. uvNode = uvNode.flipY();
  15713. } else {
  15714. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  15715. }
  15716. }
  15717. return uvNode;
  15718. }
  15719. /**
  15720. * Generates the uv code snippet.
  15721. *
  15722. * @param {NodeBuilder} builder - The current node builder.
  15723. * @param {Node} uvNode - The uv node to generate code for.
  15724. * @return {String} The generated code snippet.
  15725. */
  15726. generateUV( builder, uvNode ) {
  15727. return uvNode.build( builder, 'vec3' );
  15728. }
  15729. /**
  15730. * TODO.
  15731. *
  15732. * @param {Node<vec3>} uvNode - The uv node .
  15733. * @return {Node<vec3>} TODO.
  15734. */
  15735. normal( uvNode ) {
  15736. return normal( { texture: this, uv: uvNode } );
  15737. }
  15738. }
  15739. /**
  15740. * TSL function for creating a 3D texture node.
  15741. *
  15742. * @function
  15743. * @param {Data3DTexture} value - The 3D texture.
  15744. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  15745. * @param {Node<int>?} [levelNode=null] - The level node.
  15746. * @returns {Texture3DNode}
  15747. */
  15748. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  15749. /** @module VolumeNodeMaterial **/
  15750. /**
  15751. * Node material intended for volume rendering. The volumetic data are
  15752. * defined with an instance of {@link Data3DTexture}.
  15753. *
  15754. * @augments NodeMaterial
  15755. */
  15756. class VolumeNodeMaterial extends NodeMaterial {
  15757. static get type() {
  15758. return 'VolumeNodeMaterial';
  15759. }
  15760. /**
  15761. * Constructs a new volume node material.
  15762. *
  15763. * @param {Object?} parameters - The configuration parameter.
  15764. */
  15765. constructor( parameters ) {
  15766. super();
  15767. /**
  15768. * This flag can be used for type testing.
  15769. *
  15770. * @type {Boolean}
  15771. * @readonly
  15772. * @default true
  15773. */
  15774. this.isVolumeNodeMaterial = true;
  15775. /**
  15776. * The base color of the volume.
  15777. *
  15778. * @type {Color}
  15779. * @default 100
  15780. */
  15781. this.base = new Color( 0xffffff );
  15782. /**
  15783. * A 3D data texture holding the volumetric data.
  15784. *
  15785. * @type {Data3DTexture?}
  15786. * @default null
  15787. */
  15788. this.map = null;
  15789. /**
  15790. * This number of samples for each ray that hits the mesh's surface
  15791. * and travels through the volume.
  15792. *
  15793. * @type {Number}
  15794. * @default 100
  15795. */
  15796. this.steps = 100;
  15797. /**
  15798. * Callback for {@link VolumeNodeMaterial#testNode}.
  15799. *
  15800. * @callback testNodeCallback
  15801. * @param {Data3DTexture<float>} map - The 3D texture.
  15802. * @param {Node<float>} mapValue - The sampled value inside the volume.
  15803. * @param {Node<vec3>} probe - The probe which is the entry point of the ray on the mesh's surface.
  15804. * @param {Node<vec4>} finalColor - The final color.
  15805. */
  15806. /**
  15807. * The volume rendering of this material works by shooting rays
  15808. * from the camera position through each fragment of the mesh's
  15809. * surface and sample the inner volume in a raymarching fashion
  15810. * mutiple times.
  15811. *
  15812. * This node can be used to assign a callback function of type `Fn`
  15813. * that will be exexuted per sample. The callback receives the
  15814. * texture, the sampled texture value as well as position on the surface
  15815. * where the rays enters the volume. The last parameter is a color
  15816. * that allows the callback to determine the final color.
  15817. *
  15818. * @type {testNodeCallback?}
  15819. * @default null
  15820. */
  15821. this.testNode = null;
  15822. this.setValues( parameters );
  15823. }
  15824. /**
  15825. * Setups the vertex and fragment stage of this node material.
  15826. *
  15827. * @param {NodeBuilder} builder - The current node builder.
  15828. */
  15829. setup( builder ) {
  15830. const map = texture3D( this.map, null, 0 );
  15831. const hitBox = Fn( ( { orig, dir } ) => {
  15832. const box_min = vec3( - 0.5 );
  15833. const box_max = vec3( 0.5 );
  15834. const inv_dir = dir.reciprocal();
  15835. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  15836. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  15837. const tmin = min$1( tmin_tmp, tmax_tmp );
  15838. const tmax = max$1( tmin_tmp, tmax_tmp );
  15839. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  15840. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  15841. return vec2( t0, t1 );
  15842. } );
  15843. this.fragmentNode = Fn( () => {
  15844. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  15845. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  15846. const rayDir = vDirection.normalize();
  15847. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  15848. bounds.x.greaterThan( bounds.y ).discard();
  15849. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  15850. const p = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  15851. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  15852. const delta = float( min$1( inc.x, min$1( inc.y, inc.z ) ) ).toVar( 'delta' ); // used 'delta' name in loop
  15853. delta.divAssign( materialReference( 'steps', 'float' ) );
  15854. const ac = vec4( materialReference( 'base', 'color' ), 0.0 ).toVar();
  15855. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  15856. const d = property( 'float', 'd' ).assign( map.sample( p.add( 0.5 ) ).r );
  15857. if ( this.testNode !== null ) {
  15858. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  15859. } else {
  15860. // default to show surface of mesh
  15861. ac.a.assign( 1 );
  15862. Break();
  15863. }
  15864. p.addAssign( rayDir.mul( delta ) );
  15865. } );
  15866. ac.a.equal( 0 ).discard();
  15867. return vec4( ac );
  15868. } )();
  15869. super.setup( builder );
  15870. }
  15871. }
  15872. /**
  15873. * This module manages the internal animation loop of the renderer.
  15874. *
  15875. * @private
  15876. */
  15877. class Animation {
  15878. /**
  15879. * Constructs a new animation loop management component.
  15880. *
  15881. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  15882. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  15883. */
  15884. constructor( nodes, info ) {
  15885. /**
  15886. * Renderer component for managing nodes related logic.
  15887. *
  15888. * @type {Nodes}
  15889. */
  15890. this.nodes = nodes;
  15891. /**
  15892. * Renderer component for managing metrics and monitoring data.
  15893. *
  15894. * @type {Info}
  15895. */
  15896. this.info = info;
  15897. /**
  15898. * A reference to the context from `requestAnimationFrame()` can
  15899. * be called (usually `window`).
  15900. *
  15901. * @type {Window|XRSession}
  15902. */
  15903. this._context = self;
  15904. /**
  15905. * The user-defined animation loop.
  15906. *
  15907. * @type {Function?}
  15908. * @default null
  15909. */
  15910. this._animationLoop = null;
  15911. /**
  15912. * The requestId whic is returned from the `requestAnimationFrame()` call.
  15913. * Can be used to cancel the stop the animation loop.
  15914. *
  15915. * @type {Number?}
  15916. * @default null
  15917. */
  15918. this._requestId = null;
  15919. }
  15920. /**
  15921. * Starts the internal animation loop.
  15922. */
  15923. start() {
  15924. const update = ( time, frame ) => {
  15925. this._requestId = this._context.requestAnimationFrame( update );
  15926. if ( this.info.autoReset === true ) this.info.reset();
  15927. this.nodes.nodeFrame.update();
  15928. this.info.frame = this.nodes.nodeFrame.frameId;
  15929. if ( this._animationLoop !== null ) this._animationLoop( time, frame );
  15930. };
  15931. update();
  15932. }
  15933. /**
  15934. * Stops the internal animation loop.
  15935. */
  15936. stop() {
  15937. this._context.cancelAnimationFrame( this._requestId );
  15938. this._requestId = null;
  15939. }
  15940. /**
  15941. * Defines the user-level animation loop.
  15942. *
  15943. * @param {Function} callback - The animation loop.
  15944. */
  15945. setAnimationLoop( callback ) {
  15946. this._animationLoop = callback;
  15947. }
  15948. /**
  15949. * Defines the context in which `requestAnimationFrame()` is executed.
  15950. *
  15951. * @param {Window|XRSession} context - The context to set.
  15952. */
  15953. setContext( context ) {
  15954. this._context = context;
  15955. }
  15956. /**
  15957. * Frees all internal resources and stops the animation loop.
  15958. */
  15959. dispose() {
  15960. this.stop();
  15961. }
  15962. }
  15963. /**
  15964. * Data structure for the renderer. It allows defining values
  15965. * with chained, hierarchical keys. Keys are meant to be
  15966. * objects since the module internally works with Weak Maps
  15967. * for perforamnce reasons.
  15968. *
  15969. * @private
  15970. */
  15971. class ChainMap {
  15972. /**
  15973. * Constructs a new chained map.
  15974. */
  15975. constructor() {
  15976. /**
  15977. * The root Weak Map.
  15978. *
  15979. * @type {WeakMap}
  15980. */
  15981. this.weakMap = new WeakMap();
  15982. }
  15983. /**
  15984. * Returns the value for the given array of keys.
  15985. *
  15986. * @param {Array<Object>} keys - List of keys.
  15987. * @return {Any} The value. Returns `undefined` if no value was found.
  15988. */
  15989. get( keys ) {
  15990. let map = this.weakMap;
  15991. for ( let i = 0; i < keys.length; i ++ ) {
  15992. map = map.get( keys[ i ] );
  15993. if ( map === undefined ) return undefined;
  15994. }
  15995. return map.get( keys[ keys.length - 1 ] );
  15996. }
  15997. /**
  15998. * Sets the value for the given keys.
  15999. *
  16000. * @param {Array<Object>} keys - List of keys.
  16001. * @param {Any} value - The value to set.
  16002. * @return {ChainMap} A reference to this chain map.
  16003. */
  16004. set( keys, value ) {
  16005. let map = this.weakMap;
  16006. for ( let i = 0; i < keys.length; i ++ ) {
  16007. const key = keys[ i ];
  16008. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  16009. map = map.get( key );
  16010. }
  16011. map.set( keys[ keys.length - 1 ], value );
  16012. return this;
  16013. }
  16014. /**
  16015. * Deletes a value for the given keys.
  16016. *
  16017. * @param {Array<Object>} keys - The keys.
  16018. * @return {Boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  16019. */
  16020. delete( keys ) {
  16021. let map = this.weakMap;
  16022. for ( let i = 0; i < keys.length; i ++ ) {
  16023. map = map.get( keys[ i ] );
  16024. if ( map === undefined ) return false;
  16025. }
  16026. return map.delete( keys[ keys.length - 1 ] );
  16027. }
  16028. }
  16029. let _id$9 = 0;
  16030. function getKeys( obj ) {
  16031. const keys = Object.keys( obj );
  16032. let proto = Object.getPrototypeOf( obj );
  16033. while ( proto ) {
  16034. const descriptors = Object.getOwnPropertyDescriptors( proto );
  16035. for ( const key in descriptors ) {
  16036. if ( descriptors[ key ] !== undefined ) {
  16037. const descriptor = descriptors[ key ];
  16038. if ( descriptor && typeof descriptor.get === 'function' ) {
  16039. keys.push( key );
  16040. }
  16041. }
  16042. }
  16043. proto = Object.getPrototypeOf( proto );
  16044. }
  16045. return keys;
  16046. }
  16047. /**
  16048. * A render object is the renderer's representation of single entity that gets drawn
  16049. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  16050. * scene since render objects also depend from the used material, the current render context
  16051. * and the current scene's lighting.
  16052. *
  16053. * In general, the basic process of the renderer is:
  16054. *
  16055. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  16056. * - Process the render lists by calling one or more render commands for each render item.
  16057. * - For each render command, request a render object and perform the draw.
  16058. *
  16059. * The module provides an interface to get data required for the draw command like the actual
  16060. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  16061. * creating render objects should only be done when necessary.
  16062. *
  16063. * @private
  16064. */
  16065. class RenderObject {
  16066. /**
  16067. * Constructs a new render object.
  16068. *
  16069. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16070. * @param {Geometries} geometries - Renderer component for managing geometries.
  16071. * @param {Renderer} renderer - The renderer.
  16072. * @param {Object3D} object - The 3D object.
  16073. * @param {Material} material - The 3D object's material.
  16074. * @param {Scene} scene - The scene the 3D object belongs to.
  16075. * @param {Camera} camera - The camera the object should be rendered with.
  16076. * @param {LightsNode} lightsNode - The lights node.
  16077. * @param {RenderContext} renderContext - The render context.
  16078. * @param {ClippingContext} clippingContext - The clipping context.
  16079. */
  16080. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  16081. this.id = _id$9 ++;
  16082. /**
  16083. * Renderer component for managing nodes related logic.
  16084. *
  16085. * @type {Nodes}
  16086. * @private
  16087. */
  16088. this._nodes = nodes;
  16089. /**
  16090. * Renderer component for managing geometries.
  16091. *
  16092. * @type {Geometries}
  16093. * @private
  16094. */
  16095. this._geometries = geometries;
  16096. /**
  16097. * The renderer.
  16098. *
  16099. * @type {Renderer}
  16100. */
  16101. this.renderer = renderer;
  16102. /**
  16103. * The 3D object.
  16104. *
  16105. * @type {Object3D}
  16106. */
  16107. this.object = object;
  16108. /**
  16109. * The 3D object's material.
  16110. *
  16111. * @type {Material}
  16112. */
  16113. this.material = material;
  16114. /**
  16115. * The scene the 3D object belongs to.
  16116. *
  16117. * @type {Scene}
  16118. */
  16119. this.scene = scene;
  16120. /**
  16121. * The camera the 3D object should be rendered with.
  16122. *
  16123. * @type {Camera}
  16124. */
  16125. this.camera = camera;
  16126. /**
  16127. * The lights node.
  16128. *
  16129. * @type {LightsNode}
  16130. */
  16131. this.lightsNode = lightsNode;
  16132. /**
  16133. * The render context.
  16134. *
  16135. * @type {RenderContext}
  16136. */
  16137. this.context = renderContext;
  16138. /**
  16139. * The 3D object's geometry.
  16140. *
  16141. * @type {BufferGeometry}
  16142. */
  16143. this.geometry = object.geometry;
  16144. /**
  16145. * The render object's version.
  16146. *
  16147. * @type {Number}
  16148. */
  16149. this.version = material.version;
  16150. /**
  16151. * The draw range of the geometry.
  16152. *
  16153. * @type {Object?}
  16154. * @default null
  16155. */
  16156. this.drawRange = null;
  16157. /**
  16158. * An array holding the buffer attributes
  16159. * of the render object. This entails attribute
  16160. * definitions on geometry and node level.
  16161. *
  16162. * @type {Array<BufferAttribute>?}
  16163. * @default null
  16164. */
  16165. this.attributes = null;
  16166. /**
  16167. * A reference to a render pipeline the render
  16168. * object is processed with.
  16169. *
  16170. * @type {RenderPipeline}
  16171. * @default null
  16172. */
  16173. this.pipeline = null;
  16174. /**
  16175. * An array holding the vertex buffers which can
  16176. * be buffer attributes but also interleaved buffers.
  16177. *
  16178. * @type {Array<BufferAttribute|InterleavedBuffer>?}
  16179. * @default null
  16180. */
  16181. this.vertexBuffers = null;
  16182. /**
  16183. * The parameters for the draw command.
  16184. *
  16185. * @type {Object?}
  16186. * @default null
  16187. */
  16188. this.drawParams = null;
  16189. /**
  16190. * If this render object is used inside a render bundle,
  16191. * this property points to the respective bundle group.
  16192. *
  16193. * @type {BundleGroup?}
  16194. * @default null
  16195. */
  16196. this.bundle = null;
  16197. /**
  16198. * The clipping context.
  16199. *
  16200. * @type {ClippingContext}
  16201. */
  16202. this.clippingContext = clippingContext;
  16203. /**
  16204. * The clipping context's cache key.
  16205. *
  16206. * @type {String}
  16207. */
  16208. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  16209. /**
  16210. * The initial node cache key.
  16211. *
  16212. * @type {Number}
  16213. */
  16214. this.initialNodesCacheKey = this.getDynamicCacheKey();
  16215. /**
  16216. * The initial cache key.
  16217. *
  16218. * @type {Number}
  16219. */
  16220. this.initialCacheKey = this.getCacheKey();
  16221. /**
  16222. * The node builder state.
  16223. *
  16224. * @type {NodeBuilderState?}
  16225. * @private
  16226. * @default null
  16227. */
  16228. this._nodeBuilderState = null;
  16229. /**
  16230. * An array of bindings.
  16231. *
  16232. * @type {Array<BindGroup>?}
  16233. * @private
  16234. * @default null
  16235. */
  16236. this._bindings = null;
  16237. /**
  16238. * Reference to the node material observer.
  16239. *
  16240. * @type {NodeMaterialObserver?}
  16241. * @private
  16242. * @default null
  16243. */
  16244. this._monitor = null;
  16245. /**
  16246. * An event listener which is defined by `RenderObjects`. It performs
  16247. * clean up tasks when `dispose()` on this render object.
  16248. *
  16249. * @method
  16250. */
  16251. this.onDispose = null;
  16252. /**
  16253. * This flag can be used for type testing.
  16254. *
  16255. * @type {Boolean}
  16256. * @readonly
  16257. * @default true
  16258. */
  16259. this.isRenderObject = true;
  16260. /**
  16261. * An event listener which is executed when `dispose()` is called on
  16262. * the render object's material.
  16263. *
  16264. * @method
  16265. */
  16266. this.onMaterialDispose = () => {
  16267. this.dispose();
  16268. };
  16269. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  16270. }
  16271. /**
  16272. * Updates the clipping context.
  16273. *
  16274. * @param {ClippingContext} context - The clipping context to set.
  16275. */
  16276. updateClipping( context ) {
  16277. this.clippingContext = context;
  16278. }
  16279. /**
  16280. * Whether the clipping requires an update or not.
  16281. *
  16282. * @type {Boolean}
  16283. * @readonly
  16284. */
  16285. get clippingNeedsUpdate() {
  16286. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  16287. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  16288. return true;
  16289. }
  16290. /**
  16291. * The number of clipping planes defined in context of hardware clipping.
  16292. *
  16293. * @type {Number}
  16294. * @readonly
  16295. */
  16296. get hardwareClippingPlanes() {
  16297. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  16298. }
  16299. /**
  16300. * Returns the node builder state of this render object.
  16301. *
  16302. * @return {NodeBuilderState} The node buider state.
  16303. */
  16304. getNodeBuilderState() {
  16305. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  16306. }
  16307. /**
  16308. * Returns the node material observer of this render object.
  16309. *
  16310. * @return {NodeMaterialObserver} The node material observer.
  16311. */
  16312. getMonitor() {
  16313. return this._monitor || ( this._monitor = this.getNodeBuilderState().monitor );
  16314. }
  16315. /**
  16316. * Returns an array of bind groups of this render object.
  16317. *
  16318. * @return {Array<BindGroup>} The bindings.
  16319. */
  16320. getBindings() {
  16321. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  16322. }
  16323. /**
  16324. * Returns the index of the render object's geometry.
  16325. *
  16326. * @return {BufferAttribute?} The index. Returns `null` for non-indexed geometries.
  16327. */
  16328. getIndex() {
  16329. return this._geometries.getIndex( this );
  16330. }
  16331. /**
  16332. * Returns the indirect buffer attribute.
  16333. *
  16334. * @return {BufferAttribute?} The indirect attribute. `null` if no indirect drawing is used.
  16335. */
  16336. getIndirect() {
  16337. return this._geometries.getIndirect( this );
  16338. }
  16339. /**
  16340. * Returns an array that acts as a key for identifying the render object in a chain map.
  16341. *
  16342. * @return {Array<Object>} An array with object references.
  16343. */
  16344. getChainArray() {
  16345. return [ this.object, this.material, this.context, this.lightsNode ];
  16346. }
  16347. /**
  16348. * This method is used when the geometry of a 3D object has been exchanged and the
  16349. * respective render object now requires an update.
  16350. *
  16351. * @param {BufferGeometry} geometry - The geometry to set.
  16352. */
  16353. setGeometry( geometry ) {
  16354. this.geometry = geometry;
  16355. this.attributes = null;
  16356. }
  16357. /**
  16358. * Returns the buffer attributes of the render object. The returned array holds
  16359. * attribute definitions on geometry and node level.
  16360. *
  16361. * @return {Array<BufferAttribute>} An array with buffer attributes.
  16362. */
  16363. getAttributes() {
  16364. if ( this.attributes !== null ) return this.attributes;
  16365. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  16366. const geometry = this.geometry;
  16367. const attributes = [];
  16368. const vertexBuffers = new Set();
  16369. for ( const nodeAttribute of nodeAttributes ) {
  16370. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  16371. if ( attribute === undefined ) continue;
  16372. attributes.push( attribute );
  16373. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  16374. vertexBuffers.add( bufferAttribute );
  16375. }
  16376. this.attributes = attributes;
  16377. this.vertexBuffers = Array.from( vertexBuffers.values() );
  16378. return attributes;
  16379. }
  16380. /**
  16381. * Returns the vertex buffers of the render object.
  16382. *
  16383. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  16384. */
  16385. getVertexBuffers() {
  16386. if ( this.vertexBuffers === null ) this.getAttributes();
  16387. return this.vertexBuffers;
  16388. }
  16389. /**
  16390. * Returns the draw parameters for the render object.
  16391. *
  16392. * @return {{vertexCount: Number, firstVertex: Number, instanceCount: Number, firstInstance: Number}} The draw parameters.
  16393. */
  16394. getDrawParameters() {
  16395. const { object, material, geometry, group, drawRange } = this;
  16396. const drawParams = this.drawParams || ( this.drawParams = {
  16397. vertexCount: 0,
  16398. firstVertex: 0,
  16399. instanceCount: 0,
  16400. firstInstance: 0
  16401. } );
  16402. const index = this.getIndex();
  16403. const hasIndex = ( index !== null );
  16404. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  16405. if ( instanceCount === 0 ) return null;
  16406. drawParams.instanceCount = instanceCount;
  16407. if ( object.isBatchedMesh === true ) return drawParams;
  16408. let rangeFactor = 1;
  16409. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  16410. rangeFactor = 2;
  16411. }
  16412. let firstVertex = drawRange.start * rangeFactor;
  16413. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  16414. if ( group !== null ) {
  16415. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  16416. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  16417. }
  16418. const position = geometry.attributes.position;
  16419. let itemCount = Infinity;
  16420. if ( hasIndex ) {
  16421. itemCount = index.count;
  16422. } else if ( position !== undefined && position !== null ) {
  16423. itemCount = position.count;
  16424. }
  16425. firstVertex = Math.max( firstVertex, 0 );
  16426. lastVertex = Math.min( lastVertex, itemCount );
  16427. const count = lastVertex - firstVertex;
  16428. if ( count < 0 || count === Infinity ) return null;
  16429. drawParams.vertexCount = count;
  16430. drawParams.firstVertex = firstVertex;
  16431. return drawParams;
  16432. }
  16433. /**
  16434. * Returns the render object's geometry cache key.
  16435. *
  16436. * The geometry cache key is part of the material cache key.
  16437. *
  16438. * @return {String} The geometry cache key.
  16439. */
  16440. getGeometryCacheKey() {
  16441. const { geometry } = this;
  16442. let cacheKey = '';
  16443. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  16444. const attribute = geometry.attributes[ name ];
  16445. cacheKey += name + ',';
  16446. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  16447. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  16448. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  16449. if ( attribute.normalized ) cacheKey += 'n,';
  16450. }
  16451. if ( geometry.index ) {
  16452. cacheKey += 'index,';
  16453. }
  16454. return cacheKey;
  16455. }
  16456. /**
  16457. * Returns the render object's material cache key.
  16458. *
  16459. * The material cache key is part of the render object cache key.
  16460. *
  16461. * @return {String} The material cache key.
  16462. */
  16463. getMaterialCacheKey() {
  16464. const { object, material } = this;
  16465. let cacheKey = material.customProgramCacheKey();
  16466. for ( const property of getKeys( material ) ) {
  16467. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  16468. const value = material[ property ];
  16469. let valueKey;
  16470. if ( value !== null ) {
  16471. // some material values require a formatting
  16472. const type = typeof value;
  16473. if ( type === 'number' ) {
  16474. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  16475. } else if ( type === 'object' ) {
  16476. valueKey = '{';
  16477. if ( value.isTexture ) {
  16478. valueKey += value.mapping;
  16479. }
  16480. valueKey += '}';
  16481. } else {
  16482. valueKey = String( value );
  16483. }
  16484. } else {
  16485. valueKey = String( value );
  16486. }
  16487. cacheKey += /*property + ':' +*/ valueKey + ',';
  16488. }
  16489. cacheKey += this.clippingContextCacheKey + ',';
  16490. if ( object.geometry ) {
  16491. cacheKey += this.getGeometryCacheKey();
  16492. }
  16493. if ( object.skeleton ) {
  16494. cacheKey += object.skeleton.bones.length + ',';
  16495. }
  16496. if ( object.morphTargetInfluences ) {
  16497. cacheKey += object.morphTargetInfluences.length + ',';
  16498. }
  16499. if ( object.isBatchedMesh ) {
  16500. cacheKey += object._matricesTexture.uuid + ',';
  16501. if ( object._colorsTexture !== null ) {
  16502. cacheKey += object._colorsTexture.uuid + ',';
  16503. }
  16504. }
  16505. if ( object.count > 1 ) {
  16506. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  16507. cacheKey += object.uuid + ',';
  16508. }
  16509. cacheKey += object.receiveShadow + ',';
  16510. return hashString( cacheKey );
  16511. }
  16512. /**
  16513. * Whether the geometry requires an update or not.
  16514. *
  16515. * @type {Boolean}
  16516. * @readonly
  16517. */
  16518. get needsGeometryUpdate() {
  16519. return this.geometry.id !== this.object.geometry.id;
  16520. }
  16521. /**
  16522. * Whether the render object requires an update or not.
  16523. *
  16524. * Note: There are two distinct places where render objects are checked for an update.
  16525. *
  16526. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  16527. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  16528. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  16529. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  16530. * a need for a refresh due to material, geometry or object related value changes.
  16531. *
  16532. * TODO: Investigate if it's possible to merge boths steps so there is only a single place
  16533. * that performs the 'needsUpdate' check.
  16534. *
  16535. * @type {Boolean}
  16536. * @readonly
  16537. */
  16538. get needsUpdate() {
  16539. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  16540. }
  16541. /**
  16542. * Returns the dynamic cache key which represents a key that is computed per draw command.
  16543. *
  16544. * @return {String} The cache key.
  16545. */
  16546. getDynamicCacheKey() {
  16547. // Environment Nodes Cache Key
  16548. let cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  16549. if ( this.object.receiveShadow ) {
  16550. cacheKey += 1;
  16551. }
  16552. return cacheKey;
  16553. }
  16554. /**
  16555. * Returns the render object's cache key.
  16556. *
  16557. * @return {String} The cache key.
  16558. */
  16559. getCacheKey() {
  16560. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  16561. }
  16562. /**
  16563. * Frees internal resources.
  16564. */
  16565. dispose() {
  16566. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  16567. this.onDispose();
  16568. }
  16569. }
  16570. const _chainArray = [];
  16571. /**
  16572. * This module manages the render objects of the renderer.
  16573. *
  16574. * @private
  16575. */
  16576. class RenderObjects {
  16577. /**
  16578. * Constructs a new render object management component.
  16579. *
  16580. * @param {Renderer} renderer - The renderer.
  16581. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16582. * @param {Geometries} geometries - Renderer component for managing geometries.
  16583. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  16584. * @param {Bindings} bindings - Renderer component for managing bindings.
  16585. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  16586. */
  16587. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  16588. /**
  16589. * The renderer.
  16590. *
  16591. * @type {Renderer}
  16592. */
  16593. this.renderer = renderer;
  16594. /**
  16595. * Renderer component for managing nodes related logic.
  16596. *
  16597. * @type {Nodes}
  16598. */
  16599. this.nodes = nodes;
  16600. /**
  16601. * Renderer component for managing geometries.
  16602. *
  16603. * @type {Geometries}
  16604. */
  16605. this.geometries = geometries;
  16606. /**
  16607. * Renderer component for managing pipelines.
  16608. *
  16609. * @type {Pipelines}
  16610. */
  16611. this.pipelines = pipelines;
  16612. /**
  16613. * Renderer component for managing bindings.
  16614. *
  16615. * @type {Bindings}
  16616. */
  16617. this.bindings = bindings;
  16618. /**
  16619. * Renderer component for managing metrics and monitoring data.
  16620. *
  16621. * @type {Info}
  16622. */
  16623. this.info = info;
  16624. /**
  16625. * A dictionary that manages render contexts in chain maps
  16626. * for each pass ID.
  16627. *
  16628. * @type {Object<String,ChainMap>}
  16629. */
  16630. this.chainMaps = {};
  16631. }
  16632. /**
  16633. * Returns a render object for the given object and state data.
  16634. *
  16635. * @param {Object3D} object - The 3D object.
  16636. * @param {Material} material - The 3D object's material.
  16637. * @param {Scene} scene - The scene the 3D object belongs to.
  16638. * @param {Camera} camera - The camera the 3D object should be rendered with.
  16639. * @param {LightsNode} lightsNode - The lights node.
  16640. * @param {RenderContext} renderContext - The render context.
  16641. * @param {ClippingContext} clippingContext - The clipping context.
  16642. * @param {String?} passId - An optional ID for identifying the pass.
  16643. * @return {RenderObject} The render object.
  16644. */
  16645. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  16646. const chainMap = this.getChainMap( passId );
  16647. // reuse chainArray
  16648. _chainArray[ 0 ] = object;
  16649. _chainArray[ 1 ] = material;
  16650. _chainArray[ 2 ] = renderContext;
  16651. _chainArray[ 3 ] = lightsNode;
  16652. let renderObject = chainMap.get( _chainArray );
  16653. if ( renderObject === undefined ) {
  16654. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  16655. chainMap.set( _chainArray, renderObject );
  16656. } else {
  16657. renderObject.updateClipping( clippingContext );
  16658. if ( renderObject.needsGeometryUpdate ) {
  16659. renderObject.setGeometry( object.geometry );
  16660. }
  16661. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  16662. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  16663. renderObject.dispose();
  16664. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  16665. } else {
  16666. renderObject.version = material.version;
  16667. }
  16668. }
  16669. }
  16670. return renderObject;
  16671. }
  16672. /**
  16673. * Returns a chain map for the given pass ID.
  16674. *
  16675. * @param {String} [passId='default'] - The pass ID.
  16676. * @return {ChainMap} The chain map.
  16677. */
  16678. getChainMap( passId = 'default' ) {
  16679. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  16680. }
  16681. /**
  16682. * Frees internal resources.
  16683. */
  16684. dispose() {
  16685. this.chainMaps = {};
  16686. }
  16687. /**
  16688. * Factory method for creating render objects with the given list of parameters.
  16689. *
  16690. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16691. * @param {Geometries} geometries - Renderer component for managing geometries.
  16692. * @param {Renderer} renderer - The renderer.
  16693. * @param {Object3D} object - The 3D object.
  16694. * @param {Material} material - The object's material.
  16695. * @param {Scene} scene - The scene the 3D object belongs to.
  16696. * @param {Camera} camera - The camera the object should be rendered with.
  16697. * @param {LightsNode} lightsNode - The lights node.
  16698. * @param {RenderContext} renderContext - The render context.
  16699. * @param {ClippingContext} clippingContext - The clipping context.
  16700. * @param {String?} passId - An optional ID for identifying the pass.
  16701. * @return {RenderObject} The render object.
  16702. */
  16703. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  16704. const chainMap = this.getChainMap( passId );
  16705. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  16706. renderObject.onDispose = () => {
  16707. this.pipelines.delete( renderObject );
  16708. this.bindings.delete( renderObject );
  16709. this.nodes.delete( renderObject );
  16710. chainMap.delete( renderObject.getChainArray() );
  16711. };
  16712. return renderObject;
  16713. }
  16714. }
  16715. /**
  16716. * Data structure for the renderer. It is intended to manage
  16717. * data of objects in dictionaries.
  16718. *
  16719. * @private
  16720. */
  16721. class DataMap {
  16722. /**
  16723. * Constructs a new data map.
  16724. */
  16725. constructor() {
  16726. /**
  16727. * `DataMap` internally uses a weak map
  16728. * to manage its data.
  16729. *
  16730. * @type {WeakMap}
  16731. */
  16732. this.data = new WeakMap();
  16733. }
  16734. /**
  16735. * Returns the dictionary for the given object.
  16736. *
  16737. * @param {Object} object - The object.
  16738. * @return {Object} The dictionary.
  16739. */
  16740. get( object ) {
  16741. let map = this.data.get( object );
  16742. if ( map === undefined ) {
  16743. map = {};
  16744. this.data.set( object, map );
  16745. }
  16746. return map;
  16747. }
  16748. /**
  16749. * Deletes the dictionary for the given object.
  16750. *
  16751. * @param {Object} object - The object.
  16752. * @return {Object?} The deleted dictionary.
  16753. */
  16754. delete( object ) {
  16755. let map = null;
  16756. if ( this.data.has( object ) ) {
  16757. map = this.data.get( object );
  16758. this.data.delete( object );
  16759. }
  16760. return map;
  16761. }
  16762. /**
  16763. * Returns `true` if the given object has a dictionary defined.
  16764. *
  16765. * @param {Object} object - The object to test.
  16766. * @return {Boolean} Whether a dictionary is defined or not.
  16767. */
  16768. has( object ) {
  16769. return this.data.has( object );
  16770. }
  16771. /**
  16772. * Frees internal resources.
  16773. */
  16774. dispose() {
  16775. this.data = new WeakMap();
  16776. }
  16777. }
  16778. const AttributeType = {
  16779. VERTEX: 1,
  16780. INDEX: 2,
  16781. STORAGE: 3,
  16782. INDIRECT: 4
  16783. };
  16784. // size of a chunk in bytes (STD140 layout)
  16785. const GPU_CHUNK_BYTES = 16;
  16786. // @TODO: Move to src/constants.js
  16787. const BlendColorFactor = 211;
  16788. const OneMinusBlendColorFactor = 212;
  16789. /**
  16790. * This renderer module manages geometry attributes.
  16791. *
  16792. * @private
  16793. * @augments DataMap
  16794. */
  16795. class Attributes extends DataMap {
  16796. /**
  16797. * Constructs a new attribute management component.
  16798. *
  16799. * @param {Backend} backend - The renderer's backend.
  16800. */
  16801. constructor( backend ) {
  16802. super();
  16803. /**
  16804. * The renderer's backend.
  16805. *
  16806. * @type {Backend}
  16807. */
  16808. this.backend = backend;
  16809. }
  16810. /**
  16811. * Deletes the data for the given attribute.
  16812. *
  16813. * @param {BufferAttribute} attribute - The attribute.
  16814. * @return {Object} The deleted attribute data.
  16815. */
  16816. delete( attribute ) {
  16817. const attributeData = super.delete( attribute );
  16818. if ( attributeData !== undefined ) {
  16819. this.backend.destroyAttribute( attribute );
  16820. }
  16821. return attributeData;
  16822. }
  16823. /**
  16824. * Updates the given attribute. This method creates attribute buffers
  16825. * for new attributes and updates data for existing ones.
  16826. *
  16827. * @param {BufferAttribute} attribute - The attribute to update.
  16828. * @param {Number} type - The attribute type.
  16829. */
  16830. update( attribute, type ) {
  16831. const data = this.get( attribute );
  16832. if ( data.version === undefined ) {
  16833. if ( type === AttributeType.VERTEX ) {
  16834. this.backend.createAttribute( attribute );
  16835. } else if ( type === AttributeType.INDEX ) {
  16836. this.backend.createIndexAttribute( attribute );
  16837. } else if ( type === AttributeType.STORAGE ) {
  16838. this.backend.createStorageAttribute( attribute );
  16839. } else if ( type === AttributeType.INDIRECT ) {
  16840. this.backend.createIndirectStorageAttribute( attribute );
  16841. }
  16842. data.version = this._getBufferAttribute( attribute ).version;
  16843. } else {
  16844. const bufferAttribute = this._getBufferAttribute( attribute );
  16845. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  16846. this.backend.updateAttribute( attribute );
  16847. data.version = bufferAttribute.version;
  16848. }
  16849. }
  16850. }
  16851. /**
  16852. * Utility method for handling interleaved buffer attributes correctly.
  16853. * To process them, their `InterleavedBuffer` is returned.
  16854. *
  16855. * @param {BufferAttribute} attribute - The attribute.
  16856. * @return {BufferAttribute|InterleavedBuffer}
  16857. */
  16858. _getBufferAttribute( attribute ) {
  16859. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  16860. return attribute;
  16861. }
  16862. }
  16863. /**
  16864. * Returns `true` if the given array has values that require an Uint32 array type.
  16865. *
  16866. * @private
  16867. * @function
  16868. * @param {Array<Number>} array - The array to test.
  16869. * @return {Booolean} Whether the given array has values that require an Uint32 array type or not.
  16870. */
  16871. function arrayNeedsUint32( array ) {
  16872. // assumes larger values usually on last
  16873. for ( let i = array.length - 1; i >= 0; -- i ) {
  16874. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  16875. }
  16876. return false;
  16877. }
  16878. /**
  16879. * Returns the wireframe version for the given geometry.
  16880. *
  16881. * @private
  16882. * @function
  16883. * @param {BufferGeometry} geometry - The geometry.
  16884. * @return {Number} The versio.
  16885. */
  16886. function getWireframeVersion( geometry ) {
  16887. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  16888. }
  16889. /**
  16890. * Returns a wireframe index attribute for the given geometry.
  16891. *
  16892. * @private
  16893. * @function
  16894. * @param {BufferGeometry} geometry - The geometry.
  16895. * @return {BufferAttribute} The wireframe index attribute.
  16896. */
  16897. function getWireframeIndex( geometry ) {
  16898. const indices = [];
  16899. const geometryIndex = geometry.index;
  16900. const geometryPosition = geometry.attributes.position;
  16901. if ( geometryIndex !== null ) {
  16902. const array = geometryIndex.array;
  16903. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  16904. const a = array[ i + 0 ];
  16905. const b = array[ i + 1 ];
  16906. const c = array[ i + 2 ];
  16907. indices.push( a, b, b, c, c, a );
  16908. }
  16909. } else {
  16910. const array = geometryPosition.array;
  16911. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  16912. const a = i + 0;
  16913. const b = i + 1;
  16914. const c = i + 2;
  16915. indices.push( a, b, b, c, c, a );
  16916. }
  16917. }
  16918. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  16919. attribute.version = getWireframeVersion( geometry );
  16920. return attribute;
  16921. }
  16922. /**
  16923. * This renderer module manages geometries.
  16924. *
  16925. * @private
  16926. * @augments DataMap
  16927. */
  16928. class Geometries extends DataMap {
  16929. /**
  16930. * Constructs a new geometry management component.
  16931. *
  16932. * @param {Attributes} attributes - Renderer component for managing attributes.
  16933. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  16934. */
  16935. constructor( attributes, info ) {
  16936. super();
  16937. /**
  16938. * Renderer component for managing attributes.
  16939. *
  16940. * @type {Attributes}
  16941. */
  16942. this.attributes = attributes;
  16943. /**
  16944. * Renderer component for managing metrics and monitoring data.
  16945. *
  16946. * @type {Info}
  16947. */
  16948. this.info = info;
  16949. /**
  16950. * Weak Map for managing attributes for wireframe rendering.
  16951. *
  16952. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  16953. */
  16954. this.wireframes = new WeakMap();
  16955. /**
  16956. * This Weak Map is used to make sure buffer attributes are
  16957. * updated only once per render call.
  16958. *
  16959. * @type {WeakMap<BufferAttribute,Number>}
  16960. */
  16961. this.attributeCall = new WeakMap();
  16962. }
  16963. /**
  16964. * Returns `true` if the given render object has an initialized geometry.
  16965. *
  16966. * @param {RenderObject} renderObject - The render object.
  16967. * @return {Boolean} Whether if the given render object has an initialized geometry or not.
  16968. */
  16969. has( renderObject ) {
  16970. const geometry = renderObject.geometry;
  16971. return super.has( geometry ) && this.get( geometry ).initialized === true;
  16972. }
  16973. /**
  16974. * Prepares the geometry of the given render object for rendering.
  16975. *
  16976. * @param {RenderObject} renderObject - The render object.
  16977. */
  16978. updateForRender( renderObject ) {
  16979. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  16980. this.updateAttributes( renderObject );
  16981. }
  16982. /**
  16983. * Initializes the geometry of the given render object.
  16984. *
  16985. * @param {RenderObject} renderObject - The render object.
  16986. */
  16987. initGeometry( renderObject ) {
  16988. const geometry = renderObject.geometry;
  16989. const geometryData = this.get( geometry );
  16990. geometryData.initialized = true;
  16991. this.info.memory.geometries ++;
  16992. const onDispose = () => {
  16993. this.info.memory.geometries --;
  16994. const index = geometry.index;
  16995. const geometryAttributes = renderObject.getAttributes();
  16996. if ( index !== null ) {
  16997. this.attributes.delete( index );
  16998. }
  16999. for ( const geometryAttribute of geometryAttributes ) {
  17000. this.attributes.delete( geometryAttribute );
  17001. }
  17002. const wireframeAttribute = this.wireframes.get( geometry );
  17003. if ( wireframeAttribute !== undefined ) {
  17004. this.attributes.delete( wireframeAttribute );
  17005. }
  17006. geometry.removeEventListener( 'dispose', onDispose );
  17007. };
  17008. geometry.addEventListener( 'dispose', onDispose );
  17009. }
  17010. /**
  17011. * Updates the geometry attributes of the given render object.
  17012. *
  17013. * @param {RenderObject} renderObject - The render object.
  17014. */
  17015. updateAttributes( renderObject ) {
  17016. // attributes
  17017. const attributes = renderObject.getAttributes();
  17018. for ( const attribute of attributes ) {
  17019. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  17020. this.updateAttribute( attribute, AttributeType.STORAGE );
  17021. } else {
  17022. this.updateAttribute( attribute, AttributeType.VERTEX );
  17023. }
  17024. }
  17025. // indexes
  17026. const index = this.getIndex( renderObject );
  17027. if ( index !== null ) {
  17028. this.updateAttribute( index, AttributeType.INDEX );
  17029. }
  17030. // indirect
  17031. const indirect = renderObject.geometry.indirect;
  17032. if ( indirect !== null ) {
  17033. this.updateAttribute( indirect, AttributeType.INDIRECT );
  17034. }
  17035. }
  17036. /**
  17037. * Updates the given attribute.
  17038. *
  17039. * @param {BufferAttribute} attribute - The attribute to update.
  17040. * @param {Number} type - The attribute type.
  17041. */
  17042. updateAttribute( attribute, type ) {
  17043. const callId = this.info.render.calls;
  17044. if ( ! attribute.isInterleavedBufferAttribute ) {
  17045. if ( this.attributeCall.get( attribute ) !== callId ) {
  17046. this.attributes.update( attribute, type );
  17047. this.attributeCall.set( attribute, callId );
  17048. }
  17049. } else {
  17050. if ( this.attributeCall.get( attribute ) === undefined ) {
  17051. this.attributes.update( attribute, type );
  17052. this.attributeCall.set( attribute, callId );
  17053. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  17054. this.attributes.update( attribute, type );
  17055. this.attributeCall.set( attribute.data, callId );
  17056. this.attributeCall.set( attribute, callId );
  17057. }
  17058. }
  17059. }
  17060. /**
  17061. * Returns the indirect buffer attribute of the given render object.
  17062. *
  17063. * @param {RenderObject} renderObject - The render object.
  17064. * @return {BufferAttribute?} The indirect attribute. `null` if no indirect drawing is used.
  17065. */
  17066. getIndirect( renderObject ) {
  17067. return renderObject.geometry.indirect;
  17068. }
  17069. /**
  17070. * Returns the index of the given render object's geometry. This is implemented
  17071. * in a method to return a wireframe index if necessary.
  17072. *
  17073. * @param {RenderObject} renderObject - The render object.
  17074. * @return {BufferAttribute?} The index. Returns `null` for non-indexed geometries.
  17075. */
  17076. getIndex( renderObject ) {
  17077. const { geometry, material } = renderObject;
  17078. let index = geometry.index;
  17079. if ( material.wireframe === true ) {
  17080. const wireframes = this.wireframes;
  17081. let wireframeAttribute = wireframes.get( geometry );
  17082. if ( wireframeAttribute === undefined ) {
  17083. wireframeAttribute = getWireframeIndex( geometry );
  17084. wireframes.set( geometry, wireframeAttribute );
  17085. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  17086. this.attributes.delete( wireframeAttribute );
  17087. wireframeAttribute = getWireframeIndex( geometry );
  17088. wireframes.set( geometry, wireframeAttribute );
  17089. }
  17090. index = wireframeAttribute;
  17091. }
  17092. return index;
  17093. }
  17094. }
  17095. /**
  17096. * This renderer module provides a series of statistical information
  17097. * about the GPU memory and the rendering process. Useful for debugging
  17098. * and monitoring.
  17099. */
  17100. class Info {
  17101. /**
  17102. * Constructs a new info component.
  17103. */
  17104. constructor() {
  17105. /**
  17106. * Whether frame related metrics should automatically
  17107. * be resetted or not. This property should be set to `false`
  17108. * by apps which manage their own animation loop. They must
  17109. * then call `renderer.info.reset()` once per frame manually.
  17110. *
  17111. * @type {Boolean}
  17112. * @default true
  17113. */
  17114. this.autoReset = true;
  17115. /**
  17116. * The current frame ID. This ID is managed
  17117. * by `NodeFrame`.
  17118. *
  17119. * @type {Number}
  17120. * @readonly
  17121. * @default 0
  17122. */
  17123. this.frame = 0;
  17124. /**
  17125. * The number of render calls since the
  17126. * app has been started.
  17127. *
  17128. * @type {Number}
  17129. * @readonly
  17130. * @default 0
  17131. */
  17132. this.calls = 0;
  17133. /**
  17134. * Render related metrics.
  17135. *
  17136. * @type {Object}
  17137. * @readonly
  17138. * @property {Number} calls - The number of render calls since the app has been started.
  17139. * @property {Number} frameCalls - The number of render calls of the current frame.
  17140. * @property {Number} drawCalls - The number of draw calls of the current frame.
  17141. * @property {Number} triangles - The number of rendered triangle primitives of the current frame.
  17142. * @property {Number} points - The number of rendered point primitives of the current frame.
  17143. * @property {Number} lines - The number of rendered line primitives of the current frame.
  17144. * @property {Number} previousFrameCalls - The number of render calls of the previous frame.
  17145. * @property {Number} timestamp - The timestamp of the frame when using `renderer.renderAsync()`.
  17146. * @property {Number} timestampCalls - The number of render calls using `renderer.renderAsync()`.
  17147. */
  17148. this.render = {
  17149. calls: 0,
  17150. frameCalls: 0,
  17151. drawCalls: 0,
  17152. triangles: 0,
  17153. points: 0,
  17154. lines: 0,
  17155. timestamp: 0,
  17156. previousFrameCalls: 0,
  17157. timestampCalls: 0
  17158. };
  17159. /**
  17160. * Compute related metrics.
  17161. *
  17162. * @type {Object}
  17163. * @readonly
  17164. * @property {Number} calls - The number of compute calls since the app has been started.
  17165. * @property {Number} frameCalls - The number of compute calls of the current frame.
  17166. * @property {Number} previousFrameCalls - The number of compute calls of the previous frame.
  17167. * @property {Number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  17168. * @property {Number} timestampCalls - The number of render calls using `renderer.computeAsync()`.
  17169. */
  17170. this.compute = {
  17171. calls: 0,
  17172. frameCalls: 0,
  17173. timestamp: 0,
  17174. previousFrameCalls: 0,
  17175. timestampCalls: 0
  17176. };
  17177. /**
  17178. * Memory related metrics.
  17179. *
  17180. * @type {Object}
  17181. * @readonly
  17182. * @property {Number} geometries - The number of active geometries.
  17183. * @property {Number} frameCalls - The number of active textures.
  17184. */
  17185. this.memory = {
  17186. geometries: 0,
  17187. textures: 0
  17188. };
  17189. }
  17190. /**
  17191. * This method should be executed per draw call and updates the corresponding metrics.
  17192. *
  17193. * @param {Object3D} object - The 3D object that is going to be rendered.
  17194. * @param {Number} count - The vertex or index count.
  17195. * @param {Number} instanceCount - The instance count.
  17196. */
  17197. update( object, count, instanceCount ) {
  17198. this.render.drawCalls ++;
  17199. if ( object.isMesh || object.isSprite ) {
  17200. this.render.triangles += instanceCount * ( count / 3 );
  17201. } else if ( object.isPoints ) {
  17202. this.render.points += instanceCount * count;
  17203. } else if ( object.isLineSegments ) {
  17204. this.render.lines += instanceCount * ( count / 2 );
  17205. } else if ( object.isLine ) {
  17206. this.render.lines += instanceCount * ( count - 1 );
  17207. } else {
  17208. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  17209. }
  17210. }
  17211. /**
  17212. * Used by async render methods to updated timestamp metrics.
  17213. *
  17214. * @param {('render'|'compute')} type - The type of render call.
  17215. * @param {Number} time - The duration of the compute/render call in milliseconds.
  17216. */
  17217. updateTimestamp( type, time ) {
  17218. if ( this[ type ].timestampCalls === 0 ) {
  17219. this[ type ].timestamp = 0;
  17220. }
  17221. this[ type ].timestamp += time;
  17222. this[ type ].timestampCalls ++;
  17223. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  17224. this[ type ].timestampCalls = 0;
  17225. }
  17226. }
  17227. /**
  17228. * Resets frame related metrics.
  17229. */
  17230. reset() {
  17231. const previousRenderFrameCalls = this.render.frameCalls;
  17232. this.render.previousFrameCalls = previousRenderFrameCalls;
  17233. const previousComputeFrameCalls = this.compute.frameCalls;
  17234. this.compute.previousFrameCalls = previousComputeFrameCalls;
  17235. this.render.drawCalls = 0;
  17236. this.render.frameCalls = 0;
  17237. this.compute.frameCalls = 0;
  17238. this.render.triangles = 0;
  17239. this.render.points = 0;
  17240. this.render.lines = 0;
  17241. }
  17242. /**
  17243. * Performs a complete reset of the object.
  17244. */
  17245. dispose() {
  17246. this.reset();
  17247. this.calls = 0;
  17248. this.render.calls = 0;
  17249. this.compute.calls = 0;
  17250. this.render.timestamp = 0;
  17251. this.compute.timestamp = 0;
  17252. this.memory.geometries = 0;
  17253. this.memory.textures = 0;
  17254. }
  17255. }
  17256. /**
  17257. * Abstract class for representing pipelines.
  17258. *
  17259. * @private
  17260. * @abstract
  17261. */
  17262. class Pipeline {
  17263. /**
  17264. * Constructs a new pipeline.
  17265. *
  17266. * @param {String} cacheKey - The pipeline's cache key.
  17267. */
  17268. constructor( cacheKey ) {
  17269. /**
  17270. * The pipeline's cache key.
  17271. *
  17272. * @type {String}
  17273. */
  17274. this.cacheKey = cacheKey;
  17275. /**
  17276. * How often the pipeline is currently in use.
  17277. *
  17278. * @type {Number}
  17279. * @default 0
  17280. */
  17281. this.usedTimes = 0;
  17282. }
  17283. }
  17284. /**
  17285. * Class for representing render pipelines.
  17286. *
  17287. * @private
  17288. * @augments Pipeline
  17289. */
  17290. class RenderPipeline extends Pipeline {
  17291. /**
  17292. * Constructs a new render pipeline.
  17293. *
  17294. * @param {String} cacheKey - The pipeline's cache key.
  17295. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  17296. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  17297. */
  17298. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  17299. super( cacheKey );
  17300. /**
  17301. * The pipeline's vertex shader.
  17302. *
  17303. * @type {ProgrammableStage}
  17304. */
  17305. this.vertexProgram = vertexProgram;
  17306. /**
  17307. * The pipeline's fragment shader.
  17308. *
  17309. * @type {ProgrammableStage}
  17310. */
  17311. this.fragmentProgram = fragmentProgram;
  17312. }
  17313. }
  17314. /**
  17315. * Class for representing compute pipelines.
  17316. *
  17317. * @private
  17318. * @augments Pipeline
  17319. */
  17320. class ComputePipeline extends Pipeline {
  17321. /**
  17322. * Constructs a new render pipeline.
  17323. *
  17324. * @param {String} cacheKey - The pipeline's cache key.
  17325. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  17326. */
  17327. constructor( cacheKey, computeProgram ) {
  17328. super( cacheKey );
  17329. /**
  17330. * The pipeline's compute shader.
  17331. *
  17332. * @type {ProgrammableStage}
  17333. */
  17334. this.computeProgram = computeProgram;
  17335. /**
  17336. * This flag can be used for type testing.
  17337. *
  17338. * @type {Boolean}
  17339. * @readonly
  17340. * @default true
  17341. */
  17342. this.isComputePipeline = true;
  17343. }
  17344. }
  17345. let _id$8 = 0;
  17346. /**
  17347. * Class for representing programmable stages which are vertex,
  17348. * fragment or compute shaders. Unlike fixed-function states (like blending),
  17349. * they represent the programmable part of a pipeline.
  17350. *
  17351. * @private
  17352. */
  17353. class ProgrammableStage {
  17354. /**
  17355. * Constructs a new programmable stage.
  17356. *
  17357. * @param {String} code - The shader code.
  17358. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  17359. * @param {String} name - The name of the shader.
  17360. * @param {Array<Object>?} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17361. * @param {Array<Object>?} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17362. */
  17363. constructor( code, stage, name, transforms = null, attributes = null ) {
  17364. /**
  17365. * The id of the programmable stage.
  17366. *
  17367. * @type {Number}
  17368. */
  17369. this.id = _id$8 ++;
  17370. /**
  17371. * The shader code.
  17372. *
  17373. * @type {String}
  17374. */
  17375. this.code = code;
  17376. /**
  17377. * The type of stage.
  17378. *
  17379. * @type {String}
  17380. */
  17381. this.stage = stage;
  17382. /**
  17383. * The name of the stage.
  17384. * This is used for debugging purposes.
  17385. *
  17386. * @type {String}
  17387. */
  17388. this.name = name;
  17389. /**
  17390. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17391. *
  17392. * @type {Array<Object>?}
  17393. */
  17394. this.transforms = transforms;
  17395. /**
  17396. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17397. *
  17398. * @type {Array<Object>?}
  17399. */
  17400. this.attributes = attributes;
  17401. /**
  17402. * How often the programmable stage is currently in use.
  17403. *
  17404. * @type {Number}
  17405. * @default 0
  17406. */
  17407. this.usedTimes = 0;
  17408. }
  17409. }
  17410. /**
  17411. * This renderer module manages the pipelines of the renderer.
  17412. *
  17413. * @private
  17414. * @augments DataMap
  17415. */
  17416. class Pipelines extends DataMap {
  17417. /**
  17418. * Constructs a new pipeline management component.
  17419. *
  17420. * @param {Backend} backend - The renderer's backend.
  17421. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17422. */
  17423. constructor( backend, nodes ) {
  17424. super();
  17425. /**
  17426. * The renderer's backend.
  17427. *
  17428. * @type {Backend}
  17429. */
  17430. this.backend = backend;
  17431. /**
  17432. * Renderer component for managing nodes related logic.
  17433. *
  17434. * @type {Nodes}
  17435. */
  17436. this.nodes = nodes;
  17437. /**
  17438. * A references to the bindings management component.
  17439. * This reference will be set inside the `Bindings`
  17440. * constructor.
  17441. *
  17442. * @type {Bindings?}
  17443. * @default null
  17444. */
  17445. this.bindings = null;
  17446. /**
  17447. * Internal cache for maintaining pipelines.
  17448. * The key of the map is a cache key, the value the pipeline.
  17449. *
  17450. * @type {Map<String,Pipeline>}
  17451. */
  17452. this.caches = new Map();
  17453. /**
  17454. * This dictionary maintains for each shader stage type (vertex,
  17455. * fragment and compute) the progammable stage objects which
  17456. * represent the actual shader code.
  17457. *
  17458. * @type {Object<String,Map>}
  17459. */
  17460. this.programs = {
  17461. vertex: new Map(),
  17462. fragment: new Map(),
  17463. compute: new Map()
  17464. };
  17465. }
  17466. /**
  17467. * Returns a compute pipeline for the given compute node.
  17468. *
  17469. * @param {Node} computeNode - The compute node.
  17470. * @param {Array<BindGroup>} bindings - The bindings.
  17471. * @return {ComputePipeline} The compute pipeline.
  17472. */
  17473. getForCompute( computeNode, bindings ) {
  17474. const { backend } = this;
  17475. const data = this.get( computeNode );
  17476. if ( this._needsComputeUpdate( computeNode ) ) {
  17477. const previousPipeline = data.pipeline;
  17478. if ( previousPipeline ) {
  17479. previousPipeline.usedTimes --;
  17480. previousPipeline.computeProgram.usedTimes --;
  17481. }
  17482. // get shader
  17483. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  17484. // programmable stage
  17485. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  17486. if ( stageCompute === undefined ) {
  17487. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  17488. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  17489. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  17490. backend.createProgram( stageCompute );
  17491. }
  17492. // determine compute pipeline
  17493. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  17494. let pipeline = this.caches.get( cacheKey );
  17495. if ( pipeline === undefined ) {
  17496. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  17497. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  17498. }
  17499. // keep track of all used times
  17500. pipeline.usedTimes ++;
  17501. stageCompute.usedTimes ++;
  17502. //
  17503. data.version = computeNode.version;
  17504. data.pipeline = pipeline;
  17505. }
  17506. return data.pipeline;
  17507. }
  17508. /**
  17509. * Returns a render pipeline for the given render object.
  17510. *
  17511. * @param {RenderObject} renderObject - The render object.
  17512. * @param {Array<Promise>?} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  17513. * @return {RenderPipeline} The render pipeline.
  17514. */
  17515. getForRender( renderObject, promises = null ) {
  17516. const { backend } = this;
  17517. const data = this.get( renderObject );
  17518. if ( this._needsRenderUpdate( renderObject ) ) {
  17519. const previousPipeline = data.pipeline;
  17520. if ( previousPipeline ) {
  17521. previousPipeline.usedTimes --;
  17522. previousPipeline.vertexProgram.usedTimes --;
  17523. previousPipeline.fragmentProgram.usedTimes --;
  17524. }
  17525. // get shader
  17526. const nodeBuilderState = renderObject.getNodeBuilderState();
  17527. const name = renderObject.material ? renderObject.material.name : '';
  17528. // programmable stages
  17529. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  17530. if ( stageVertex === undefined ) {
  17531. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  17532. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  17533. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  17534. backend.createProgram( stageVertex );
  17535. }
  17536. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  17537. if ( stageFragment === undefined ) {
  17538. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  17539. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  17540. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  17541. backend.createProgram( stageFragment );
  17542. }
  17543. // determine render pipeline
  17544. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  17545. let pipeline = this.caches.get( cacheKey );
  17546. if ( pipeline === undefined ) {
  17547. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  17548. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  17549. } else {
  17550. renderObject.pipeline = pipeline;
  17551. }
  17552. // keep track of all used times
  17553. pipeline.usedTimes ++;
  17554. stageVertex.usedTimes ++;
  17555. stageFragment.usedTimes ++;
  17556. //
  17557. data.pipeline = pipeline;
  17558. }
  17559. return data.pipeline;
  17560. }
  17561. /**
  17562. * Deletes the pipeline for the given render object.
  17563. *
  17564. * @param {RenderObject} object - The render object.
  17565. * @return {Object?} The deleted dictionary.
  17566. */
  17567. delete( object ) {
  17568. const pipeline = this.get( object ).pipeline;
  17569. if ( pipeline ) {
  17570. // pipeline
  17571. pipeline.usedTimes --;
  17572. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  17573. // programs
  17574. if ( pipeline.isComputePipeline ) {
  17575. pipeline.computeProgram.usedTimes --;
  17576. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  17577. } else {
  17578. pipeline.fragmentProgram.usedTimes --;
  17579. pipeline.vertexProgram.usedTimes --;
  17580. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  17581. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  17582. }
  17583. }
  17584. return super.delete( object );
  17585. }
  17586. /**
  17587. * Frees internal resources.
  17588. */
  17589. dispose() {
  17590. super.dispose();
  17591. this.caches = new Map();
  17592. this.programs = {
  17593. vertex: new Map(),
  17594. fragment: new Map(),
  17595. compute: new Map()
  17596. };
  17597. }
  17598. /**
  17599. * Updates the pipeline for the given render object.
  17600. *
  17601. * @param {RenderObject} renderObject - The render object.
  17602. */
  17603. updateForRender( renderObject ) {
  17604. this.getForRender( renderObject );
  17605. }
  17606. /**
  17607. * Returns a compute pipeline for the given parameters.
  17608. *
  17609. * @private
  17610. * @param {Node} computeNode - The compute node.
  17611. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  17612. * @param {String} cacheKey - The cache key.
  17613. * @param {Array<BindGroup>} bindings - The bindings.
  17614. * @return {ComputePipeline} The compute pipeline.
  17615. */
  17616. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  17617. // check for existing pipeline
  17618. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  17619. let pipeline = this.caches.get( cacheKey );
  17620. if ( pipeline === undefined ) {
  17621. pipeline = new ComputePipeline( cacheKey, stageCompute );
  17622. this.caches.set( cacheKey, pipeline );
  17623. this.backend.createComputePipeline( pipeline, bindings );
  17624. }
  17625. return pipeline;
  17626. }
  17627. /**
  17628. * Returns a render pipeline for the given parameters.
  17629. *
  17630. * @private
  17631. * @param {RenderObject} renderObject - The render object.
  17632. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  17633. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  17634. * @param {String} cacheKey - The cache key.
  17635. * @param {Array} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  17636. * @return {ComputePipeline} The compute pipeline.
  17637. */
  17638. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  17639. // check for existing pipeline
  17640. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  17641. let pipeline = this.caches.get( cacheKey );
  17642. if ( pipeline === undefined ) {
  17643. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  17644. this.caches.set( cacheKey, pipeline );
  17645. renderObject.pipeline = pipeline;
  17646. // The `promises` array is `null` by default and only set to an empty array when
  17647. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  17648. // pending promises that resolve when the render pipelines are ready for rendering.
  17649. this.backend.createRenderPipeline( renderObject, promises );
  17650. }
  17651. return pipeline;
  17652. }
  17653. /**
  17654. * Computes a cache key representing a compute pipeline.
  17655. *
  17656. * @private
  17657. * @param {Node} computeNode - The compute node.
  17658. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  17659. * @return {String} The cache key.
  17660. */
  17661. _getComputeCacheKey( computeNode, stageCompute ) {
  17662. return computeNode.id + ',' + stageCompute.id;
  17663. }
  17664. /**
  17665. * Computes a cache key representing a render pipeline.
  17666. *
  17667. * @private
  17668. * @param {RenderObject} renderObject - The render object.
  17669. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  17670. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  17671. * @return {String} The cache key.
  17672. */
  17673. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  17674. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  17675. }
  17676. /**
  17677. * Releases the given pipeline.
  17678. *
  17679. * @private
  17680. * @param {Pipeline} pipeline - The pipeline to release.
  17681. */
  17682. _releasePipeline( pipeline ) {
  17683. this.caches.delete( pipeline.cacheKey );
  17684. }
  17685. /**
  17686. * Releases the shader program.
  17687. *
  17688. * @private
  17689. * @param {Object} program - The shdaer program to release.
  17690. */
  17691. _releaseProgram( program ) {
  17692. const code = program.code;
  17693. const stage = program.stage;
  17694. this.programs[ stage ].delete( code );
  17695. }
  17696. /**
  17697. * Returns `true` if the compute pipeline for the given compute node requires an update.
  17698. *
  17699. * @private
  17700. * @param {Node} computeNode - The compute node.
  17701. * @return {Boolean} Whether the compute pipeline for the given compute node requires an update or not.
  17702. */
  17703. _needsComputeUpdate( computeNode ) {
  17704. const data = this.get( computeNode );
  17705. return data.pipeline === undefined || data.version !== computeNode.version;
  17706. }
  17707. /**
  17708. * Returns `true` if the render pipeline for the given render object requires an update.
  17709. *
  17710. * @private
  17711. * @param {RenderObject} renderObject - The render object.
  17712. * @return {Boolean} Whether the render object for the given render object requires an update or not.
  17713. */
  17714. _needsRenderUpdate( renderObject ) {
  17715. const data = this.get( renderObject );
  17716. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  17717. }
  17718. }
  17719. /**
  17720. * This renderer module manages the bindings of the renderer.
  17721. *
  17722. * @private
  17723. * @augments DataMap
  17724. */
  17725. class Bindings extends DataMap {
  17726. /**
  17727. * Constructs a new bindings management component.
  17728. *
  17729. * @param {Backend} backend - The renderer's backend.
  17730. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17731. * @param {Textures} textures - Renderer component for managing textures.
  17732. * @param {Attributes} attributes - Renderer component for managing attributes.
  17733. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  17734. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  17735. */
  17736. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  17737. super();
  17738. /**
  17739. * The renderer's backend.
  17740. *
  17741. * @type {Backend}
  17742. */
  17743. this.backend = backend;
  17744. /**
  17745. * Renderer component for managing textures.
  17746. *
  17747. * @type {Textures}
  17748. */
  17749. this.textures = textures;
  17750. /**
  17751. * Renderer component for managing pipelines.
  17752. *
  17753. * @type {Pipelines}
  17754. */
  17755. this.pipelines = pipelines;
  17756. /**
  17757. * Renderer component for managing attributes.
  17758. *
  17759. * @type {Attributes}
  17760. */
  17761. this.attributes = attributes;
  17762. /**
  17763. * Renderer component for managing nodes related logic.
  17764. *
  17765. * @type {Nodes}
  17766. */
  17767. this.nodes = nodes;
  17768. /**
  17769. * Renderer component for managing metrics and monitoring data.
  17770. *
  17771. * @type {Info}
  17772. */
  17773. this.info = info;
  17774. this.pipelines.bindings = this; // assign bindings to pipelines
  17775. }
  17776. /**
  17777. * Returns the bind groups for the given render object.
  17778. *
  17779. * @param {RenderObject} renderObject - The render object.
  17780. * @return {Array<BindGroup>} The bind groups.
  17781. */
  17782. getForRender( renderObject ) {
  17783. const bindings = renderObject.getBindings();
  17784. for ( const bindGroup of bindings ) {
  17785. const groupData = this.get( bindGroup );
  17786. if ( groupData.bindGroup === undefined ) {
  17787. // each object defines an array of bindings (ubos, textures, samplers etc.)
  17788. this._init( bindGroup );
  17789. this.backend.createBindings( bindGroup, bindings, 0 );
  17790. groupData.bindGroup = bindGroup;
  17791. }
  17792. }
  17793. return bindings;
  17794. }
  17795. /**
  17796. * Returns the bind groups for the given compute node.
  17797. *
  17798. * @param {Node} computeNode - The compute node.
  17799. * @return {Array<BindGroup>} The bind groups.
  17800. */
  17801. getForCompute( computeNode ) {
  17802. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  17803. for ( const bindGroup of bindings ) {
  17804. const groupData = this.get( bindGroup );
  17805. if ( groupData.bindGroup === undefined ) {
  17806. this._init( bindGroup );
  17807. this.backend.createBindings( bindGroup, bindings, 0 );
  17808. groupData.bindGroup = bindGroup;
  17809. }
  17810. }
  17811. return bindings;
  17812. }
  17813. /**
  17814. * Updates the bindings for the given compute node.
  17815. *
  17816. * @param {Node} computeNode - The compute node.
  17817. */
  17818. updateForCompute( computeNode ) {
  17819. this._updateBindings( this.getForCompute( computeNode ) );
  17820. }
  17821. /**
  17822. * Updates the bindings for the given render object.
  17823. *
  17824. * @param {RenderObject} renderObject - The render object.
  17825. */
  17826. updateForRender( renderObject ) {
  17827. this._updateBindings( this.getForRender( renderObject ) );
  17828. }
  17829. /**
  17830. * Updates the given array of bindings.
  17831. *
  17832. * @param {Array<BindGroup>} bindings - The bind groups.
  17833. */
  17834. _updateBindings( bindings ) {
  17835. for ( const bindGroup of bindings ) {
  17836. this._update( bindGroup, bindings );
  17837. }
  17838. }
  17839. /**
  17840. * Initializes the given bind group.
  17841. *
  17842. * @param {BindGroup} bindGroup - The bind group to initialize.
  17843. */
  17844. _init( bindGroup ) {
  17845. for ( const binding of bindGroup.bindings ) {
  17846. if ( binding.isSampledTexture ) {
  17847. this.textures.updateTexture( binding.texture );
  17848. } else if ( binding.isStorageBuffer ) {
  17849. const attribute = binding.attribute;
  17850. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  17851. this.attributes.update( attribute, attributeType );
  17852. }
  17853. }
  17854. }
  17855. /**
  17856. * Updates the given bind group.
  17857. *
  17858. * @param {BindGroup} bindGroup - The bind group to update.
  17859. * @param {Array<BindGroup>} bindings - The bind groups.
  17860. */
  17861. _update( bindGroup, bindings ) {
  17862. const { backend } = this;
  17863. let needsBindingsUpdate = false;
  17864. let cacheBindings = true;
  17865. let cacheIndex = 0;
  17866. let version = 0;
  17867. // iterate over all bindings and check if buffer updates or a new binding group is required
  17868. for ( const binding of bindGroup.bindings ) {
  17869. if ( binding.isNodeUniformsGroup ) {
  17870. const updated = this.nodes.updateGroup( binding );
  17871. // every uniforms group is a uniform buffer. So if no update is required,
  17872. // we move one with the next binding. Otherwise the next if block will update the group.
  17873. if ( updated === false ) continue;
  17874. }
  17875. if ( binding.isUniformBuffer ) {
  17876. const updated = binding.update();
  17877. if ( updated ) {
  17878. backend.updateBinding( binding );
  17879. }
  17880. } else if ( binding.isSampler ) {
  17881. binding.update();
  17882. } else if ( binding.isSampledTexture ) {
  17883. const texturesTextureData = this.textures.get( binding.texture );
  17884. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  17885. const updated = binding.update();
  17886. const texture = binding.texture;
  17887. if ( updated ) {
  17888. this.textures.updateTexture( texture );
  17889. }
  17890. const textureData = backend.get( texture );
  17891. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  17892. cacheBindings = false;
  17893. } else {
  17894. cacheIndex = cacheIndex * 10 + texture.id;
  17895. version += texture.version;
  17896. }
  17897. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  17898. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  17899. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  17900. this.textures.updateTexture( texture );
  17901. needsBindingsUpdate = true;
  17902. }
  17903. if ( texture.isStorageTexture === true ) {
  17904. const textureData = this.get( texture );
  17905. if ( binding.store === true ) {
  17906. textureData.needsMipmap = true;
  17907. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  17908. this.backend.generateMipmaps( texture );
  17909. textureData.needsMipmap = false;
  17910. }
  17911. }
  17912. }
  17913. }
  17914. if ( needsBindingsUpdate === true ) {
  17915. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  17916. }
  17917. }
  17918. }
  17919. /**
  17920. * Default sorting function for opaque render items.
  17921. *
  17922. * @private
  17923. * @function
  17924. * @param {Object} a - The first render item.
  17925. * @param {Object} b - The second render item.
  17926. * @return {Number} A numeric value which defines the sort order.
  17927. */
  17928. function painterSortStable( a, b ) {
  17929. if ( a.groupOrder !== b.groupOrder ) {
  17930. return a.groupOrder - b.groupOrder;
  17931. } else if ( a.renderOrder !== b.renderOrder ) {
  17932. return a.renderOrder - b.renderOrder;
  17933. } else if ( a.material.id !== b.material.id ) {
  17934. return a.material.id - b.material.id;
  17935. } else if ( a.z !== b.z ) {
  17936. return a.z - b.z;
  17937. } else {
  17938. return a.id - b.id;
  17939. }
  17940. }
  17941. /**
  17942. * Default sorting function for transparent render items.
  17943. *
  17944. * @private
  17945. * @function
  17946. * @param {Object} a - The first render item.
  17947. * @param {Object} b - The second render item.
  17948. * @return {Number} A numeric value which defines the sort order.
  17949. */
  17950. function reversePainterSortStable( a, b ) {
  17951. if ( a.groupOrder !== b.groupOrder ) {
  17952. return a.groupOrder - b.groupOrder;
  17953. } else if ( a.renderOrder !== b.renderOrder ) {
  17954. return a.renderOrder - b.renderOrder;
  17955. } else if ( a.z !== b.z ) {
  17956. return b.z - a.z;
  17957. } else {
  17958. return a.id - b.id;
  17959. }
  17960. }
  17961. /**
  17962. * Returns `true` if the given transparent material requires a double pass.
  17963. *
  17964. * @private
  17965. * @function
  17966. * @param {Material} material - The transparent material.
  17967. * @return {Boolean} Whether the given material requires a double pass or not.
  17968. */
  17969. function needsDoublePass( material ) {
  17970. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  17971. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  17972. }
  17973. /**
  17974. * When the renderer analyzes the scene at the beginning of a render call,
  17975. * it stores 3D object for further processing in render lists. Depending on the
  17976. * properties of a 3D objects (like their transformation or material state), the
  17977. * objects are maintained in ordered lists for the actual rendering.
  17978. *
  17979. * Render lists are unique per scene and camera combination.
  17980. *
  17981. * @private
  17982. * @augments Pipeline
  17983. */
  17984. class RenderList {
  17985. /**
  17986. * Constructs a render list.
  17987. *
  17988. * @param {Lighting} lighting - The lighting management component.
  17989. * @param {Scene} scene - The scene.
  17990. * @param {Camera} camera - The camera the scene is rendered with.
  17991. */
  17992. constructor( lighting, scene, camera ) {
  17993. /**
  17994. * 3D objects are transformed into render items and stored in this array.
  17995. *
  17996. * @type {Array<Object>}
  17997. */
  17998. this.renderItems = [];
  17999. /**
  18000. * The current render items index.
  18001. *
  18002. * @type {Number}
  18003. * @default 0
  18004. */
  18005. this.renderItemsIndex = 0;
  18006. /**
  18007. * A list with opaque render items.
  18008. *
  18009. * @type {Array<Object>}
  18010. */
  18011. this.opaque = [];
  18012. /**
  18013. * A list with transparent render items which require
  18014. * double pass rendering (e.g. transmissive objects).
  18015. *
  18016. * @type {Array<Object>}
  18017. */
  18018. this.transparentDoublePass = [];
  18019. /**
  18020. * A list with transparent render items.
  18021. *
  18022. * @type {Array<Object>}
  18023. */
  18024. this.transparent = [];
  18025. /**
  18026. * A list with transparent render bundle data.
  18027. *
  18028. * @type {Array<Object>}
  18029. */
  18030. this.bundles = [];
  18031. /**
  18032. * The render list's lights node. This node is later
  18033. * relevant for the actual analytical light nodes which
  18034. * compute the scene's lighting in the shader.
  18035. *
  18036. * @type {LightsNode}
  18037. */
  18038. this.lightsNode = lighting.getNode( scene, camera );
  18039. /**
  18040. * The scene's lights stored in an array. This array
  18041. * is used to setup the lights node.
  18042. *
  18043. * @type {Array<Light>}
  18044. */
  18045. this.lightsArray = [];
  18046. /**
  18047. * The scene.
  18048. *
  18049. * @type {Scene}
  18050. */
  18051. this.scene = scene;
  18052. /**
  18053. * The camera the scene is rendered with.
  18054. *
  18055. * @type {Camera}
  18056. */
  18057. this.camera = camera;
  18058. /**
  18059. * How many objects perform occlusion query tests.
  18060. *
  18061. * @type {Number}
  18062. * @default 0
  18063. */
  18064. this.occlusionQueryCount = 0;
  18065. }
  18066. /**
  18067. * This method is called right at the beginning of a render call
  18068. * before the scene is analyzed. It prepares the internal data
  18069. * structures for the upcoming render lists generation.
  18070. *
  18071. * @return {RenderList} A reference to this render list.
  18072. */
  18073. begin() {
  18074. this.renderItemsIndex = 0;
  18075. this.opaque.length = 0;
  18076. this.transparentDoublePass.length = 0;
  18077. this.transparent.length = 0;
  18078. this.bundles.length = 0;
  18079. this.lightsArray.length = 0;
  18080. this.occlusionQueryCount = 0;
  18081. return this;
  18082. }
  18083. /**
  18084. * Returns a render item for the giving render item state. The state is defined
  18085. * by a series of object-related parameters.
  18086. *
  18087. * The method avoids object creation by holding render items and reusing them in
  18088. * subsequent render calls (just with different property values).
  18089. *
  18090. * @param {Object3D} object - The 3D object.
  18091. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18092. * @param {Material} material - The 3D object's material.
  18093. * @param {Number} groupOrder - The current group order.
  18094. * @param {Number} z - Th 3D object's depth value (z value in clip space).
  18095. * @param {Number?} group - {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18096. * @param {ClippingContext} clippingContext - The current clipping context.
  18097. * @return {Object} The render item.
  18098. */
  18099. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18100. let renderItem = this.renderItems[ this.renderItemsIndex ];
  18101. if ( renderItem === undefined ) {
  18102. renderItem = {
  18103. id: object.id,
  18104. object: object,
  18105. geometry: geometry,
  18106. material: material,
  18107. groupOrder: groupOrder,
  18108. renderOrder: object.renderOrder,
  18109. z: z,
  18110. group: group,
  18111. clippingContext: clippingContext
  18112. };
  18113. this.renderItems[ this.renderItemsIndex ] = renderItem;
  18114. } else {
  18115. renderItem.id = object.id;
  18116. renderItem.object = object;
  18117. renderItem.geometry = geometry;
  18118. renderItem.material = material;
  18119. renderItem.groupOrder = groupOrder;
  18120. renderItem.renderOrder = object.renderOrder;
  18121. renderItem.z = z;
  18122. renderItem.group = group;
  18123. renderItem.clippingContext = clippingContext;
  18124. }
  18125. this.renderItemsIndex ++;
  18126. return renderItem;
  18127. }
  18128. /**
  18129. * Pushes the given object as a render item to the internal render lists.
  18130. * The selected lists depend on the object properties.
  18131. *
  18132. * @param {Object3D} object - The 3D object.
  18133. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18134. * @param {Material} material - The 3D object's material.
  18135. * @param {Number} groupOrder - The current group order.
  18136. * @param {Number} z - Th 3D object's depth value (z value in clip space).
  18137. * @param {Number?} group - {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18138. * @param {ClippingContext} clippingContext - The current clipping context.
  18139. */
  18140. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18141. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  18142. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  18143. if ( material.transparent === true || material.transmission > 0 ) {
  18144. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  18145. this.transparent.push( renderItem );
  18146. } else {
  18147. this.opaque.push( renderItem );
  18148. }
  18149. }
  18150. /**
  18151. * Inserts the given object as a render item at the start of the internal render lists.
  18152. * The selected lists depend on the object properties.
  18153. *
  18154. * @param {Object3D} object - The 3D object.
  18155. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18156. * @param {Material} material - The 3D object's material.
  18157. * @param {Number} groupOrder - The current group order.
  18158. * @param {Number} z - Th 3D object's depth value (z value in clip space).
  18159. * @param {Number?} group - {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18160. * @param {ClippingContext} clippingContext - The current clipping context.
  18161. */
  18162. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18163. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  18164. if ( material.transparent === true || material.transmission > 0 ) {
  18165. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  18166. this.transparent.unshift( renderItem );
  18167. } else {
  18168. this.opaque.unshift( renderItem );
  18169. }
  18170. }
  18171. /**
  18172. * Pushes render bundle group data into the render list.
  18173. *
  18174. * @param {Object} group - Bundle group data.
  18175. */
  18176. pushBundle( group ) {
  18177. this.bundles.push( group );
  18178. }
  18179. /**
  18180. * Pushes a light into the render list.
  18181. *
  18182. * @param {Light} light - The light.
  18183. */
  18184. pushLight( light ) {
  18185. this.lightsArray.push( light );
  18186. }
  18187. /**
  18188. * Sorts the internal render lists.
  18189. *
  18190. * @param {Function} customOpaqueSort - A custom sort function for opaque objects.
  18191. * @param {Function} customTransparentSort - A custom sort function for transparent objects.
  18192. */
  18193. sort( customOpaqueSort, customTransparentSort ) {
  18194. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  18195. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  18196. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  18197. }
  18198. /**
  18199. * This method performs finalizing tasks right after the render lists
  18200. * have been generated.
  18201. */
  18202. finish() {
  18203. // update lights
  18204. this.lightsNode.setLights( this.lightsArray );
  18205. // Clear references from inactive renderItems in the list
  18206. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  18207. const renderItem = this.renderItems[ i ];
  18208. if ( renderItem.id === null ) break;
  18209. renderItem.id = null;
  18210. renderItem.object = null;
  18211. renderItem.geometry = null;
  18212. renderItem.material = null;
  18213. renderItem.groupOrder = null;
  18214. renderItem.renderOrder = null;
  18215. renderItem.z = null;
  18216. renderItem.group = null;
  18217. renderItem.clippingContext = null;
  18218. }
  18219. }
  18220. }
  18221. /**
  18222. * This renderer module manages the render lists which are unique
  18223. * per scene and camera combination.
  18224. *
  18225. * @private
  18226. */
  18227. class RenderLists {
  18228. /**
  18229. * Constructs a render lists management component.
  18230. *
  18231. * @param {Lighting} lighting - The lighting management component.
  18232. */
  18233. constructor( lighting ) {
  18234. /**
  18235. * The lighting management component.
  18236. *
  18237. * @type {Lighting}
  18238. */
  18239. this.lighting = lighting;
  18240. /**
  18241. * The internal chain map which holds the render lists.
  18242. *
  18243. * @type {ChainMap}
  18244. */
  18245. this.lists = new ChainMap();
  18246. }
  18247. /**
  18248. * Returns a render list for the given scene and camera.
  18249. *
  18250. * @param {Scene} scene - The scene.
  18251. * @param {Camera} camera - The camera.
  18252. * @return {RenderList} The render list.
  18253. */
  18254. get( scene, camera ) {
  18255. const lists = this.lists;
  18256. const keys = [ scene, camera ];
  18257. let list = lists.get( keys );
  18258. if ( list === undefined ) {
  18259. list = new RenderList( this.lighting, scene, camera );
  18260. lists.set( keys, list );
  18261. }
  18262. return list;
  18263. }
  18264. /**
  18265. * Frees all internal resources.
  18266. */
  18267. dispose() {
  18268. this.lists = new ChainMap();
  18269. }
  18270. }
  18271. let _id$7 = 0;
  18272. /**
  18273. * Any render or compute command is executed in a specific context that defines
  18274. * the state of the renderer and its backend. Typical examples for such context
  18275. * data are the current clear values or data from the active framebuffer. This
  18276. * module is used to represent these contexts as objects.
  18277. *
  18278. * @private
  18279. */
  18280. class RenderContext {
  18281. /**
  18282. * Constructs a new render context.
  18283. */
  18284. constructor() {
  18285. /**
  18286. * The context's ID.
  18287. *
  18288. * @type {Number}
  18289. */
  18290. this.id = _id$7 ++;
  18291. /**
  18292. * Whether the current active framebuffer has a color attachment.
  18293. *
  18294. * @type {Boolean}
  18295. * @default true
  18296. */
  18297. this.color = true;
  18298. /**
  18299. * Whether the color attachment should be cleared or not.
  18300. *
  18301. * @type {Boolean}
  18302. * @default true
  18303. */
  18304. this.clearColor = true;
  18305. /**
  18306. * The clear color value.
  18307. *
  18308. * @type {Object}
  18309. * @default true
  18310. */
  18311. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  18312. /**
  18313. * Whether the current active framebuffer has a depth attachment.
  18314. *
  18315. * @type {Boolean}
  18316. * @default true
  18317. */
  18318. this.depth = true;
  18319. /**
  18320. * Whether the depth attachment should be cleared or not.
  18321. *
  18322. * @type {Boolean}
  18323. * @default true
  18324. */
  18325. this.clearDepth = true;
  18326. /**
  18327. * The clear depth value.
  18328. *
  18329. * @type {Number}
  18330. * @default 1
  18331. */
  18332. this.clearDepthValue = 1;
  18333. /**
  18334. * Whether the current active framebuffer has a stencil attachment.
  18335. *
  18336. * @type {Boolean}
  18337. * @default false
  18338. */
  18339. this.stencil = false;
  18340. /**
  18341. * Whether the stencil attachment should be cleared or not.
  18342. *
  18343. * @type {Boolean}
  18344. * @default true
  18345. */
  18346. this.clearStencil = true;
  18347. /**
  18348. * The clear stencil value.
  18349. *
  18350. * @type {Number}
  18351. * @default 1
  18352. */
  18353. this.clearStencilValue = 1;
  18354. /**
  18355. * By default the viewport encloses the entire framebuffer If a smaller
  18356. * viewport is manually defined, this property is to `true` by the renderer.
  18357. *
  18358. * @type {Boolean}
  18359. * @default false
  18360. */
  18361. this.viewport = false;
  18362. /**
  18363. * The viewport value. This value is in physical pixels meaning it incorporates
  18364. * the renderer's pixel ratio. The viewport property of render targets or
  18365. * the renderer is in logical pixels.
  18366. *
  18367. * @type {Vector4}
  18368. */
  18369. this.viewportValue = new Vector4();
  18370. /**
  18371. * When the scissor test is active and scissor rectangle smaller than the
  18372. * framebuffers dimensions, this property is to `true` by the renderer.
  18373. *
  18374. * @type {Boolean}
  18375. * @default false
  18376. */
  18377. this.scissor = false;
  18378. /**
  18379. * The scissor rectangle.
  18380. *
  18381. * @type {Vector4}
  18382. */
  18383. this.scissorValue = new Vector4();
  18384. /**
  18385. * The textures of the active render target.
  18386. * `null` when no render target is set.
  18387. *
  18388. * @type {Array<Texture>?}
  18389. * @default null
  18390. */
  18391. this.textures = null;
  18392. /**
  18393. * The depth texture of the active render target.
  18394. * `null` when no render target is set.
  18395. *
  18396. * @type {DepthTexture?}
  18397. * @default null
  18398. */
  18399. this.depthTexture = null;
  18400. /**
  18401. * The active cube face.
  18402. *
  18403. * @type {Number}
  18404. * @default 0
  18405. */
  18406. this.activeCubeFace = 0;
  18407. /**
  18408. * The number of MSAA samples. This value is always `1` when
  18409. * MSAA isn't used.
  18410. *
  18411. * @type {Number}
  18412. * @default 1
  18413. */
  18414. this.sampleCount = 1;
  18415. /**
  18416. * The framebuffers width in physical pixels.
  18417. *
  18418. * @type {Number}
  18419. * @default 0
  18420. */
  18421. this.width = 0;
  18422. /**
  18423. * The framebuffers height in physical pixels.
  18424. *
  18425. * @type {Number}
  18426. * @default 0
  18427. */
  18428. this.height = 0;
  18429. /**
  18430. * This flag can be used for type testing.
  18431. *
  18432. * @type {Boolean}
  18433. * @readonly
  18434. * @default true
  18435. */
  18436. this.isRenderContext = true;
  18437. }
  18438. /**
  18439. * Returns the cache key of this render context.
  18440. *
  18441. * @return {Number} The cache key.
  18442. */
  18443. getCacheKey() {
  18444. return getCacheKey( this );
  18445. }
  18446. }
  18447. /**
  18448. * Computes a cache key for the given render context.
  18449. *
  18450. * @param {RenderContext} renderContext - The render context.
  18451. * @return {Number} The cache key.
  18452. */
  18453. function getCacheKey( renderContext ) {
  18454. const { textures, activeCubeFace } = renderContext;
  18455. const values = [ activeCubeFace ];
  18456. for ( const texture of textures ) {
  18457. values.push( texture.id );
  18458. }
  18459. return hashArray( values );
  18460. }
  18461. /**
  18462. * This module manages the render contexts of the renderer.
  18463. *
  18464. * @private
  18465. */
  18466. class RenderContexts {
  18467. /**
  18468. * Constructs a new render context management component.
  18469. */
  18470. constructor() {
  18471. /**
  18472. * A dictionary that manages render contexts in chain maps
  18473. * for each attachment state.
  18474. *
  18475. * @type {Object<String,ChainMap>}
  18476. */
  18477. this.chainMaps = {};
  18478. }
  18479. /**
  18480. * Returns a render context for the given scene, camera and render target.
  18481. *
  18482. * @param {Scene?} [scene=null] - The scene. The parameter can become `null` e.g. when the renderer clears a render target.
  18483. * @param {Camera?} [camera=null] - The camera that is used to render the scene. The parameter can become `null` e.g. when the renderer clears a render target.
  18484. * @param {RenderTarget?} [renderTarget=null] - The active render target.
  18485. * @return {RenderContext} The render context.
  18486. */
  18487. get( scene = null, camera = null, renderTarget = null ) {
  18488. const chainKey = [];
  18489. if ( scene !== null ) chainKey.push( scene );
  18490. if ( camera !== null ) chainKey.push( camera );
  18491. if ( chainKey.length === 0 ) {
  18492. chainKey.push( { id: 'default' } );
  18493. }
  18494. let attachmentState;
  18495. if ( renderTarget === null ) {
  18496. attachmentState = 'default';
  18497. } else {
  18498. const format = renderTarget.texture.format;
  18499. const count = renderTarget.textures.length;
  18500. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  18501. }
  18502. const chainMap = this.getChainMap( attachmentState );
  18503. let renderState = chainMap.get( chainKey );
  18504. if ( renderState === undefined ) {
  18505. renderState = new RenderContext();
  18506. chainMap.set( chainKey, renderState );
  18507. }
  18508. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  18509. return renderState;
  18510. }
  18511. /**
  18512. * Returns a chain map for the given attachment state.
  18513. *
  18514. * @param {String} attachmentState - The attachment state.
  18515. * @return {ChainMap} The chain map.
  18516. */
  18517. getChainMap( attachmentState ) {
  18518. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  18519. }
  18520. /**
  18521. * Frees internal resources.
  18522. */
  18523. dispose() {
  18524. this.chainMaps = {};
  18525. }
  18526. }
  18527. const _size$3 = /*@__PURE__*/ new Vector3();
  18528. /**
  18529. * This module manages the textures of the renderer.
  18530. *
  18531. * @private
  18532. * @augments DataMap
  18533. */
  18534. class Textures extends DataMap {
  18535. /**
  18536. * Constructs a new texture management component.
  18537. *
  18538. * @param {Renderer} renderer - The renderer.
  18539. * @param {Backend} backend - The renderer's backend.
  18540. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  18541. */
  18542. constructor( renderer, backend, info ) {
  18543. super();
  18544. /**
  18545. * The renderer.
  18546. *
  18547. * @type {Renderer}
  18548. */
  18549. this.renderer = renderer;
  18550. /**
  18551. * The backend.
  18552. *
  18553. * @type {Backend}
  18554. */
  18555. this.backend = backend;
  18556. /**
  18557. * Renderer component for managing metrics and monitoring data.
  18558. *
  18559. * @type {Info}
  18560. */
  18561. this.info = info;
  18562. }
  18563. /**
  18564. * Updates the given render target. Based on the given render target configuration,
  18565. * it updates the texture states representing the attachments of the framebuffer.
  18566. *
  18567. * @param {RenderTarget} renderTarget - The render target to update.
  18568. * @param {Number} [activeMipmapLevel=0] - The active mipmap level.
  18569. */
  18570. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  18571. const renderTargetData = this.get( renderTarget );
  18572. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  18573. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  18574. const textures = renderTarget.textures;
  18575. const size = this.getSize( textures[ 0 ] );
  18576. const mipWidth = size.width >> activeMipmapLevel;
  18577. const mipHeight = size.height >> activeMipmapLevel;
  18578. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  18579. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  18580. let textureNeedsUpdate = false;
  18581. if ( depthTexture === undefined && useDepthTexture ) {
  18582. depthTexture = new DepthTexture();
  18583. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  18584. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  18585. depthTexture.image.width = mipWidth;
  18586. depthTexture.image.height = mipHeight;
  18587. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  18588. }
  18589. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  18590. textureNeedsUpdate = true;
  18591. if ( depthTexture ) {
  18592. depthTexture.needsUpdate = true;
  18593. depthTexture.image.width = mipWidth;
  18594. depthTexture.image.height = mipHeight;
  18595. }
  18596. }
  18597. renderTargetData.width = size.width;
  18598. renderTargetData.height = size.height;
  18599. renderTargetData.textures = textures;
  18600. renderTargetData.depthTexture = depthTexture || null;
  18601. renderTargetData.depth = renderTarget.depthBuffer;
  18602. renderTargetData.stencil = renderTarget.stencilBuffer;
  18603. renderTargetData.renderTarget = renderTarget;
  18604. if ( renderTargetData.sampleCount !== sampleCount ) {
  18605. textureNeedsUpdate = true;
  18606. if ( depthTexture ) {
  18607. depthTexture.needsUpdate = true;
  18608. }
  18609. renderTargetData.sampleCount = sampleCount;
  18610. }
  18611. //
  18612. const options = { sampleCount };
  18613. for ( let i = 0; i < textures.length; i ++ ) {
  18614. const texture = textures[ i ];
  18615. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  18616. this.updateTexture( texture, options );
  18617. }
  18618. if ( depthTexture ) {
  18619. this.updateTexture( depthTexture, options );
  18620. }
  18621. // dispose handler
  18622. if ( renderTargetData.initialized !== true ) {
  18623. renderTargetData.initialized = true;
  18624. // dispose
  18625. const onDispose = () => {
  18626. renderTarget.removeEventListener( 'dispose', onDispose );
  18627. for ( let i = 0; i < textures.length; i ++ ) {
  18628. this._destroyTexture( textures[ i ] );
  18629. }
  18630. if ( depthTexture ) {
  18631. this._destroyTexture( depthTexture );
  18632. }
  18633. this.delete( renderTarget );
  18634. };
  18635. renderTarget.addEventListener( 'dispose', onDispose );
  18636. }
  18637. }
  18638. /**
  18639. * Updates the given texture. Depending on the texture state, this method
  18640. * triggers the upload of texture data to the GPU memory. If the texture data are
  18641. * not yet ready for the upload, it uses default texture data for as a placeholder.
  18642. *
  18643. * @param {Texture} texture - The texture to update.
  18644. * @param {Object} [options={}] - The options.
  18645. */
  18646. updateTexture( texture, options = {} ) {
  18647. const textureData = this.get( texture );
  18648. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  18649. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  18650. const backend = this.backend;
  18651. if ( isRenderTarget && textureData.initialized === true ) {
  18652. // it's an update
  18653. backend.destroySampler( texture );
  18654. backend.destroyTexture( texture );
  18655. }
  18656. //
  18657. if ( texture.isFramebufferTexture ) {
  18658. const renderTarget = this.renderer.getRenderTarget();
  18659. if ( renderTarget ) {
  18660. texture.type = renderTarget.texture.type;
  18661. } else {
  18662. texture.type = UnsignedByteType;
  18663. }
  18664. }
  18665. //
  18666. const { width, height, depth } = this.getSize( texture );
  18667. options.width = width;
  18668. options.height = height;
  18669. options.depth = depth;
  18670. options.needsMipmaps = this.needsMipmaps( texture );
  18671. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  18672. //
  18673. if ( isRenderTarget || texture.isStorageTexture === true ) {
  18674. backend.createSampler( texture );
  18675. backend.createTexture( texture, options );
  18676. textureData.generation = texture.version;
  18677. } else {
  18678. const needsCreate = textureData.initialized !== true;
  18679. if ( needsCreate ) backend.createSampler( texture );
  18680. if ( texture.version > 0 ) {
  18681. const image = texture.image;
  18682. if ( image === undefined ) {
  18683. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  18684. } else if ( image.complete === false ) {
  18685. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  18686. } else {
  18687. if ( texture.images ) {
  18688. const images = [];
  18689. for ( const image of texture.images ) {
  18690. images.push( image );
  18691. }
  18692. options.images = images;
  18693. } else {
  18694. options.image = image;
  18695. }
  18696. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  18697. backend.createTexture( texture, options );
  18698. textureData.isDefaultTexture = false;
  18699. textureData.generation = texture.version;
  18700. }
  18701. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  18702. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  18703. }
  18704. } else {
  18705. // async update
  18706. backend.createDefaultTexture( texture );
  18707. textureData.isDefaultTexture = true;
  18708. textureData.generation = texture.version;
  18709. }
  18710. }
  18711. // dispose handler
  18712. if ( textureData.initialized !== true ) {
  18713. textureData.initialized = true;
  18714. textureData.generation = texture.version;
  18715. //
  18716. this.info.memory.textures ++;
  18717. // dispose
  18718. const onDispose = () => {
  18719. texture.removeEventListener( 'dispose', onDispose );
  18720. this._destroyTexture( texture );
  18721. this.info.memory.textures --;
  18722. };
  18723. texture.addEventListener( 'dispose', onDispose );
  18724. }
  18725. //
  18726. textureData.version = texture.version;
  18727. }
  18728. /**
  18729. * Computes the size of the given texture and writes the result
  18730. * into the target vector. This vector is also returned by the
  18731. * method.
  18732. *
  18733. * If no texture data are available for the compute yet, the method
  18734. * returns default size values.
  18735. *
  18736. * @param {Texture} texture - The texture to compute the size for.
  18737. * @param {Vector3} target - The target vector.
  18738. * @return {Vector3} The target vector.
  18739. */
  18740. getSize( texture, target = _size$3 ) {
  18741. let image = texture.images ? texture.images[ 0 ] : texture.image;
  18742. if ( image ) {
  18743. if ( image.image !== undefined ) image = image.image;
  18744. target.width = image.width || 1;
  18745. target.height = image.height || 1;
  18746. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  18747. } else {
  18748. target.width = target.height = target.depth = 1;
  18749. }
  18750. return target;
  18751. }
  18752. /**
  18753. * Computes the number of mipmap levels for the given texture.
  18754. *
  18755. * @param {Texture} texture - The texture.
  18756. * @param {Number} width - The texture's width.
  18757. * @param {Number} height - The texture's height.
  18758. * @return {Number} The number of mipmap levels.
  18759. */
  18760. getMipLevels( texture, width, height ) {
  18761. let mipLevelCount;
  18762. if ( texture.isCompressedTexture ) {
  18763. if ( texture.mipmaps ) {
  18764. mipLevelCount = texture.mipmaps.length;
  18765. } else {
  18766. mipLevelCount = 1;
  18767. }
  18768. } else {
  18769. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  18770. }
  18771. return mipLevelCount;
  18772. }
  18773. /**
  18774. * Returns `true` if the given texture requires mipmaps.
  18775. *
  18776. * @param {Texture} texture - The texture.
  18777. * @return {Boolean} Whether mipmaps are required or not.
  18778. */
  18779. needsMipmaps( texture ) {
  18780. return this.isEnvironmentTexture( texture ) || texture.isCompressedTexture === true || texture.generateMipmaps;
  18781. }
  18782. /**
  18783. * Returns `true` if the given texture is an environment map.
  18784. *
  18785. * @param {Texture} texture - The texture.
  18786. * @return {Boolean} Whether the given texture is an environment map or not.
  18787. */
  18788. isEnvironmentTexture( texture ) {
  18789. const mapping = texture.mapping;
  18790. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  18791. }
  18792. /**
  18793. * Frees internal resource when the given texture isn't
  18794. * required anymore.
  18795. *
  18796. * @param {Texture} texture - The texture to destroy.
  18797. */
  18798. _destroyTexture( texture ) {
  18799. this.backend.destroySampler( texture );
  18800. this.backend.destroyTexture( texture );
  18801. this.delete( texture );
  18802. }
  18803. }
  18804. /**
  18805. * A four-component version of {@link Color} which is internally
  18806. * used by the renderer to represents clear color with alpha as
  18807. * one object.
  18808. *
  18809. * @private
  18810. * @augments Color
  18811. */
  18812. class Color4 extends Color {
  18813. /**
  18814. * Constructs a new four-component color.
  18815. *
  18816. * @param {Number|String} r - The red value.
  18817. * @param {Number} g - The green value.
  18818. * @param {Number} b - The blue value.
  18819. * @param {Number} [a=1] - The alpha value.
  18820. */
  18821. constructor( r, g, b, a = 1 ) {
  18822. super( r, g, b );
  18823. this.a = a;
  18824. }
  18825. /**
  18826. * Overwrites the default to honor alpha.
  18827. *
  18828. * @param {Number|String} r - The red value.
  18829. * @param {Number} g - The green value.
  18830. * @param {Number} b - The blue value.
  18831. * @param {Number} [a=1] - The alpha value.
  18832. * @return {Color4} A reference to this object.
  18833. */
  18834. set( r, g, b, a = 1 ) {
  18835. this.a = a;
  18836. return super.set( r, g, b );
  18837. }
  18838. /**
  18839. * Overwrites the default to honor alpha.
  18840. *
  18841. * @param {Color4} color - The color to copy.
  18842. * @return {Color4} A reference to this object.
  18843. */
  18844. copy( color ) {
  18845. if ( color.a !== undefined ) this.a = color.a;
  18846. return super.copy( color );
  18847. }
  18848. /**
  18849. * Overwrites the default to honor alpha.
  18850. *
  18851. * @return {Color4} The cloned color.
  18852. */
  18853. clone() {
  18854. return new this.constructor( this.r, this.g, this.b, this.a );
  18855. }
  18856. }
  18857. /** @module ParameterNode **/
  18858. /**
  18859. * Special version of {@link PropertyNode} which is used for parameters.
  18860. *
  18861. * @augments PropertyNode
  18862. */
  18863. class ParameterNode extends PropertyNode {
  18864. static get type() {
  18865. return 'ParameterNode';
  18866. }
  18867. /**
  18868. * Constructs a new parameter node.
  18869. *
  18870. * @param {String} nodeType - The type of the node.
  18871. * @param {String?} [name=null] - The name of the parameter in the shader.
  18872. */
  18873. constructor( nodeType, name = null ) {
  18874. super( nodeType, name );
  18875. /**
  18876. * This flag can be used for type testing.
  18877. *
  18878. * @type {Boolean}
  18879. * @readonly
  18880. * @default true
  18881. */
  18882. this.isParameterNode = true;
  18883. }
  18884. getHash() {
  18885. return this.uuid;
  18886. }
  18887. generate() {
  18888. return this.name;
  18889. }
  18890. }
  18891. /**
  18892. * TSL function for creating a parameter node.
  18893. *
  18894. * @function
  18895. * @param {String} type - The type of the node.
  18896. * @param {String?} name - The name of the parameter in the shader.
  18897. * @returns {ParameterNode}
  18898. */
  18899. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  18900. /** @module StackNode **/
  18901. /**
  18902. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  18903. * They are usually needed in cases like `If`, `Else`.
  18904. *
  18905. * @augments Node
  18906. */
  18907. class StackNode extends Node {
  18908. static get type() {
  18909. return 'StackNode';
  18910. }
  18911. /**
  18912. * Constructs a new stack node.
  18913. *
  18914. * @param {StackNode?} [parent=null] - The parent stack node.
  18915. */
  18916. constructor( parent = null ) {
  18917. super();
  18918. /**
  18919. * List of nodes.
  18920. *
  18921. * @type {Array<Node>}
  18922. */
  18923. this.nodes = [];
  18924. /**
  18925. * The output node.
  18926. *
  18927. * @type {Node?}
  18928. * @default null
  18929. */
  18930. this.outputNode = null;
  18931. /**
  18932. * The parent stack node.
  18933. *
  18934. * @type {StackNode}
  18935. * @default null
  18936. */
  18937. this.parent = parent;
  18938. /**
  18939. * The current conditional node.
  18940. *
  18941. * @private
  18942. * @type {ConditionalNode}
  18943. * @default null
  18944. */
  18945. this._currentCond = null;
  18946. /**
  18947. * This flag can be used for type testing.
  18948. *
  18949. * @type {Boolean}
  18950. * @readonly
  18951. * @default true
  18952. */
  18953. this.isStackNode = true;
  18954. }
  18955. getNodeType( builder ) {
  18956. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  18957. }
  18958. /**
  18959. * Adds a node to this stack.
  18960. *
  18961. * @param {Node} node - The node to add.
  18962. * @return {StackNode} A reference to this stack node.
  18963. */
  18964. add( node ) {
  18965. this.nodes.push( node );
  18966. return this;
  18967. }
  18968. /**
  18969. * Represent an `if` statement in TSL.
  18970. *
  18971. * @param {Node} boolNode - Represents the condition.
  18972. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  18973. * @return {StackNode} A reference to this stack node.
  18974. */
  18975. If( boolNode, method ) {
  18976. const methodNode = new ShaderNode( method );
  18977. this._currentCond = select( boolNode, methodNode );
  18978. return this.add( this._currentCond );
  18979. }
  18980. /**
  18981. * Represent an `elseif` statement in TSL.
  18982. *
  18983. * @param {Node} boolNode - Represents the condition.
  18984. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  18985. * @return {StackNode} A reference to this stack node.
  18986. */
  18987. ElseIf( boolNode, method ) {
  18988. const methodNode = new ShaderNode( method );
  18989. const ifNode = select( boolNode, methodNode );
  18990. this._currentCond.elseNode = ifNode;
  18991. this._currentCond = ifNode;
  18992. return this;
  18993. }
  18994. /**
  18995. * Represent an `else` statement in TSL.
  18996. *
  18997. * @param {Function} method - TSL code which is executed in the `else` case.
  18998. * @return {StackNode} A reference to this stack node.
  18999. */
  19000. Else( method ) {
  19001. this._currentCond.elseNode = new ShaderNode( method );
  19002. return this;
  19003. }
  19004. build( builder, ...params ) {
  19005. const previousStack = getCurrentStack();
  19006. setCurrentStack( this );
  19007. for ( const node of this.nodes ) {
  19008. node.build( builder, 'void' );
  19009. }
  19010. setCurrentStack( previousStack );
  19011. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  19012. }
  19013. //
  19014. else( ...params ) { // @deprecated, r168
  19015. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  19016. return this.Else( ...params );
  19017. }
  19018. elseif( ...params ) { // @deprecated, r168
  19019. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  19020. return this.ElseIf( ...params );
  19021. }
  19022. }
  19023. /**
  19024. * TSL function for creating a stack node.
  19025. *
  19026. * @function
  19027. * @param {StackNode?} [parent=null] - The parent stack node.
  19028. * @returns {StackNode}
  19029. */
  19030. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  19031. /** @module OutputStructNode **/
  19032. /**
  19033. * This node can be used to define multiple outputs in a shader programs.
  19034. *
  19035. * @augments Node
  19036. */
  19037. class OutputStructNode extends Node {
  19038. static get type() {
  19039. return 'OutputStructNode';
  19040. }
  19041. /**
  19042. * Constructs a new output struct node. The constructor can be invoked with an
  19043. * arbitrary number of nodes representing the members.
  19044. *
  19045. * @param {...Node} members - A parameter list of nodes.
  19046. */
  19047. constructor( ...members ) {
  19048. super();
  19049. /**
  19050. * An array of nodes which defines the output.
  19051. *
  19052. * @type {Array<Node>}
  19053. */
  19054. this.members = members;
  19055. /**
  19056. * This flag can be used for type testing.
  19057. *
  19058. * @type {Boolean}
  19059. * @readonly
  19060. * @default true
  19061. */
  19062. this.isOutputStructNode = true;
  19063. }
  19064. setup( builder ) {
  19065. super.setup( builder );
  19066. const members = this.members;
  19067. const types = [];
  19068. for ( let i = 0; i < members.length; i ++ ) {
  19069. types.push( members[ i ].getNodeType( builder ) );
  19070. }
  19071. this.nodeType = builder.getStructTypeFromNode( this, types ).name;
  19072. }
  19073. generate( builder, output ) {
  19074. const propertyName = builder.getOutputStructName();
  19075. const members = this.members;
  19076. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  19077. for ( let i = 0; i < members.length; i ++ ) {
  19078. const snippet = members[ i ].build( builder, output );
  19079. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  19080. }
  19081. return propertyName;
  19082. }
  19083. }
  19084. /**
  19085. * TSL function for creating an output struct node.
  19086. *
  19087. * @function
  19088. * @param {...Node} members - A parameter list of nodes.
  19089. * @returns {OutputStructNode}
  19090. */
  19091. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  19092. /** @module MRTNode **/
  19093. /**
  19094. * Returns the MRT texture index for the given name.
  19095. *
  19096. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  19097. * @param {String} name - The name of the MRT texture which index is requested.
  19098. * @return {Number} The texture index.
  19099. */
  19100. function getTextureIndex( textures, name ) {
  19101. for ( let i = 0; i < textures.length; i ++ ) {
  19102. if ( textures[ i ].name === name ) {
  19103. return i;
  19104. }
  19105. }
  19106. return - 1;
  19107. }
  19108. /**
  19109. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  19110. * post-processing is shown below:
  19111. * ```js
  19112. * const mrtNode = mrt( {
  19113. * output: output,
  19114. * normal: normalView
  19115. * } ) );
  19116. * ```
  19117. * The MRT output is defined as a dictionary.
  19118. *
  19119. * @augments OutputStructNode
  19120. */
  19121. class MRTNode extends OutputStructNode {
  19122. static get type() {
  19123. return 'MRTNode';
  19124. }
  19125. /**
  19126. * Constructs a new output struct node.
  19127. *
  19128. * @param {Object<String, Node>} outputNodes - The MRT outputs.
  19129. */
  19130. constructor( outputNodes ) {
  19131. super();
  19132. /**
  19133. * A dictionary representing the MRT outputs. The key
  19134. * is the name of the output, the value the node which produces
  19135. * the output result.
  19136. *
  19137. * @type {Object<String, Node>}
  19138. */
  19139. this.outputNodes = outputNodes;
  19140. /**
  19141. * This flag can be used for type testing.
  19142. *
  19143. * @type {Boolean}
  19144. * @readonly
  19145. * @default true
  19146. */
  19147. this.isMRTNode = true;
  19148. }
  19149. /**
  19150. * Returns `true` if the MRT node has an output with the given name.
  19151. *
  19152. * @param {String} name - The name of the output.
  19153. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  19154. */
  19155. has( name ) {
  19156. return this.outputNodes[ name ] !== undefined;
  19157. }
  19158. /**
  19159. * Returns the output node for the given name.
  19160. *
  19161. * @param {String} name - The name of the output.
  19162. * @return {Node} The output node.
  19163. */
  19164. get( name ) {
  19165. return this.outputNodes[ name ];
  19166. }
  19167. /**
  19168. * Merges the outputs of the given MRT node with the outputs of this node.
  19169. *
  19170. * @param {MRTNode} mrtNode - The MRT to merge.
  19171. * @return {MRTNode} A new MRT node with merged outputs..
  19172. */
  19173. merge( mrtNode ) {
  19174. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  19175. return mrt( outputs );
  19176. }
  19177. setup( builder ) {
  19178. const outputNodes = this.outputNodes;
  19179. const mrt = builder.renderer.getRenderTarget();
  19180. const members = [];
  19181. const textures = mrt.textures;
  19182. for ( const name in outputNodes ) {
  19183. const index = getTextureIndex( textures, name );
  19184. members[ index ] = vec4( outputNodes[ name ] );
  19185. }
  19186. this.members = members;
  19187. return super.setup( builder );
  19188. }
  19189. }
  19190. /**
  19191. * TSL function for creating a MRT node.
  19192. *
  19193. * @function
  19194. * @param {Object<String, Node>} outputNodes - The MRT outputs.
  19195. * @returns {MRTNode}
  19196. */
  19197. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  19198. /** @module Hash **/
  19199. /**
  19200. * Generates a hash value in the range `[0, 1]` from the given seed.
  19201. *
  19202. * @method
  19203. * @param {Node<float>} seed - The seed.
  19204. * @return {Node<float>} The hash value.
  19205. */
  19206. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  19207. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  19208. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  19209. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  19210. const result = word.shiftRight( 22 ).bitXor( word );
  19211. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  19212. } );
  19213. /** @module MathUtils **/
  19214. /**
  19215. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  19216. * The corners are mapped to `0` and the center to `1`.
  19217. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19218. *
  19219. * @method
  19220. * @param {Node<float>} x - The value to remap.
  19221. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  19222. * @return {Node<float>} The remapped value.
  19223. */
  19224. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  19225. /**
  19226. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  19227. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  19228. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19229. *
  19230. * @method
  19231. * @param {Node<float>} x - The value to remap.
  19232. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  19233. * @return {Node<float>} The remapped value.
  19234. */
  19235. 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 ) );
  19236. /**
  19237. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  19238. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  19239. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19240. *
  19241. * @method
  19242. * @param {Node<float>} x - The value to remap.
  19243. * @param {Node<float>} a - First control parameter.
  19244. * @param {Node<float>} b - Second control parameter.
  19245. * @return {Node<float>} The remapped value.
  19246. */
  19247. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  19248. /**
  19249. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  19250. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19251. *
  19252. * @method
  19253. * @param {Node<float>} x - The value to compute the sin for.
  19254. * @param {Node<float>} k - Controls the amount of bounces.
  19255. * @return {Node<float>} The result value.
  19256. */
  19257. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  19258. // https://github.com/cabbibo/glsl-tri-noise-3d
  19259. /** @module TriNoise3D **/
  19260. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  19261. return x.fract().sub( .5 ).abs();
  19262. } ).setLayout( {
  19263. name: 'tri',
  19264. type: 'float',
  19265. inputs: [
  19266. { name: 'x', type: 'float' }
  19267. ]
  19268. } );
  19269. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  19270. 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. ) ) ) ) );
  19271. } ).setLayout( {
  19272. name: 'tri3',
  19273. type: 'vec3',
  19274. inputs: [
  19275. { name: 'p', type: 'vec3' }
  19276. ]
  19277. } );
  19278. /**
  19279. * Generates a noise value from the given position, speed and time parameters.
  19280. *
  19281. * @method
  19282. * @param {Node<vec3>} position - The position.
  19283. * @param {Node<float>} speed - The speed.
  19284. * @param {Node<float>} time - The time.
  19285. * @return {Node<float>} The generated noise.
  19286. */
  19287. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  19288. const p = vec3( position ).toVar();
  19289. const z = float( 1.4 ).toVar();
  19290. const rz = float( 0.0 ).toVar();
  19291. const bp = vec3( p ).toVar();
  19292. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  19293. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  19294. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  19295. bp.mulAssign( 1.8 );
  19296. z.mulAssign( 1.5 );
  19297. p.mulAssign( 1.2 );
  19298. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  19299. rz.addAssign( t.div( z ) );
  19300. bp.addAssign( 0.14 );
  19301. } );
  19302. return rz;
  19303. } ).setLayout( {
  19304. name: 'triNoise3D',
  19305. type: 'float',
  19306. inputs: [
  19307. { name: 'position', type: 'vec3' },
  19308. { name: 'speed', type: 'float' },
  19309. { name: 'time', type: 'float' }
  19310. ]
  19311. } );
  19312. /** @module FunctionOverloadingNode **/
  19313. /**
  19314. * This class allows to define multiple overloaded versions
  19315. * of the same function. Depending on the parameters of the function
  19316. * call, the node picks the best-fit overloaded version.
  19317. *
  19318. * @augments Node
  19319. */
  19320. class FunctionOverloadingNode extends Node {
  19321. static get type() {
  19322. return 'FunctionOverloadingNode';
  19323. }
  19324. /**
  19325. * Constructs a new function overloading node.
  19326. *
  19327. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  19328. * @param {...Node} parametersNodes - A list of parameter nodes.
  19329. */
  19330. constructor( functionNodes = [], ...parametersNodes ) {
  19331. super();
  19332. /**
  19333. * Array of `Fn` function definitions.
  19334. *
  19335. * @type {Array<Function>}
  19336. */
  19337. this.functionNodes = functionNodes;
  19338. /**
  19339. * A list of parameter nodes.
  19340. *
  19341. * @type {Array<Node>}
  19342. */
  19343. this.parametersNodes = parametersNodes;
  19344. /**
  19345. * The selected overloaded function call.
  19346. *
  19347. * @private
  19348. * @type {ShaderCallNodeInternal}
  19349. */
  19350. this._candidateFnCall = null;
  19351. /**
  19352. * This node is marked as global.
  19353. *
  19354. * @type {Boolean}
  19355. * @default true
  19356. */
  19357. this.global = true;
  19358. }
  19359. /**
  19360. * This method is overwritten since the node type is inferred from
  19361. * the function's return type.
  19362. *
  19363. * @param {NodeBuilder} builder - The current node builder.
  19364. * @return {String} The node type.
  19365. */
  19366. getNodeType() {
  19367. return this.functionNodes[ 0 ].shaderNode.layout.type;
  19368. }
  19369. setup( builder ) {
  19370. const params = this.parametersNodes;
  19371. let candidateFnCall = this._candidateFnCall;
  19372. if ( candidateFnCall === null ) {
  19373. let candidateFn = null;
  19374. let candidateScore = - 1;
  19375. for ( const functionNode of this.functionNodes ) {
  19376. const shaderNode = functionNode.shaderNode;
  19377. const layout = shaderNode.layout;
  19378. if ( layout === null ) {
  19379. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  19380. }
  19381. const inputs = layout.inputs;
  19382. if ( params.length === inputs.length ) {
  19383. let score = 0;
  19384. for ( let i = 0; i < params.length; i ++ ) {
  19385. const param = params[ i ];
  19386. const input = inputs[ i ];
  19387. if ( param.getNodeType( builder ) === input.type ) {
  19388. score ++;
  19389. } else {
  19390. score = 0;
  19391. }
  19392. }
  19393. if ( score > candidateScore ) {
  19394. candidateFn = functionNode;
  19395. candidateScore = score;
  19396. }
  19397. }
  19398. }
  19399. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  19400. }
  19401. return candidateFnCall;
  19402. }
  19403. }
  19404. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  19405. /**
  19406. * TSL function for creating a function overloading node.
  19407. *
  19408. * @function
  19409. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  19410. * @returns {FunctionOverloadingNode}
  19411. */
  19412. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  19413. /** @module Timer **/
  19414. /**
  19415. * Represents the elapsed time in seconds.
  19416. *
  19417. * @type {UniformNode<float>}
  19418. */
  19419. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  19420. /**
  19421. * Represents the delta time in seconds.
  19422. *
  19423. * @type {UniformNode<float>}
  19424. */
  19425. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  19426. /**
  19427. * Represents the current frame ID.
  19428. *
  19429. * @type {UniformNode<uint>}
  19430. */
  19431. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  19432. // Deprecated
  19433. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  19434. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  19435. return time.mul( timeScale );
  19436. };
  19437. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  19438. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  19439. return time.mul( timeScale );
  19440. };
  19441. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  19442. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  19443. return deltaTime.mul( timeScale );
  19444. };
  19445. /** @module Oscillators **/
  19446. /**
  19447. * Generates a sine wave oscillation based on a timer.
  19448. *
  19449. * @method
  19450. * @param {Node<float>} t - The timer to generate the oscillation with.
  19451. * @return {Node<float>} The oscillation node.
  19452. */
  19453. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  19454. /**
  19455. * Generates a square wave oscillation based on a timer.
  19456. *
  19457. * @method
  19458. * @param {Node<float>} t - The timer to generate the oscillation with.
  19459. * @return {Node<float>} The oscillation node.
  19460. */
  19461. const oscSquare = ( t = time ) => t.fract().round();
  19462. /**
  19463. * Generates a triangle wave oscillation based on a timer.
  19464. *
  19465. * @method
  19466. * @param {Node<float>} t - The timer to generate the oscillation with.
  19467. * @return {Node<float>} The oscillation node.
  19468. */
  19469. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  19470. /**
  19471. * Generates a sawtooth wave oscillation based on a timer.
  19472. *
  19473. * @method
  19474. * @param {Node<float>} t - The timer to generate the oscillation with.
  19475. * @return {Node<float>} The oscillation node.
  19476. */
  19477. const oscSawtooth = ( t = time ) => t.fract();
  19478. /** @module UVUtils **/
  19479. /**
  19480. * Rotates the given uv coordinates around a center point
  19481. *
  19482. * @method
  19483. * @param {Node<vec2>} uv - The uv coordinates.
  19484. * @param {Node<float>} rotation - The rotation defined in radians.
  19485. * @param {Node<vec2>} center - The center of rotation
  19486. * @return {Node<vec2>} The rotated uv coordinates.
  19487. */
  19488. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  19489. return rotate( uv.sub( center ), rotation ).add( center );
  19490. } );
  19491. /**
  19492. * Applies a spherical warping effect to the given uv coordinates.
  19493. *
  19494. * @method
  19495. * @param {Node<vec2>} uv - The uv coordinates.
  19496. * @param {Node<float>} strength - The strength of the effect.
  19497. * @param {Node<vec2>} center - The center point
  19498. * @return {Node<vec2>} The updated uv coordinates.
  19499. */
  19500. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  19501. const delta = uv.sub( center );
  19502. const delta2 = delta.dot( delta );
  19503. const delta4 = delta2.mul( delta2 );
  19504. const deltaOffset = delta4.mul( strength );
  19505. return uv.add( delta.mul( deltaOffset ) );
  19506. } );
  19507. /** @module SpriteUtils **/
  19508. /**
  19509. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  19510. * oriented always towards the camera.
  19511. *
  19512. * ```js
  19513. * material.vertexNode = billboarding();
  19514. * ```
  19515. *
  19516. * @method
  19517. * @param {Object} config - The configuration object.
  19518. * @param {Node<vec3>?} [config.position=null] - Can be used to define the vertex positions in world space.
  19519. * @param {Boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  19520. * @param {Boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  19521. * @return {Node<vec3>} The updated vertex position in clip space.
  19522. */
  19523. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  19524. let worldMatrix;
  19525. if ( position !== null ) {
  19526. worldMatrix = modelWorldMatrix.toVar();
  19527. worldMatrix[ 3 ][ 0 ] = position.x;
  19528. worldMatrix[ 3 ][ 1 ] = position.y;
  19529. worldMatrix[ 3 ][ 2 ] = position.z;
  19530. } else {
  19531. worldMatrix = modelWorldMatrix;
  19532. }
  19533. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  19534. if ( defined( horizontal ) ) {
  19535. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  19536. modelViewMatrix[ 0 ][ 1 ] = 0;
  19537. modelViewMatrix[ 0 ][ 2 ] = 0;
  19538. }
  19539. if ( defined( vertical ) ) {
  19540. modelViewMatrix[ 1 ][ 0 ] = 0;
  19541. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  19542. modelViewMatrix[ 1 ][ 2 ] = 0;
  19543. }
  19544. modelViewMatrix[ 2 ][ 0 ] = 0;
  19545. modelViewMatrix[ 2 ][ 1 ] = 0;
  19546. modelViewMatrix[ 2 ][ 2 ] = 1;
  19547. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  19548. } );
  19549. /** @module ViewportUtils **/
  19550. /**
  19551. * A special version of a screen uv function that involves a depth comparison
  19552. * when computing the final uvs. The function mitigates visual errors when
  19553. * using viewport texture nodes for refraction purposes. Without this function
  19554. * objects in front of a refractive surface might appear on the refractive surface
  19555. * which is incorrect.
  19556. *
  19557. * @method
  19558. * @param {Node<vec2>?} uv - Optional uv coordinates. By default `screenUV` is used.
  19559. * @return {Node<vec2>} The update uv coordinates.
  19560. */
  19561. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  19562. const depth = linearDepth();
  19563. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  19564. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  19565. return finalUV;
  19566. } );
  19567. /** @module SpriteSheetUVNode **/
  19568. /**
  19569. * Can be used to compute texture coordinates for animated sprite sheets.
  19570. *
  19571. * ```js
  19572. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  19573. *
  19574. * material.colorNode = texture( spriteSheet, uvNode );
  19575. * ```
  19576. *
  19577. * @augments Node
  19578. */
  19579. class SpriteSheetUVNode extends Node {
  19580. static get type() {
  19581. return 'SpriteSheetUVNode';
  19582. }
  19583. /**
  19584. * Constructs a new sprite sheet uv node.
  19585. *
  19586. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  19587. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  19588. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  19589. */
  19590. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  19591. super( 'vec2' );
  19592. /**
  19593. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  19594. *
  19595. * @type {Node<vec2>}
  19596. */
  19597. this.countNode = countNode;
  19598. /**
  19599. * The uv node.
  19600. *
  19601. * @type {Node<vec2>}
  19602. */
  19603. this.uvNode = uvNode;
  19604. /**
  19605. * The node that defines the current frame/sprite.
  19606. *
  19607. * @type {Node<float>}
  19608. */
  19609. this.frameNode = frameNode;
  19610. }
  19611. setup() {
  19612. const { frameNode, uvNode, countNode } = this;
  19613. const { width, height } = countNode;
  19614. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  19615. const column = frameNum.mod( width );
  19616. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  19617. const scale = countNode.reciprocal();
  19618. const uvFrameOffset = vec2( column, row );
  19619. return uvNode.add( uvFrameOffset ).mul( scale );
  19620. }
  19621. }
  19622. /**
  19623. * TSL function for creating a sprite sheet uv node.
  19624. *
  19625. * @function
  19626. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  19627. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  19628. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  19629. * @returns {SpriteSheetUVNode}
  19630. */
  19631. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  19632. /** @module TriplanarTexturesNode **/
  19633. /**
  19634. * Can be used for triplanar texture mapping.
  19635. *
  19636. * ```js
  19637. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  19638. * ```
  19639. *
  19640. * @augments Node
  19641. */
  19642. class TriplanarTexturesNode extends Node {
  19643. static get type() {
  19644. return 'TriplanarTexturesNode';
  19645. }
  19646. /**
  19647. * Constructs a new triplanar textures node.
  19648. *
  19649. * @param {Node} textureXNode - First texture node.
  19650. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19651. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19652. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  19653. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  19654. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  19655. */
  19656. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  19657. super( 'vec4' );
  19658. /**
  19659. * First texture node.
  19660. *
  19661. * @type {Node}
  19662. */
  19663. this.textureXNode = textureXNode;
  19664. /**
  19665. * Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19666. *
  19667. * @type {Node}
  19668. * @default null
  19669. */
  19670. this.textureYNode = textureYNode;
  19671. /**
  19672. * Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19673. *
  19674. * @type {Node}
  19675. * @default null
  19676. */
  19677. this.textureZNode = textureZNode;
  19678. /**
  19679. * The scale node.
  19680. *
  19681. * @type {Node<float>}
  19682. * @default float(1)
  19683. */
  19684. this.scaleNode = scaleNode;
  19685. /**
  19686. * Vertex positions in local space.
  19687. *
  19688. * @type {Node<vec3>}
  19689. * @default positionLocal
  19690. */
  19691. this.positionNode = positionNode;
  19692. /**
  19693. * Normals in local space.
  19694. *
  19695. * @type {Node<vec3>}
  19696. * @default normalLocal
  19697. */
  19698. this.normalNode = normalNode;
  19699. }
  19700. setup() {
  19701. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  19702. // Ref: https://github.com/keijiro/StandardTriplanar
  19703. // Blending factor of triplanar mapping
  19704. let bf = normalNode.abs().normalize();
  19705. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  19706. // Triplanar mapping
  19707. const tx = positionNode.yz.mul( scaleNode );
  19708. const ty = positionNode.zx.mul( scaleNode );
  19709. const tz = positionNode.xy.mul( scaleNode );
  19710. // Base color
  19711. const textureX = textureXNode.value;
  19712. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  19713. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  19714. const cx = texture( textureX, tx ).mul( bf.x );
  19715. const cy = texture( textureY, ty ).mul( bf.y );
  19716. const cz = texture( textureZ, tz ).mul( bf.z );
  19717. return add( cx, cy, cz );
  19718. }
  19719. }
  19720. /**
  19721. * TSL function for creating a triplanar textures node.
  19722. *
  19723. * @function
  19724. * @param {Node} textureXNode - First texture node.
  19725. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19726. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19727. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  19728. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  19729. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  19730. * @returns {TriplanarTexturesNode}
  19731. */
  19732. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  19733. /**
  19734. * TSL function for creating a triplanar textures node.
  19735. *
  19736. * @function
  19737. * @param {Node} textureXNode - First texture node.
  19738. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19739. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19740. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  19741. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  19742. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  19743. * @returns {TriplanarTexturesNode}
  19744. */
  19745. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  19746. /** @module ReflectorNode **/
  19747. const _reflectorPlane = new Plane();
  19748. const _normal = new Vector3();
  19749. const _reflectorWorldPosition = new Vector3();
  19750. const _cameraWorldPosition = new Vector3();
  19751. const _rotationMatrix = new Matrix4();
  19752. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  19753. const clipPlane = new Vector4();
  19754. const _view = new Vector3();
  19755. const _target = new Vector3();
  19756. const _q = new Vector4();
  19757. const _size$2 = new Vector2();
  19758. const _defaultRT = new RenderTarget();
  19759. const _defaultUV = screenUV.flipX();
  19760. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  19761. let _inReflector = false;
  19762. /**
  19763. * This node can be used to implement mirror-like flat reflective surfaces.
  19764. *
  19765. * ```js
  19766. * const groundReflector = reflector();
  19767. * material.colorNode = groundReflector;
  19768. *
  19769. * const plane = new Mesh( geometry, material );
  19770. * plane.add( groundReflector.target );
  19771. * ```
  19772. *
  19773. * @augments module:TextureNode~TextureNode
  19774. */
  19775. class ReflectorNode extends TextureNode {
  19776. static get type() {
  19777. return 'ReflectorNode';
  19778. }
  19779. /**
  19780. * Constructs a new reflector node.
  19781. *
  19782. * @param {Object} [parameters={}] - An object holding configuration parameters.
  19783. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  19784. * @param {Number} [parameters.resolution=1] - The resolution scale.
  19785. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  19786. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  19787. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  19788. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  19789. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  19790. */
  19791. constructor( parameters = {} ) {
  19792. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  19793. /**
  19794. * A reference to the internal reflector base node which holds the actual implementation.
  19795. *
  19796. * @private
  19797. * @type {ReflectorBaseNode?}
  19798. * @default null
  19799. */
  19800. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  19801. /**
  19802. * A reference to the internal depth node.
  19803. *
  19804. * @private
  19805. * @type {Node?}
  19806. * @default null
  19807. */
  19808. this._depthNode = null;
  19809. this.setUpdateMatrix( false );
  19810. }
  19811. /**
  19812. * A reference to the internal reflector node.
  19813. *
  19814. * @type {ReflectorBaseNode}
  19815. */
  19816. get reflector() {
  19817. return this._reflectorBaseNode;
  19818. }
  19819. /**
  19820. * A reference to 3D object the reflector is linked to.
  19821. *
  19822. * @type {Object3D}
  19823. */
  19824. get target() {
  19825. return this._reflectorBaseNode.target;
  19826. }
  19827. /**
  19828. * Returns a node representing the mirror's depth. That can be used
  19829. * to implement more advanced reflection effects like distance attenuation.
  19830. *
  19831. * @return {Node} The depth node.
  19832. */
  19833. getDepthNode() {
  19834. if ( this._depthNode === null ) {
  19835. if ( this._reflectorBaseNode.depth !== true ) {
  19836. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  19837. }
  19838. this._depthNode = nodeObject( new ReflectorNode( {
  19839. defaultTexture: _defaultRT.depthTexture,
  19840. reflector: this._reflectorBaseNode
  19841. } ) );
  19842. }
  19843. return this._depthNode;
  19844. }
  19845. setup( builder ) {
  19846. // ignore if used in post-processing
  19847. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  19848. return super.setup( builder );
  19849. }
  19850. clone() {
  19851. const texture = new this.constructor( this.reflectorNode );
  19852. texture._reflectorBaseNode = this._reflectorBaseNode;
  19853. return texture;
  19854. }
  19855. }
  19856. /**
  19857. * Holds the actual implementation of the reflector.
  19858. *
  19859. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  19860. * in `ReflectorNode`, see #29619.
  19861. *
  19862. * @private
  19863. * @augments Node
  19864. */
  19865. class ReflectorBaseNode extends Node {
  19866. static get type() {
  19867. return 'ReflectorBaseNode';
  19868. }
  19869. /**
  19870. * Constructs a new reflector base node.
  19871. *
  19872. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  19873. * @param {Object} [parameters={}] - An object holding configuration parameters.
  19874. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  19875. * @param {Number} [parameters.resolution=1] - The resolution scale.
  19876. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  19877. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  19878. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  19879. */
  19880. constructor( textureNode, parameters = {} ) {
  19881. super();
  19882. const {
  19883. target = new Object3D(),
  19884. resolution = 1,
  19885. generateMipmaps = false,
  19886. bounces = true,
  19887. depth = false
  19888. } = parameters;
  19889. /**
  19890. * Represents the rendered reflections as a texture node.
  19891. *
  19892. * @type {TextureNode}
  19893. */
  19894. this.textureNode = textureNode;
  19895. /**
  19896. * The 3D object the reflector is linked to.
  19897. *
  19898. * @type {Object3D}
  19899. * @default {new Object3D()}
  19900. */
  19901. this.target = target;
  19902. /**
  19903. * The resolution scale.
  19904. *
  19905. * @type {Number}
  19906. * @default {1}
  19907. */
  19908. this.resolution = resolution;
  19909. /**
  19910. * Whether mipmaps should be generated or not.
  19911. *
  19912. * @type {Boolean}
  19913. * @default {false}
  19914. */
  19915. this.generateMipmaps = generateMipmaps;
  19916. /**
  19917. * Whether reflectors can render other reflector nodes or not.
  19918. *
  19919. * @type {Boolean}
  19920. * @default {true}
  19921. */
  19922. this.bounces = bounces;
  19923. /**
  19924. * Whether depth data should be generated or not.
  19925. *
  19926. * @type {Boolean}
  19927. * @default {false}
  19928. */
  19929. this.depth = depth;
  19930. /**
  19931. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  19932. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  19933. *
  19934. * @type {String}
  19935. * @default 'render'
  19936. */
  19937. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  19938. /**
  19939. * Weak map for managing virtual cameras.
  19940. *
  19941. * @type {WeakMap<Camera, Camera>}
  19942. */
  19943. this.virtualCameras = new WeakMap();
  19944. /**
  19945. * Weak map for managing render targets.
  19946. *
  19947. * @type {WeakMap<Camera, RenderTarget>}
  19948. */
  19949. this.renderTargets = new WeakMap();
  19950. }
  19951. /**
  19952. * Updates the resolution of the internal render target.
  19953. *
  19954. * @private
  19955. * @param {RenderTarget} renderTarget - The render target to resize.
  19956. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  19957. */
  19958. _updateResolution( renderTarget, renderer ) {
  19959. const resolution = this.resolution;
  19960. renderer.getDrawingBufferSize( _size$2 );
  19961. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  19962. }
  19963. setup( builder ) {
  19964. this._updateResolution( _defaultRT, builder.renderer );
  19965. return super.setup( builder );
  19966. }
  19967. /**
  19968. * Returns a virtual camera for the given camera. The virtual camera is used to
  19969. * render the scene from the reflector's view so correct reflections can be produced.
  19970. *
  19971. * @param {Camera} camera - The scene's camera.
  19972. * @return {Camera} The corresponding virtual camera.
  19973. */
  19974. getVirtualCamera( camera ) {
  19975. let virtualCamera = this.virtualCameras.get( camera );
  19976. if ( virtualCamera === undefined ) {
  19977. virtualCamera = camera.clone();
  19978. this.virtualCameras.set( camera, virtualCamera );
  19979. }
  19980. return virtualCamera;
  19981. }
  19982. /**
  19983. * Returns a render target for the given camera. The reflections are rendered
  19984. * into this render target.
  19985. *
  19986. * @param {Camera} camera - The scene's camera.
  19987. * @return {RenderTarget} The render target.
  19988. */
  19989. getRenderTarget( camera ) {
  19990. let renderTarget = this.renderTargets.get( camera );
  19991. if ( renderTarget === undefined ) {
  19992. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  19993. if ( this.generateMipmaps === true ) {
  19994. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  19995. renderTarget.texture.generateMipmaps = true;
  19996. }
  19997. if ( this.depth === true ) {
  19998. renderTarget.depthTexture = new DepthTexture();
  19999. }
  20000. this.renderTargets.set( camera, renderTarget );
  20001. }
  20002. return renderTarget;
  20003. }
  20004. updateBefore( frame ) {
  20005. if ( this.bounces === false && _inReflector ) return false;
  20006. _inReflector = true;
  20007. const { scene, camera, renderer, material } = frame;
  20008. const { target } = this;
  20009. const virtualCamera = this.getVirtualCamera( camera );
  20010. const renderTarget = this.getRenderTarget( virtualCamera );
  20011. renderer.getDrawingBufferSize( _size$2 );
  20012. this._updateResolution( renderTarget, renderer );
  20013. //
  20014. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  20015. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  20016. _rotationMatrix.extractRotation( target.matrixWorld );
  20017. _normal.set( 0, 0, 1 );
  20018. _normal.applyMatrix4( _rotationMatrix );
  20019. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  20020. // Avoid rendering when reflector is facing away
  20021. if ( _view.dot( _normal ) > 0 ) return;
  20022. _view.reflect( _normal ).negate();
  20023. _view.add( _reflectorWorldPosition );
  20024. _rotationMatrix.extractRotation( camera.matrixWorld );
  20025. _lookAtPosition.set( 0, 0, - 1 );
  20026. _lookAtPosition.applyMatrix4( _rotationMatrix );
  20027. _lookAtPosition.add( _cameraWorldPosition );
  20028. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  20029. _target.reflect( _normal ).negate();
  20030. _target.add( _reflectorWorldPosition );
  20031. //
  20032. virtualCamera.coordinateSystem = camera.coordinateSystem;
  20033. virtualCamera.position.copy( _view );
  20034. virtualCamera.up.set( 0, 1, 0 );
  20035. virtualCamera.up.applyMatrix4( _rotationMatrix );
  20036. virtualCamera.up.reflect( _normal );
  20037. virtualCamera.lookAt( _target );
  20038. virtualCamera.near = camera.near;
  20039. virtualCamera.far = camera.far;
  20040. virtualCamera.updateMatrixWorld();
  20041. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  20042. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  20043. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  20044. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  20045. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  20046. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  20047. const projectionMatrix = virtualCamera.projectionMatrix;
  20048. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  20049. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  20050. _q.z = - 1.0;
  20051. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  20052. // Calculate the scaled plane vector
  20053. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  20054. const clipBias = 0;
  20055. // Replacing the third row of the projection matrix
  20056. projectionMatrix.elements[ 2 ] = clipPlane.x;
  20057. projectionMatrix.elements[ 6 ] = clipPlane.y;
  20058. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  20059. projectionMatrix.elements[ 14 ] = clipPlane.w;
  20060. //
  20061. this.textureNode.value = renderTarget.texture;
  20062. if ( this.depth === true ) {
  20063. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  20064. }
  20065. material.visible = false;
  20066. const currentRenderTarget = renderer.getRenderTarget();
  20067. const currentMRT = renderer.getMRT();
  20068. const currentAutoClear = renderer.autoClear;
  20069. renderer.setMRT( null );
  20070. renderer.setRenderTarget( renderTarget );
  20071. renderer.autoClear = true;
  20072. renderer.render( scene, virtualCamera );
  20073. renderer.setMRT( currentMRT );
  20074. renderer.setRenderTarget( currentRenderTarget );
  20075. renderer.autoClear = currentAutoClear;
  20076. material.visible = true;
  20077. _inReflector = false;
  20078. }
  20079. }
  20080. /**
  20081. * TSL function for creating a reflector node.
  20082. *
  20083. * @function
  20084. * @param {Object} [parameters={}] - An object holding configuration parameters.
  20085. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  20086. * @param {Number} [parameters.resolution=1] - The resolution scale.
  20087. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  20088. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  20089. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  20090. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  20091. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  20092. * @returns {ReflectorNode}
  20093. */
  20094. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  20095. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  20096. /**
  20097. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  20098. *
  20099. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  20100. *
  20101. * @private
  20102. * @augments BufferGeometry
  20103. */
  20104. class QuadGeometry extends BufferGeometry {
  20105. /**
  20106. * Constructs a new quad geometry.
  20107. *
  20108. * @param {Boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  20109. */
  20110. constructor( flipY = false ) {
  20111. super();
  20112. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  20113. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  20114. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  20115. }
  20116. }
  20117. const _geometry = /*@__PURE__*/ new QuadGeometry();
  20118. /**
  20119. * This module is a helper for passes which need to render a full
  20120. * screen effect which is quite common in context of post processing.
  20121. *
  20122. * The intended usage is to reuse a single quad mesh for rendering
  20123. * subsequent passes by just reassigning the `material` reference.
  20124. *
  20125. * @augments BufferGeometry
  20126. */
  20127. class QuadMesh extends Mesh {
  20128. /**
  20129. * Constructs a new quad mesh.
  20130. *
  20131. * @param {Material?} [material=null] - The material to render the quad mesh with.
  20132. */
  20133. constructor( material = null ) {
  20134. super( _geometry, material );
  20135. /**
  20136. * The camera to render the quad mesh with.
  20137. *
  20138. * @type {OrthographicCamera}
  20139. * @readonly
  20140. */
  20141. this.camera = _camera;
  20142. /**
  20143. * This flag can be used for type testing.
  20144. *
  20145. * @type {Boolean}
  20146. * @readonly
  20147. * @default true
  20148. */
  20149. this.isQuadMesh = true;
  20150. }
  20151. /**
  20152. * Async version of `render()`.
  20153. *
  20154. * @async
  20155. * @param {Renderer} renderer - The renderer.
  20156. * @return {Promise} A Promise that resolves when the render has been finished.
  20157. */
  20158. async renderAsync( renderer ) {
  20159. return renderer.renderAsync( this, _camera );
  20160. }
  20161. /**
  20162. * Renders the quad mesh
  20163. *
  20164. * @param {Renderer} renderer - The renderer.
  20165. */
  20166. render( renderer ) {
  20167. renderer.render( this, _camera );
  20168. }
  20169. }
  20170. /** @module RTTNode **/
  20171. const _size$1 = /*@__PURE__*/ new Vector2();
  20172. /**
  20173. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  20174. * This module is especially relevant in context of post processing where certain nodes require
  20175. * texture input for their effects. With the helper function `convertToTexture()` which is based
  20176. * on this module, the node system can automatically ensure texture input if required.
  20177. *
  20178. * @augments module:TextureNode~TextureNode
  20179. */
  20180. class RTTNode extends TextureNode {
  20181. static get type() {
  20182. return 'RTTNode';
  20183. }
  20184. /**
  20185. * Constructs a new RTT node.
  20186. *
  20187. * @param {Node} node - The node to render a texture with.
  20188. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  20189. * @param {Number?} [height=null] - The height of the internal render target.
  20190. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  20191. */
  20192. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  20193. const renderTarget = new RenderTarget( width, height, options );
  20194. super( renderTarget.texture, uv() );
  20195. /**
  20196. * The node to render a texture with.
  20197. *
  20198. * @type {Node}
  20199. */
  20200. this.node = node;
  20201. /**
  20202. * The width of the internal render target.
  20203. * If not width is applied, the render target is automatically resized.
  20204. *
  20205. * @type {Number?}
  20206. * @default null
  20207. */
  20208. this.width = width;
  20209. /**
  20210. * The height of the internal render target.
  20211. *
  20212. * @type {Number?}
  20213. * @default null
  20214. */
  20215. this.height = height;
  20216. /**
  20217. * The pixel ratio
  20218. *
  20219. * @type {Number}
  20220. * @default 1
  20221. */
  20222. this.pixelRatio = 1;
  20223. /**
  20224. * The render target
  20225. *
  20226. * @type {RenderTarget}
  20227. */
  20228. this.renderTarget = renderTarget;
  20229. /**
  20230. * Whether the texture requires an update or not.
  20231. *
  20232. * @type {Boolean}
  20233. * @default true
  20234. */
  20235. this.textureNeedsUpdate = true;
  20236. /**
  20237. * Whether the texture should automatically be updated or not.
  20238. *
  20239. * @type {Boolean}
  20240. * @default true
  20241. */
  20242. this.autoUpdate = true;
  20243. /**
  20244. * The node which is used with the quad mesh for RTT.
  20245. *
  20246. * @private
  20247. * @type {Node}
  20248. * @default null
  20249. */
  20250. this._rttNode = null;
  20251. /**
  20252. * The internal quad mesh for RTT.
  20253. *
  20254. * @private
  20255. * @type {QuadMesh}
  20256. */
  20257. this._quadMesh = new QuadMesh( new NodeMaterial() );
  20258. /**
  20259. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  20260. * the texture once per render in its {@link RTTNode#updateBefore} method.
  20261. *
  20262. * @type {String}
  20263. * @default 'render'
  20264. */
  20265. this.updateBeforeType = NodeUpdateType.RENDER;
  20266. }
  20267. /**
  20268. * Whether the internal render target should automatically be resized or not.
  20269. *
  20270. * @type {Boolean}
  20271. * @readonly
  20272. * @default true
  20273. */
  20274. get autoSize() {
  20275. return this.width === null;
  20276. }
  20277. setup( builder ) {
  20278. this._rttNode = this.node.context( builder.getSharedContext() );
  20279. this._quadMesh.material.name = 'RTT';
  20280. this._quadMesh.material.needsUpdate = true;
  20281. return super.setup( builder );
  20282. }
  20283. /**
  20284. * Sets the size of the internal render target
  20285. *
  20286. * @param {Number} width - The width to set.
  20287. * @param {Number} height - The width to set.
  20288. */
  20289. setSize( width, height ) {
  20290. this.width = width;
  20291. this.height = height;
  20292. const effectiveWidth = width * this.pixelRatio;
  20293. const effectiveHeight = height * this.pixelRatio;
  20294. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  20295. this.textureNeedsUpdate = true;
  20296. }
  20297. /**
  20298. * Sets the pixel ratio. This will also resize the render target.
  20299. *
  20300. * @param {Number} pixelRatio - The pixel ratio to set.
  20301. */
  20302. setPixelRatio( pixelRatio ) {
  20303. this.pixelRatio = pixelRatio;
  20304. this.setSize( this.width, this.height );
  20305. }
  20306. updateBefore( { renderer } ) {
  20307. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  20308. this.textureNeedsUpdate = false;
  20309. //
  20310. if ( this.autoSize === true ) {
  20311. this.pixelRatio = renderer.getPixelRatio();
  20312. const size = renderer.getSize( _size$1 );
  20313. this.setSize( size.width, size.height );
  20314. }
  20315. //
  20316. this._quadMesh.material.fragmentNode = this._rttNode;
  20317. //
  20318. const currentRenderTarget = renderer.getRenderTarget();
  20319. renderer.setRenderTarget( this.renderTarget );
  20320. this._quadMesh.render( renderer );
  20321. renderer.setRenderTarget( currentRenderTarget );
  20322. }
  20323. clone() {
  20324. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  20325. newNode.sampler = this.sampler;
  20326. newNode.referenceNode = this;
  20327. return newNode;
  20328. }
  20329. }
  20330. /**
  20331. * TSL function for creating a RTT node.
  20332. *
  20333. * @function
  20334. * @param {Node} node - The node to render a texture with.
  20335. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  20336. * @param {Number?} [height=null] - The height of the internal render target.
  20337. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  20338. * @returns {RTTNode}
  20339. */
  20340. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  20341. /**
  20342. * TSL function for converting nodes to textures nodes.
  20343. *
  20344. * @function
  20345. * @param {Node} node - The node to render a texture with.
  20346. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  20347. * @param {Number?} [height=null] - The height of the internal render target.
  20348. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  20349. * @returns {RTTNode}
  20350. */
  20351. const convertToTexture = ( node, ...params ) => {
  20352. if ( node.isTextureNode ) return node;
  20353. if ( node.isPassNode ) return node.getTextureNode();
  20354. return rtt( node, ...params );
  20355. };
  20356. /** @module PostProcessingUtils **/
  20357. /**
  20358. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  20359. * depth value and the camera's inverse projection matrix.
  20360. *
  20361. * @method
  20362. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  20363. * @param {Node<float>} depth - The fragment's depth value.
  20364. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  20365. * @return {Node<vec3>} The fragments position in view space.
  20366. */
  20367. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  20368. let clipSpacePosition;
  20369. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  20370. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  20371. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  20372. } else {
  20373. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  20374. }
  20375. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  20376. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  20377. } );
  20378. /**
  20379. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  20380. * and the camera's projection matrix
  20381. *
  20382. * @method
  20383. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  20384. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  20385. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  20386. */
  20387. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  20388. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  20389. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  20390. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  20391. } );
  20392. /**
  20393. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  20394. * target is available or if flat surface normals are required.
  20395. *
  20396. * @method
  20397. * @param {Node<vec2>} uv - The texture coordinate.
  20398. * @param {DepthTexture} depthTexture - The depth texture.
  20399. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  20400. * @return {Node<vec3>} The computed normal vector.
  20401. */
  20402. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  20403. const size = textureSize( textureLoad( depthTexture ) );
  20404. const p = ivec2( uv.mul( size ) ).toVar();
  20405. const c0 = textureLoad( depthTexture, p ).toVar();
  20406. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  20407. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  20408. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  20409. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  20410. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  20411. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  20412. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  20413. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  20414. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  20415. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  20416. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  20417. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  20418. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  20419. 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 ) ) );
  20420. 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 ) ) );
  20421. return normalize( cross( dpdx, dpdy ) );
  20422. } );
  20423. /**
  20424. * This special type of instanced buffer attribute is intended for compute shaders.
  20425. * In earlier three.js versions it was only possible to update attribute data
  20426. * on the CPU via JavaScript and then upload the data to the GPU. With the
  20427. * new material system and renderer it is now possible to use compute shaders
  20428. * to compute the data for an attribute more efficiently on the GPU.
  20429. *
  20430. * The idea is to create an instance of this class and provide it as an input
  20431. * to {@link module:StorageBufferNode}.
  20432. *
  20433. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  20434. *
  20435. * @augments InstancedBufferAttribute
  20436. */
  20437. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  20438. /**
  20439. * Constructs a new storage instanced buffer attribute.
  20440. *
  20441. * @param {Number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  20442. * The subsequent parameters are then obsolete.
  20443. * @param {Number} itemSize - The item size.
  20444. * @param {TypedArray.contructor} [typeClass=Float32Array] - A typed array constructor.
  20445. */
  20446. constructor( count, itemSize, typeClass = Float32Array ) {
  20447. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  20448. super( array, itemSize );
  20449. /**
  20450. * This flag can be used for type testing.
  20451. *
  20452. * @type {Boolean}
  20453. * @readonly
  20454. * @default true
  20455. */
  20456. this.isStorageInstancedBufferAttribute = true;
  20457. }
  20458. }
  20459. /**
  20460. * This special type of buffer attribute is intended for compute shaders.
  20461. * In earlier three.js versions it was only possible to update attribute data
  20462. * on the CPU via JavaScript and then upload the data to the GPU. With the
  20463. * new material system and renderer it is now possible to use compute shaders
  20464. * to compute the data for an attribute more efficiently on the GPU.
  20465. *
  20466. * The idea is to create an instance of this class and provide it as an input
  20467. * to {@link module:StorageBufferNode}.
  20468. *
  20469. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  20470. *
  20471. * @augments BufferAttribute
  20472. */
  20473. class StorageBufferAttribute extends BufferAttribute {
  20474. /**
  20475. * Constructs a new storage buffer attribute.
  20476. *
  20477. * @param {Number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  20478. * The subsequent parameters are then obsolete.
  20479. * @param {Number} itemSize - The item size.
  20480. * @param {TypedArray.contructor} [typeClass=Float32Array] - A typed array constructor.
  20481. */
  20482. constructor( count, itemSize, typeClass = Float32Array ) {
  20483. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  20484. super( array, itemSize );
  20485. /**
  20486. * This flag can be used for type testing.
  20487. *
  20488. * @type {Boolean}
  20489. * @readonly
  20490. * @default true
  20491. */
  20492. this.isStorageBufferAttribute = true;
  20493. }
  20494. }
  20495. /** @module StorageArrayElementNode **/
  20496. /**
  20497. * This class enables element access on instances of {@link StorageBufferNode}.
  20498. * In most cases, it is indirectly used when accessing elements with the
  20499. * {@link StorageBufferNode#element} method.
  20500. *
  20501. * ```js
  20502. * const position = positionStorage.element( instanceIndex );
  20503. * ```
  20504. *
  20505. * @augments ArrayElementNode
  20506. */
  20507. class StorageArrayElementNode extends ArrayElementNode {
  20508. static get type() {
  20509. return 'StorageArrayElementNode';
  20510. }
  20511. /**
  20512. * Constructs storage buffer element node.
  20513. *
  20514. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  20515. * @param {Node} indexNode - The index node that defines the element access.
  20516. */
  20517. constructor( storageBufferNode, indexNode ) {
  20518. super( storageBufferNode, indexNode );
  20519. /**
  20520. * This flag can be used for type testing.
  20521. *
  20522. * @type {Boolean}
  20523. * @readonly
  20524. * @default true
  20525. */
  20526. this.isStorageArrayElementNode = true;
  20527. }
  20528. /**
  20529. * The storage buffer node.
  20530. *
  20531. * @param {Node} value
  20532. * @type {StorageBufferNode}
  20533. */
  20534. set storageBufferNode( value ) {
  20535. this.node = value;
  20536. }
  20537. get storageBufferNode() {
  20538. return this.node;
  20539. }
  20540. setup( builder ) {
  20541. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  20542. if ( this.node.isPBO === true ) {
  20543. builder.setupPBO( this.node );
  20544. }
  20545. }
  20546. return super.setup( builder );
  20547. }
  20548. generate( builder, output ) {
  20549. let snippet;
  20550. const isAssignContext = builder.context.assign;
  20551. //
  20552. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  20553. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  20554. snippet = builder.generatePBO( this );
  20555. } else {
  20556. snippet = this.node.build( builder );
  20557. }
  20558. } else {
  20559. snippet = super.generate( builder );
  20560. }
  20561. if ( isAssignContext !== true ) {
  20562. const type = this.getNodeType( builder );
  20563. snippet = builder.format( snippet, type, output );
  20564. }
  20565. return snippet;
  20566. }
  20567. }
  20568. /**
  20569. * TSL function for creating a storage element node.
  20570. *
  20571. * @function
  20572. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  20573. * @param {Node} indexNode - The index node that defines the element access.
  20574. * @returns {StorageArrayElementNode}
  20575. */
  20576. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  20577. /** @module StorageBufferNode **/
  20578. /**
  20579. * This node is used in context of compute shaders and allows to define a
  20580. * storage buffer for data. A typical workflow is to create instances of
  20581. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  20582. * setup up a compute shader that writes into the buffers and then convert
  20583. * the storage buffers to attribute nodes for rendering.
  20584. *
  20585. * ```js
  20586. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  20587. *
  20588. * const computeInit = Fn( () => { // the compute shader
  20589. *
  20590. * const position = positionBuffer.element( instanceIndex );
  20591. *
  20592. * // compute position data
  20593. *
  20594. * position.x = 1;
  20595. * position.y = 1;
  20596. * position.z = 1;
  20597. *
  20598. * } )().compute( particleCount );
  20599. *
  20600. * const particleMaterial = new THREE.SpriteNodeMaterial();
  20601. * particleMaterial.positionNode = positionBuffer.toAttribute();
  20602. *
  20603. * renderer.computeAsync( computeInit );
  20604. *
  20605. * ```
  20606. *
  20607. * @augments BufferNode
  20608. */
  20609. class StorageBufferNode extends BufferNode {
  20610. static get type() {
  20611. return 'StorageBufferNode';
  20612. }
  20613. /**
  20614. * Constructs a new storage buffer node.
  20615. *
  20616. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  20617. * @param {String?} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  20618. * @param {Number} [bufferCount=0] - The buffer count.
  20619. */
  20620. constructor( value, bufferType = null, bufferCount = 0 ) {
  20621. if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  20622. bufferType = getTypeFromLength( value.itemSize );
  20623. bufferCount = value.count;
  20624. }
  20625. super( value, bufferType, bufferCount );
  20626. /**
  20627. * This flag can be used for type testing.
  20628. *
  20629. * @type {Boolean}
  20630. * @readonly
  20631. * @default true
  20632. */
  20633. this.isStorageBufferNode = true;
  20634. /**
  20635. * The access type of the texture node.
  20636. *
  20637. * @type {String}
  20638. * @default 'readWrite'
  20639. */
  20640. this.access = NodeAccess.READ_WRITE;
  20641. /**
  20642. * Whether the node is atomic or not.
  20643. *
  20644. * @type {Boolean}
  20645. * @default false
  20646. */
  20647. this.isAtomic = false;
  20648. /**
  20649. * Whether the node represents a PBO or not.
  20650. * Only relevant for WebGL.
  20651. *
  20652. * @type {Boolean}
  20653. * @default false
  20654. */
  20655. this.isPBO = false;
  20656. /**
  20657. * A reference to the internal buffer attribute node.
  20658. *
  20659. * @type {BufferAttributeNode?}
  20660. * @default null
  20661. */
  20662. this._attribute = null;
  20663. /**
  20664. * A reference to the internal varying node.
  20665. *
  20666. * @type {VaryingNode?}
  20667. * @default null
  20668. */
  20669. this._varying = null;
  20670. /**
  20671. * `StorageBufferNode` sets this property to `true` by default.
  20672. *
  20673. * @type {Boolean}
  20674. * @default true
  20675. */
  20676. this.global = true;
  20677. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  20678. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  20679. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  20680. else value.isStorageBufferAttribute = true;
  20681. }
  20682. }
  20683. /**
  20684. * This method is overwritten since the buffer data might be shared
  20685. * and thus the hash should be shared as well.
  20686. *
  20687. * @param {NodeBuilder} builder - The current node builder.
  20688. * @return {String} The hash.
  20689. */
  20690. getHash( builder ) {
  20691. if ( this.bufferCount === 0 ) {
  20692. let bufferData = builder.globalCache.getData( this.value );
  20693. if ( bufferData === undefined ) {
  20694. bufferData = {
  20695. node: this
  20696. };
  20697. builder.globalCache.setData( this.value, bufferData );
  20698. }
  20699. return bufferData.node.uuid;
  20700. }
  20701. return this.uuid;
  20702. }
  20703. /**
  20704. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  20705. *
  20706. * @param {NodeBuilder} builder - The current node builder.
  20707. * @return {String} The input type.
  20708. */
  20709. getInputType( /*builder*/ ) {
  20710. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  20711. }
  20712. /**
  20713. * Enables element access with the given index node.
  20714. *
  20715. * @param {IndexNode} indexNode - The index node.
  20716. * @return {StorageArrayElementNode} A node representing the element access.
  20717. */
  20718. element( indexNode ) {
  20719. return storageElement( this, indexNode );
  20720. }
  20721. /**
  20722. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  20723. *
  20724. * @param {Boolean} value - The value so set.
  20725. * @return {StorageBufferNode} A reference to this node.
  20726. */
  20727. setPBO( value ) {
  20728. this.isPBO = value;
  20729. return this;
  20730. }
  20731. /**
  20732. * Returns the `isPBO` value.
  20733. *
  20734. * @return {Boolean} Whether the node represents a PBO or not.
  20735. */
  20736. getPBO() {
  20737. return this.isPBO;
  20738. }
  20739. /**
  20740. * Defines the node access.
  20741. *
  20742. * @param {String} value - The node access.
  20743. * @return {StorageBufferNode} A reference to this node.
  20744. */
  20745. setAccess( value ) {
  20746. this.access = value;
  20747. return this;
  20748. }
  20749. /**
  20750. * Convenience method for configuring a read-only node access.
  20751. *
  20752. * @return {StorageBufferNode} A reference to this node.
  20753. */
  20754. toReadOnly() {
  20755. return this.setAccess( NodeAccess.READ_ONLY );
  20756. }
  20757. /**
  20758. * Defines whether the node is atomic or not.
  20759. *
  20760. * @param {Boolean} value - The atomic flag.
  20761. * @return {StorageBufferNode} A reference to this node.
  20762. */
  20763. setAtomic( value ) {
  20764. this.isAtomic = value;
  20765. return this;
  20766. }
  20767. /**
  20768. * Convenience method for making this node atomic.
  20769. *
  20770. * @return {StorageBufferNode} A reference to this node.
  20771. */
  20772. toAtomic() {
  20773. return this.setAtomic( true );
  20774. }
  20775. /**
  20776. * Returns attribute data for this storage buffer node.
  20777. *
  20778. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  20779. */
  20780. getAttributeData() {
  20781. if ( this._attribute === null ) {
  20782. this._attribute = bufferAttribute( this.value );
  20783. this._varying = varying( this._attribute );
  20784. }
  20785. return {
  20786. attribute: this._attribute,
  20787. varying: this._varying
  20788. };
  20789. }
  20790. /**
  20791. * This method is overwritten since the node type from the availability of storage buffers
  20792. * and the attribute data.
  20793. *
  20794. * @param {NodeBuilder} builder - The current node builder.
  20795. * @return {String} The node type.
  20796. */
  20797. getNodeType( builder ) {
  20798. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  20799. return super.getNodeType( builder );
  20800. }
  20801. const { attribute } = this.getAttributeData();
  20802. return attribute.getNodeType( builder );
  20803. }
  20804. /**
  20805. * Generates the code snippet of the storage buffer node.
  20806. *
  20807. * @param {NodeBuilder} builder - The current node builder.
  20808. * @return {String} The generated code snippet.
  20809. */
  20810. generate( builder ) {
  20811. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  20812. return super.generate( builder );
  20813. }
  20814. const { attribute, varying } = this.getAttributeData();
  20815. const output = varying.build( builder );
  20816. builder.registerTransform( output, attribute );
  20817. return output;
  20818. }
  20819. }
  20820. /**
  20821. * TSL function for creating a storage buffer node.
  20822. *
  20823. * @function
  20824. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  20825. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  20826. * @param {Number} [count=0] - The buffer count.
  20827. * @returns {StorageBufferNode}
  20828. */
  20829. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  20830. const storageObject = ( value, type, count ) => { // @deprecated, r171
  20831. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  20832. return storage( value, type, count ).setPBO( true );
  20833. };
  20834. /** @module Arrays **/
  20835. /**
  20836. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  20837. *
  20838. * @function
  20839. * @param {Number} count - The data count.
  20840. * @param {String} [type='float'] - The data type.
  20841. * @returns {StorageBufferNode}
  20842. */
  20843. const attributeArray = ( count, type = 'float' ) => {
  20844. const itemSize = getLengthFromType( type );
  20845. const typedArray = getTypedArrayFromType( type );
  20846. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  20847. const node = storage( buffer, type, count );
  20848. return node;
  20849. };
  20850. /**
  20851. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  20852. *
  20853. * @function
  20854. * @param {Number} count - The data count.
  20855. * @param {String} [type='float'] - The data type.
  20856. * @returns {StorageBufferNode}
  20857. */
  20858. const instancedArray = ( count, type = 'float' ) => {
  20859. const itemSize = getLengthFromType( type );
  20860. const typedArray = getTypedArrayFromType( type );
  20861. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  20862. const node = storage( buffer, type, count );
  20863. return node;
  20864. };
  20865. /** @module VertexColorNode **/
  20866. /**
  20867. * An attribute node for representing vertex colors.
  20868. *
  20869. * @augments module:AttributeNode~AttributeNode
  20870. */
  20871. class VertexColorNode extends AttributeNode {
  20872. static get type() {
  20873. return 'VertexColorNode';
  20874. }
  20875. /**
  20876. * Constructs a new vertex color node.
  20877. *
  20878. * @param {Number} [index=0] - The attribute index.
  20879. */
  20880. constructor( index = 0 ) {
  20881. super( null, 'vec4' );
  20882. /**
  20883. * This flag can be used for type testing.
  20884. *
  20885. * @type {Boolean}
  20886. * @readonly
  20887. * @default true
  20888. */
  20889. this.isVertexColorNode = true;
  20890. /**
  20891. * The attribute index to enable more than one sets of vertex colors.
  20892. *
  20893. * @type {Number}
  20894. * @default 0
  20895. */
  20896. this.index = index;
  20897. }
  20898. /**
  20899. * Overwrites the default implementation by honoring the attribute index.
  20900. *
  20901. * @param {NodeBuilder} builder - The current node builder.
  20902. * @return {String} The attribute name.
  20903. */
  20904. getAttributeName( /*builder*/ ) {
  20905. const index = this.index;
  20906. return 'color' + ( index > 0 ? index : '' );
  20907. }
  20908. generate( builder ) {
  20909. const attributeName = this.getAttributeName( builder );
  20910. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  20911. let result;
  20912. if ( geometryAttribute === true ) {
  20913. result = super.generate( builder );
  20914. } else {
  20915. // Vertex color fallback should be white
  20916. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  20917. }
  20918. return result;
  20919. }
  20920. serialize( data ) {
  20921. super.serialize( data );
  20922. data.index = this.index;
  20923. }
  20924. deserialize( data ) {
  20925. super.deserialize( data );
  20926. this.index = data.index;
  20927. }
  20928. }
  20929. /**
  20930. * TSL function for creating a reference node.
  20931. *
  20932. * @function
  20933. * @param {Number} index - The attribute index.
  20934. * @returns {VertexColorNode}
  20935. */
  20936. const vertexColor = ( index ) => nodeObject( new VertexColorNode( index ) );
  20937. /** @module PointUVNode **/
  20938. /**
  20939. * A node for representing the uv coordinates of points.
  20940. *
  20941. * Can only be used with a WebGL backend. In WebGPU, point
  20942. * primitives always have the size of one pixel and can thus
  20943. * can't be used as sprite-like objects that display textures.
  20944. *
  20945. * @augments Node
  20946. */
  20947. class PointUVNode extends Node {
  20948. static get type() {
  20949. return 'PointUVNode';
  20950. }
  20951. /**
  20952. * Constructs a new point uv node.
  20953. */
  20954. constructor() {
  20955. super( 'vec2' );
  20956. /**
  20957. * This flag can be used for type testing.
  20958. *
  20959. * @type {Boolean}
  20960. * @readonly
  20961. * @default true
  20962. */
  20963. this.isPointUVNode = true;
  20964. }
  20965. generate( /*builder*/ ) {
  20966. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  20967. }
  20968. }
  20969. /**
  20970. * TSL object that represents the uv coordinates of points.
  20971. *
  20972. * @type {PointUVNode}
  20973. */
  20974. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  20975. const _e1 = /*@__PURE__*/ new Euler();
  20976. const _m1 = /*@__PURE__*/ new Matrix4();
  20977. /** @module SceneNode **/
  20978. /**
  20979. * This module allows access to a collection of scene properties. The following predefined TSL objects
  20980. * are available for easier use:
  20981. *
  20982. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  20983. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  20984. * - `backgroundRotation`: A node that represents the scene's background rotation.
  20985. *
  20986. * @augments Node
  20987. */
  20988. class SceneNode extends Node {
  20989. static get type() {
  20990. return 'SceneNode';
  20991. }
  20992. /**
  20993. * Constructs a new scene node.
  20994. *
  20995. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  20996. * @param {Scene?} [scene=null] - A reference to the scene.
  20997. */
  20998. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  20999. super();
  21000. /**
  21001. * The scope defines the type of scene property that is accessed.
  21002. *
  21003. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  21004. */
  21005. this.scope = scope;
  21006. /**
  21007. * A reference to the scene that is going to be accessed.
  21008. *
  21009. * @type {Scene?}
  21010. * @default null
  21011. */
  21012. this.scene = scene;
  21013. }
  21014. /**
  21015. * Depending on the scope, the method returns a different type of node that represents
  21016. * the respective scene property.
  21017. *
  21018. * @param {NodeBuilder} builder - The current node builder.
  21019. * @return {Node} The output node.
  21020. */
  21021. setup( builder ) {
  21022. const scope = this.scope;
  21023. const scene = this.scene !== null ? this.scene : builder.scene;
  21024. let output;
  21025. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  21026. output = reference( 'backgroundBlurriness', 'float', scene );
  21027. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  21028. output = reference( 'backgroundIntensity', 'float', scene );
  21029. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  21030. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  21031. const background = scene.background;
  21032. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  21033. _e1.copy( scene.backgroundRotation );
  21034. // accommodate left-handed frame
  21035. _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1;
  21036. _m1.makeRotationFromEuler( _e1 );
  21037. } else {
  21038. _m1.identity();
  21039. }
  21040. return _m1;
  21041. } );
  21042. } else {
  21043. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  21044. }
  21045. return output;
  21046. }
  21047. }
  21048. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  21049. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  21050. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  21051. /**
  21052. * TSL object that represents the scene's background blurriness.
  21053. *
  21054. * @type {SceneNode}
  21055. */
  21056. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  21057. /**
  21058. * TSL object that represents the scene's background intensity.
  21059. *
  21060. * @type {SceneNode}
  21061. */
  21062. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  21063. /**
  21064. * TSL object that represents the scene's background rotation.
  21065. *
  21066. * @type {SceneNode}
  21067. */
  21068. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  21069. /** @module StorageTextureNode **/
  21070. /**
  21071. * This special version of a texture node can be used to
  21072. * write data into a storage texture with a compute shader.
  21073. *
  21074. * ```js
  21075. * const storageTexture = new THREE.StorageTexture( width, height );
  21076. *
  21077. * const computeTexture = Fn( ( { storageTexture } ) => {
  21078. *
  21079. * const posX = instanceIndex.modInt( width );
  21080. * const posY = instanceIndex.div( width );
  21081. * const indexUV = uvec2( posX, posY );
  21082. *
  21083. * // generate RGB values
  21084. *
  21085. * const r = 1;
  21086. * const g = 1;
  21087. * const b = 1;
  21088. *
  21089. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  21090. *
  21091. * } );
  21092. *
  21093. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  21094. * renderer.computeAsync( computeNode );
  21095. * ```
  21096. *
  21097. * This node can only be used with a WebGPU backend.
  21098. *
  21099. * @augments module:TextureNode~TextureNode
  21100. */
  21101. class StorageTextureNode extends TextureNode {
  21102. static get type() {
  21103. return 'StorageTextureNode';
  21104. }
  21105. /**
  21106. * Constructs a new storage texture node.
  21107. *
  21108. * @param {StorageTexture} value - The storage texture.
  21109. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21110. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  21111. */
  21112. constructor( value, uvNode, storeNode = null ) {
  21113. super( value, uvNode );
  21114. /**
  21115. * The value node that should be stored in the texture.
  21116. *
  21117. * @type {Node?}
  21118. * @default null
  21119. */
  21120. this.storeNode = storeNode;
  21121. /**
  21122. * This flag can be used for type testing.
  21123. *
  21124. * @type {Boolean}
  21125. * @readonly
  21126. * @default true
  21127. */
  21128. this.isStorageTextureNode = true;
  21129. /**
  21130. * The access type of the texture node.
  21131. *
  21132. * @type {String}
  21133. * @default 'writeOnly'
  21134. */
  21135. this.access = NodeAccess.WRITE_ONLY;
  21136. }
  21137. /**
  21138. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  21139. *
  21140. * @param {NodeBuilder} builder - The current node builder.
  21141. * @return {String} The input type.
  21142. */
  21143. getInputType( /*builder*/ ) {
  21144. return 'storageTexture';
  21145. }
  21146. setup( builder ) {
  21147. super.setup( builder );
  21148. const properties = builder.getNodeProperties( this );
  21149. properties.storeNode = this.storeNode;
  21150. }
  21151. /**
  21152. * Defines the node access.
  21153. *
  21154. * @param {String} value - The node access.
  21155. * @return {StorageTextureNode} A reference to this node.
  21156. */
  21157. setAccess( value ) {
  21158. this.access = value;
  21159. return this;
  21160. }
  21161. /**
  21162. * Generates the code snippet of the stroge node. If no `storeNode`
  21163. * is defined, the texture node is generated as normal texture.
  21164. *
  21165. * @param {NodeBuilder} builder - The current node builder.
  21166. * @param {String} output - The current output.
  21167. * @return {String} The generated code snippet.
  21168. */
  21169. generate( builder, output ) {
  21170. let snippet;
  21171. if ( this.storeNode !== null ) {
  21172. snippet = this.generateStore( builder );
  21173. } else {
  21174. snippet = super.generate( builder, output );
  21175. }
  21176. return snippet;
  21177. }
  21178. /**
  21179. * Convenience method for configuring a read/write node access.
  21180. *
  21181. * @return {StorageTextureNode} A reference to this node.
  21182. */
  21183. toReadWrite() {
  21184. return this.setAccess( NodeAccess.READ_WRITE );
  21185. }
  21186. /**
  21187. * Convenience method for configuring a read-only node access.
  21188. *
  21189. * @return {StorageTextureNode} A reference to this node.
  21190. */
  21191. toReadOnly() {
  21192. return this.setAccess( NodeAccess.READ_ONLY );
  21193. }
  21194. /**
  21195. * Convenience method for configuring a write-only node access.
  21196. *
  21197. * @return {StorageTextureNode} A reference to this node.
  21198. */
  21199. toWriteOnly() {
  21200. return this.setAccess( NodeAccess.WRITE_ONLY );
  21201. }
  21202. /**
  21203. * Generates the code snippet of the storage texture node.
  21204. *
  21205. * @param {NodeBuilder} builder - The current node builder.
  21206. */
  21207. generateStore( builder ) {
  21208. const properties = builder.getNodeProperties( this );
  21209. const { uvNode, storeNode } = properties;
  21210. const textureProperty = super.generate( builder, 'property' );
  21211. const uvSnippet = uvNode.build( builder, 'uvec2' );
  21212. const storeSnippet = storeNode.build( builder, 'vec4' );
  21213. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  21214. builder.addLineFlowCode( snippet, this );
  21215. }
  21216. }
  21217. /**
  21218. * TSL function for creating a storage texture node.
  21219. *
  21220. * @function
  21221. * @param {StorageTexture} value - The storage texture.
  21222. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21223. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  21224. * @returns {StorageTextureNode}
  21225. */
  21226. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  21227. /**
  21228. * TODO: Explain difference to `storageTexture()`.
  21229. *
  21230. * @function
  21231. * @param {StorageTexture} value - The storage texture.
  21232. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21233. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  21234. * @returns {StorageTextureNode}
  21235. */
  21236. const textureStore = ( value, uvNode, storeNode ) => {
  21237. const node = storageTexture( value, uvNode, storeNode );
  21238. if ( storeNode !== null ) node.append();
  21239. return node;
  21240. };
  21241. /** @module UserDataNode **/
  21242. /**
  21243. * A special type of reference node that allows to link values in
  21244. * `userData` fields to node objects.
  21245. * ```js
  21246. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  21247. *
  21248. * const material = new THREE.SpriteNodeMaterial();
  21249. * material.rotationNode = userData( 'rotation', 'float' );
  21250. * ```
  21251. * Since `UserDataNode` is extended from {@link module:ReferenceNode~ReferenceNode}, the node value
  21252. * will automatically be updated when the `rotation` user data field changes.
  21253. *
  21254. * @augments module:ReferenceNode~ReferenceNode
  21255. */
  21256. class UserDataNode extends ReferenceNode {
  21257. static get type() {
  21258. return 'UserDataNode';
  21259. }
  21260. /**
  21261. * Constructs a new user data node.
  21262. *
  21263. * @param {String} property - The property name that should be referenced by the node.
  21264. * @param {String} inputType - The node data type of the reference.
  21265. * @param {Object?} [userData=null] - A reference to the `userData` object. If not provided, the `userData` property of the 3D object that uses the node material is evaluated.
  21266. */
  21267. constructor( property, inputType, userData = null ) {
  21268. super( property, inputType, userData );
  21269. /**
  21270. * A reference to the `userData` object. If not provided, the `userData`
  21271. * property of the 3D object that uses the node material is evaluated.
  21272. *
  21273. * @type {Object?}
  21274. * @default null
  21275. */
  21276. this.userData = userData;
  21277. }
  21278. /**
  21279. * Overwritten to make sure {@link module:ReferenceNode~ReferenceNode#reference} points to the correct
  21280. * `userData` field.
  21281. *
  21282. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  21283. * @return {Object} A reference to the `userData` field.
  21284. */
  21285. updateReference( state ) {
  21286. this.reference = this.userData !== null ? this.userData : state.object.userData;
  21287. return this.reference;
  21288. }
  21289. }
  21290. /**
  21291. * TSL function for creating a user data node.
  21292. *
  21293. * @function
  21294. * @param {String} name - The property name that should be referenced by the node.
  21295. * @param {String} inputType - The node data type of the reference.
  21296. * @param {Object?} userData - A reference to the `userData` object. If not provided, the `userData` property of the 3D object that uses the node material is evaluated.
  21297. * @returns {UserDataNode}
  21298. */
  21299. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  21300. const _objectData = new WeakMap();
  21301. /** @module VelocityNode **/
  21302. /**
  21303. * A node for representing motion or velocity vectors. Foundation
  21304. * for advanced post processing effects like motion blur or TRAA.
  21305. *
  21306. * The node keeps track of the model, view and projection matrices
  21307. * of the previous frame and uses them to compute offsets in NDC space.
  21308. * These offsets represent the final velocity.
  21309. *
  21310. * @augments TempNode
  21311. */
  21312. class VelocityNode extends TempNode {
  21313. static get type() {
  21314. return 'VelocityNode';
  21315. }
  21316. /**
  21317. * Constructs a new vertex color node.
  21318. *
  21319. * @param {Number} [index=0] - The attribute index.
  21320. */
  21321. constructor() {
  21322. super( 'vec2' );
  21323. /**
  21324. * The current projection matrix.
  21325. *
  21326. * @type {Matrix4?}
  21327. * @default null
  21328. */
  21329. this.projectionMatrix = null;
  21330. /**
  21331. * Overwritten since velocity nodes are updated per object.
  21332. *
  21333. * @type {String}
  21334. * @default 'object'
  21335. */
  21336. this.updateType = NodeUpdateType.OBJECT;
  21337. /**
  21338. * Overwritten since velocity nodes save data after the update.
  21339. *
  21340. * @type {String}
  21341. * @default 'object'
  21342. */
  21343. this.updateAfterType = NodeUpdateType.OBJECT;
  21344. /**
  21345. * Uniform node representing the previous model matrix in world space.
  21346. *
  21347. * @type {UniformNode<mat4>}
  21348. * @default null
  21349. */
  21350. this.previousModelWorldMatrix = uniform( new Matrix4() );
  21351. /**
  21352. * Uniform node representing the previous projection matrix.
  21353. *
  21354. * @type {UniformNode<mat4>}
  21355. * @default null
  21356. */
  21357. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  21358. /**
  21359. * Uniform node representing the previous view matrix.
  21360. *
  21361. * @type {UniformNode<mat4>}
  21362. * @default null
  21363. */
  21364. this.previousCameraViewMatrix = uniform( new Matrix4() );
  21365. }
  21366. /**
  21367. * Sets the given projection matrix.
  21368. *
  21369. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  21370. */
  21371. setProjectionMatrix( projectionMatrix ) {
  21372. this.projectionMatrix = projectionMatrix;
  21373. }
  21374. /**
  21375. * Updates velocity specific uniforms.
  21376. *
  21377. * @param {NodeFrame} frame - A reference to the current node frame.
  21378. */
  21379. update( { frameId, camera, object } ) {
  21380. const previousModelMatrix = getPreviousMatrix( object );
  21381. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  21382. //
  21383. const cameraData = getData( camera );
  21384. if ( cameraData.frameId !== frameId ) {
  21385. cameraData.frameId = frameId;
  21386. if ( cameraData.previousProjectionMatrix === undefined ) {
  21387. cameraData.previousProjectionMatrix = new Matrix4();
  21388. cameraData.previousCameraViewMatrix = new Matrix4();
  21389. cameraData.currentProjectionMatrix = new Matrix4();
  21390. cameraData.currentCameraViewMatrix = new Matrix4();
  21391. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  21392. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  21393. } else {
  21394. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  21395. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  21396. }
  21397. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  21398. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  21399. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  21400. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  21401. }
  21402. }
  21403. /**
  21404. * Overwritten to updated velocity specific uniforms.
  21405. *
  21406. * @param {NodeFrame} frame - A reference to the current node frame.
  21407. */
  21408. updateAfter( { object } ) {
  21409. getPreviousMatrix( object ).copy( object.matrixWorld );
  21410. }
  21411. /**
  21412. * Implements the velocity computation based on the previous and current vertex data.
  21413. *
  21414. * @param {NodeBuilder} builder - A reference to the current node builder.
  21415. * @return {Node<vec2>} The motion vector.
  21416. */
  21417. setup( /*builder*/ ) {
  21418. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  21419. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  21420. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  21421. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  21422. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  21423. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  21424. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  21425. return velocity;
  21426. }
  21427. }
  21428. function getData( object ) {
  21429. let objectData = _objectData.get( object );
  21430. if ( objectData === undefined ) {
  21431. objectData = {};
  21432. _objectData.set( object, objectData );
  21433. }
  21434. return objectData;
  21435. }
  21436. function getPreviousMatrix( object, index = 0 ) {
  21437. const objectData = getData( object );
  21438. let matrix = objectData[ index ];
  21439. if ( matrix === undefined ) {
  21440. objectData[ index ] = matrix = new Matrix4();
  21441. }
  21442. return matrix;
  21443. }
  21444. /**
  21445. * TSL object that represents the velocity of a render pass.
  21446. *
  21447. * @type {VelocityNode}
  21448. */
  21449. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  21450. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21451. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  21452. } ).setLayout( {
  21453. name: 'blendBurn',
  21454. type: 'vec3',
  21455. inputs: [
  21456. { name: 'base', type: 'vec3' },
  21457. { name: 'blend', type: 'vec3' }
  21458. ]
  21459. } );
  21460. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21461. return min$1( base.div( blend.oneMinus() ), 1.0 );
  21462. } ).setLayout( {
  21463. name: 'blendDodge',
  21464. type: 'vec3',
  21465. inputs: [
  21466. { name: 'base', type: 'vec3' },
  21467. { name: 'blend', type: 'vec3' }
  21468. ]
  21469. } );
  21470. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21471. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  21472. } ).setLayout( {
  21473. name: 'blendScreen',
  21474. type: 'vec3',
  21475. inputs: [
  21476. { name: 'base', type: 'vec3' },
  21477. { name: 'blend', type: 'vec3' }
  21478. ]
  21479. } );
  21480. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21481. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  21482. } ).setLayout( {
  21483. name: 'blendOverlay',
  21484. type: 'vec3',
  21485. inputs: [
  21486. { name: 'base', type: 'vec3' },
  21487. { name: 'blend', type: 'vec3' }
  21488. ]
  21489. } );
  21490. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21491. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  21492. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  21493. } ).setLayout( {
  21494. name: 'blendColor',
  21495. type: 'vec4',
  21496. inputs: [
  21497. { name: 'base', type: 'vec4' },
  21498. { name: 'blend', type: 'vec4' }
  21499. ]
  21500. } );
  21501. // deprecated
  21502. const burn = ( ...params ) => { // @deprecated, r171
  21503. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  21504. return blendBurn( params );
  21505. };
  21506. const dodge = ( ...params ) => { // @deprecated, r171
  21507. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  21508. return blendDodge( params );
  21509. };
  21510. const screen = ( ...params ) => { // @deprecated, r171
  21511. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  21512. return blendScreen( params );
  21513. };
  21514. const overlay = ( ...params ) => { // @deprecated, r171
  21515. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  21516. return blendOverlay( params );
  21517. };
  21518. /** @module ColorAdjustment **/
  21519. /**
  21520. * Computes a grayscale value for the given RGB color value.
  21521. *
  21522. * @method
  21523. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  21524. * @return {Node<vec3>} The grayscale color.
  21525. */
  21526. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  21527. return luminance( color.rgb );
  21528. } );
  21529. /**
  21530. * Super-saturates or desaturates the given RGB color.
  21531. *
  21532. * @method
  21533. * @param {Node<vec3>} color - The input color.
  21534. * @param {Node<float>} [adjustment=1] - Specifies the amount of the conversion. A value under `1` desaturates the color, a value over `1` super-saturates it.
  21535. * @return {Node<vec3>} The saturated color.
  21536. */
  21537. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  21538. return adjustment.mix( luminance( color.rgb ), color.rgb );
  21539. } );
  21540. /**
  21541. * Selectively enhance the intensity of less saturated RGB colors. Can result
  21542. * in a more natural and visually appealing image with enhanced color depth
  21543. * compared to {@link ColorAdjustment#saturation}.
  21544. *
  21545. * @method
  21546. * @param {Node<vec3>} color - The input color.
  21547. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  21548. * @return {Node<vec3>} The updated color.
  21549. */
  21550. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  21551. const average = add( color.r, color.g, color.b ).div( 3.0 );
  21552. const mx = color.r.max( color.g.max( color.b ) );
  21553. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  21554. return mix( color.rgb, mx, amt );
  21555. } );
  21556. /**
  21557. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  21558. *
  21559. * @method
  21560. * @param {Node<vec3>} color - The input color.
  21561. * @param {Node<float>} [adjustment=1] - Defines the degree of hue rotation in radians. A positive value rotates the hue clockwise, while a negative value rotates it counterclockwise.
  21562. * @return {Node<vec3>} The updated color.
  21563. */
  21564. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  21565. const k = vec3( 0.57735, 0.57735, 0.57735 );
  21566. const cosAngle = adjustment.cos();
  21567. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  21568. } );
  21569. /**
  21570. * Computes the luminance for the given RGB color value.
  21571. *
  21572. * @method
  21573. * @param {Node<vec3>} color - The color value to compute the luminance for.
  21574. * @param {Node<vec3>?} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  21575. * @return {Node<vec3>} The luminance.
  21576. */
  21577. const luminance = (
  21578. color,
  21579. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  21580. ) => dot( color, luminanceCoefficients );
  21581. /**
  21582. * Color Decision List (CDL) v1.2
  21583. *
  21584. * Compact representation of color grading information, defined by slope, offset, power, and
  21585. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  21586. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  21587. *
  21588. * @method
  21589. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  21590. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  21591. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  21592. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  21593. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  21594. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  21595. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  21596. *
  21597. * References:
  21598. * - ASC CDL v1.2
  21599. * - {@link https://blender.stackexchange.com/a/55239/43930}
  21600. * - {@link https://docs.acescentral.com/specifications/acescc/}
  21601. */
  21602. const cdl = /*@__PURE__*/ Fn( ( [
  21603. color,
  21604. slope = vec3( 1 ),
  21605. offset = vec3( 0 ),
  21606. power = vec3( 1 ),
  21607. saturation = float( 1 ),
  21608. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  21609. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  21610. ] ) => {
  21611. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  21612. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  21613. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  21614. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  21615. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  21616. const pv = v.pow( power ).toVar();
  21617. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  21618. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  21619. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  21620. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  21621. return vec4( v.rgb, color.a );
  21622. } );
  21623. /** @module PosterizeNode **/
  21624. /**
  21625. * Represents a posterize effect which reduces the number of colors
  21626. * in an image, resulting in a more blocky and stylized appearance.
  21627. *
  21628. * @augments TempNode
  21629. */
  21630. class PosterizeNode extends TempNode {
  21631. static get type() {
  21632. return 'PosterizeNode';
  21633. }
  21634. /**
  21635. * Constructs a new posterize node.
  21636. *
  21637. * @param {Node} sourceNode - The input color.
  21638. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  21639. */
  21640. constructor( sourceNode, stepsNode ) {
  21641. super();
  21642. /**
  21643. * The input color.
  21644. *
  21645. * @type {Node}
  21646. */
  21647. this.sourceNode = sourceNode;
  21648. /**
  21649. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  21650. *
  21651. * @type {Node}
  21652. */
  21653. this.stepsNode = stepsNode;
  21654. }
  21655. setup() {
  21656. const { sourceNode, stepsNode } = this;
  21657. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  21658. }
  21659. }
  21660. /**
  21661. * TSL function for creating a posterize node.
  21662. *
  21663. * @function
  21664. * @param {Node} sourceNode - The input color.
  21665. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  21666. * @returns {PosterizeNode}
  21667. */
  21668. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  21669. /** @module PassNode **/
  21670. const _size = /*@__PURE__*/ new Vector2();
  21671. /**
  21672. * Represents the texture of a pass node.
  21673. *
  21674. * @augments module:TextureNode~TextureNode
  21675. */
  21676. class PassTextureNode extends TextureNode {
  21677. static get type() {
  21678. return 'PassTextureNode';
  21679. }
  21680. /**
  21681. * Constructs a new pass texture node.
  21682. *
  21683. * @param {PassNode} passNode - The pass node.
  21684. * @param {Texture} texture - The output texture.
  21685. */
  21686. constructor( passNode, texture ) {
  21687. super( texture );
  21688. /**
  21689. * A reference to the pass node.
  21690. *
  21691. * @type {PassNode}
  21692. */
  21693. this.passNode = passNode;
  21694. this.setUpdateMatrix( false );
  21695. }
  21696. setup( builder ) {
  21697. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  21698. return super.setup( builder );
  21699. }
  21700. clone() {
  21701. return new this.constructor( this.passNode, this.value );
  21702. }
  21703. }
  21704. /**
  21705. * An extension of `PassTextureNode` which allows to manage more than one
  21706. * internal texture. Relevant for the `getPreviousTexture()` related API.
  21707. *
  21708. * @augments module:PassTextureNode~PassTextureNode
  21709. */
  21710. class PassMultipleTextureNode extends PassTextureNode {
  21711. static get type() {
  21712. return 'PassMultipleTextureNode';
  21713. }
  21714. /**
  21715. * Constructs a new pass texture node.
  21716. *
  21717. * @param {PassNode} passNode - The pass node.
  21718. * @param {String} textureName - The output texture name.
  21719. * @param {Boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  21720. */
  21721. constructor( passNode, textureName, previousTexture = false ) {
  21722. // null is passed to the super call since this class does not
  21723. // use an external texture for rendering pass data into. Instead
  21724. // the texture is managed by the pass node itself
  21725. super( passNode, null );
  21726. /**
  21727. * The output texture name.
  21728. *
  21729. * @type {String}
  21730. */
  21731. this.textureName = textureName;
  21732. /**
  21733. * Whether previous frame data should be used or not.
  21734. *
  21735. * @type {Boolean}
  21736. */
  21737. this.previousTexture = previousTexture;
  21738. }
  21739. /**
  21740. * Updates the texture reference of this node.
  21741. */
  21742. updateTexture() {
  21743. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  21744. }
  21745. setup( builder ) {
  21746. this.updateTexture();
  21747. return super.setup( builder );
  21748. }
  21749. clone() {
  21750. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  21751. }
  21752. }
  21753. /**
  21754. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  21755. * This pass produces a render for the given scene and camera and can provide multiple outputs
  21756. * via MRT for further processing.
  21757. *
  21758. * ```js
  21759. * const postProcessing = new PostProcessing( renderer );
  21760. *
  21761. * const scenePass = pass( scene, camera );
  21762. *
  21763. * postProcessing.outputNode = scenePass;
  21764. * ```
  21765. *
  21766. * @augments TempNode
  21767. */
  21768. class PassNode extends TempNode {
  21769. static get type() {
  21770. return 'PassNode';
  21771. }
  21772. /**
  21773. * Constructs a new pass node.
  21774. *
  21775. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  21776. * @param {Scene} scene - A reference to the scene.
  21777. * @param {Camera} camera - A reference to the camera.
  21778. * @param {Object} options - Options for the internal render target.
  21779. */
  21780. constructor( scope, scene, camera, options = {} ) {
  21781. super( 'vec4' );
  21782. /**
  21783. * The scope of the pass. The scope determines whether the node outputs color or depth.
  21784. *
  21785. * @type {('color'|'depth')}
  21786. */
  21787. this.scope = scope;
  21788. /**
  21789. * A reference to the scene.
  21790. *
  21791. * @type {Scene}
  21792. */
  21793. this.scene = scene;
  21794. /**
  21795. * A reference to the camera.
  21796. *
  21797. * @type {Camera}
  21798. */
  21799. this.camera = camera;
  21800. /**
  21801. * Options for the internal render target.
  21802. *
  21803. * @type {Object}
  21804. */
  21805. this.options = options;
  21806. /**
  21807. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  21808. *
  21809. * @private
  21810. * @type {Number}
  21811. * @default 1
  21812. */
  21813. this._pixelRatio = 1;
  21814. /**
  21815. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  21816. * @private
  21817. * @type {Number}
  21818. * @default 1
  21819. */
  21820. this._width = 1;
  21821. /**
  21822. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  21823. * @private
  21824. * @type {Number}
  21825. * @default 1
  21826. */
  21827. this._height = 1;
  21828. const depthTexture = new DepthTexture();
  21829. depthTexture.isRenderTargetTexture = true;
  21830. //depthTexture.type = FloatType;
  21831. depthTexture.name = 'depth';
  21832. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  21833. renderTarget.texture.name = 'output';
  21834. renderTarget.depthTexture = depthTexture;
  21835. /**
  21836. * The pass's render target.
  21837. *
  21838. * @type {RenderTarget}
  21839. */
  21840. this.renderTarget = renderTarget;
  21841. /**
  21842. * A dictionary holding the internal result textures.
  21843. *
  21844. * @private
  21845. * @type {Object<String, Texture>}
  21846. */
  21847. this._textures = {
  21848. output: renderTarget.texture,
  21849. depth: depthTexture
  21850. };
  21851. /**
  21852. * A dictionary holding the internal texture nodes.
  21853. *
  21854. * @private
  21855. * @type {Object<String, TextureNode>}
  21856. */
  21857. this._textureNodes = {};
  21858. /**
  21859. * A dictionary holding the internal depth nodes.
  21860. *
  21861. * @private
  21862. * @type {Object}
  21863. */
  21864. this._linearDepthNodes = {};
  21865. /**
  21866. * A dictionary holding the internal viewZ nodes.
  21867. *
  21868. * @private
  21869. * @type {Object}
  21870. */
  21871. this._viewZNodes = {};
  21872. /**
  21873. * A dictionary holding the texture data of the previous frame.
  21874. * Used for computing velocity/motion vectors.
  21875. *
  21876. * @private
  21877. * @type {Object<String, Texture>}
  21878. */
  21879. this._previousTextures = {};
  21880. /**
  21881. * A dictionary holding the texture nodes of the previous frame.
  21882. * Used for computing velocity/motion vectors.
  21883. *
  21884. * @private
  21885. * @type {Object<String, TextureNode>}
  21886. */
  21887. this._previousTextureNodes = {};
  21888. /**
  21889. * The `near` property of the camera as a uniform.
  21890. *
  21891. * @private
  21892. * @type {UniformNode}
  21893. */
  21894. this._cameraNear = uniform( 0 );
  21895. /**
  21896. * The `far` property of the camera as a uniform.
  21897. *
  21898. * @private
  21899. * @type {UniformNode}
  21900. */
  21901. this._cameraFar = uniform( 0 );
  21902. /**
  21903. * A MRT node configuring the MRT settings.
  21904. *
  21905. * @private
  21906. * @type {MRTNode?}
  21907. * @default null
  21908. */
  21909. this._mrt = null;
  21910. /**
  21911. * This flag can be used for type testing.
  21912. *
  21913. * @type {Boolean}
  21914. * @readonly
  21915. * @default true
  21916. */
  21917. this.isPassNode = true;
  21918. /**
  21919. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  21920. * scene once per frame in its {@link PassNode#updateBefore} method.
  21921. *
  21922. * @type {String}
  21923. * @default 'frame'
  21924. */
  21925. this.updateBeforeType = NodeUpdateType.FRAME;
  21926. }
  21927. /**
  21928. * Sets the given MRT node to setup MRT for this pass.
  21929. *
  21930. * @param {MRTNode} mrt - The MRT object.
  21931. * @return {PassNode} A reference to this pass.
  21932. */
  21933. setMRT( mrt ) {
  21934. this._mrt = mrt;
  21935. return this;
  21936. }
  21937. /**
  21938. * Returns the current MRT node.
  21939. *
  21940. * @return {MRTNode} The current MRT node.
  21941. */
  21942. getMRT() {
  21943. return this._mrt;
  21944. }
  21945. /**
  21946. * The method is overwritten so it always returns `true`.
  21947. *
  21948. * @return {Boolean} Whether this node is global or not.
  21949. */
  21950. isGlobal() {
  21951. return true;
  21952. }
  21953. /**
  21954. * Returns the texture for the given output name.
  21955. *
  21956. * @param {String} name - The output name to get the texture for.
  21957. * @return {Texture} The texture.
  21958. */
  21959. getTexture( name ) {
  21960. let texture = this._textures[ name ];
  21961. if ( texture === undefined ) {
  21962. const refTexture = this.renderTarget.texture;
  21963. texture = refTexture.clone();
  21964. texture.name = name;
  21965. this._textures[ name ] = texture;
  21966. this.renderTarget.textures.push( texture );
  21967. }
  21968. return texture;
  21969. }
  21970. /**
  21971. * Returns the texture holding the data of the previous frame for the given output name.
  21972. *
  21973. * @param {String} name - The output name to get the texture for.
  21974. * @return {Texture} The texture holding the data of the previous frame.
  21975. */
  21976. getPreviousTexture( name ) {
  21977. let texture = this._previousTextures[ name ];
  21978. if ( texture === undefined ) {
  21979. texture = this.getTexture( name ).clone();
  21980. this._previousTextures[ name ] = texture;
  21981. }
  21982. return texture;
  21983. }
  21984. /**
  21985. * Switches current and previous textures for the given output name.
  21986. *
  21987. * @param {String} name - The output name.
  21988. */
  21989. toggleTexture( name ) {
  21990. const prevTexture = this._previousTextures[ name ];
  21991. if ( prevTexture !== undefined ) {
  21992. const texture = this._textures[ name ];
  21993. const index = this.renderTarget.textures.indexOf( texture );
  21994. this.renderTarget.textures[ index ] = prevTexture;
  21995. this._textures[ name ] = prevTexture;
  21996. this._previousTextures[ name ] = texture;
  21997. this._textureNodes[ name ].updateTexture();
  21998. this._previousTextureNodes[ name ].updateTexture();
  21999. }
  22000. }
  22001. /**
  22002. * Returns the texture node for the given output name.
  22003. *
  22004. * @param {String} [name='output'] - The output name to get the texture node for.
  22005. * @return {TextureNode} The texture node.
  22006. */
  22007. getTextureNode( name = 'output' ) {
  22008. let textureNode = this._textureNodes[ name ];
  22009. if ( textureNode === undefined ) {
  22010. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  22011. textureNode.updateTexture();
  22012. this._textureNodes[ name ] = textureNode;
  22013. }
  22014. return textureNode;
  22015. }
  22016. /**
  22017. * Returns the previous texture node for the given output name.
  22018. *
  22019. * @param {String} [name='output'] - The output name to get the previous texture node for.
  22020. * @return {TextureNode} The previous texture node.
  22021. */
  22022. getPreviousTextureNode( name = 'output' ) {
  22023. let textureNode = this._previousTextureNodes[ name ];
  22024. if ( textureNode === undefined ) {
  22025. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  22026. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  22027. textureNode.updateTexture();
  22028. this._previousTextureNodes[ name ] = textureNode;
  22029. }
  22030. return textureNode;
  22031. }
  22032. /**
  22033. * Returns a viewZ node of this pass.
  22034. *
  22035. * @param {String} [name='depth'] - The output name to get the viewZ node for. In most cases the default `'depth'` can be used however the parameter exists for custom depth outputs.
  22036. * @return {Node} The viewZ node.
  22037. */
  22038. getViewZNode( name = 'depth' ) {
  22039. let viewZNode = this._viewZNodes[ name ];
  22040. if ( viewZNode === undefined ) {
  22041. const cameraNear = this._cameraNear;
  22042. const cameraFar = this._cameraFar;
  22043. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  22044. }
  22045. return viewZNode;
  22046. }
  22047. /**
  22048. * Returns a linear depth node of this pass.
  22049. *
  22050. * @param {String} [name='depth'] - The output name to get the linear depth node for. In most cases the default `'depth'` can be used however the parameter exists for custom depth outputs.
  22051. * @return {Node} The linear depth node.
  22052. */
  22053. getLinearDepthNode( name = 'depth' ) {
  22054. let linearDepthNode = this._linearDepthNodes[ name ];
  22055. if ( linearDepthNode === undefined ) {
  22056. const cameraNear = this._cameraNear;
  22057. const cameraFar = this._cameraFar;
  22058. const viewZNode = this.getViewZNode( name );
  22059. // TODO: just if ( builder.camera.isPerspectiveCamera )
  22060. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  22061. }
  22062. return linearDepthNode;
  22063. }
  22064. setup( { renderer } ) {
  22065. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  22066. // Disable MSAA for WebGL backend for now
  22067. if ( renderer.backend.isWebGLBackend === true ) {
  22068. this.renderTarget.samples = 0;
  22069. }
  22070. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  22071. }
  22072. updateBefore( frame ) {
  22073. const { renderer } = frame;
  22074. const { scene, camera } = this;
  22075. this._pixelRatio = renderer.getPixelRatio();
  22076. const size = renderer.getSize( _size );
  22077. this.setSize( size.width, size.height );
  22078. const currentRenderTarget = renderer.getRenderTarget();
  22079. const currentMRT = renderer.getMRT();
  22080. this._cameraNear.value = camera.near;
  22081. this._cameraFar.value = camera.far;
  22082. for ( const name in this._previousTextures ) {
  22083. this.toggleTexture( name );
  22084. }
  22085. renderer.setRenderTarget( this.renderTarget );
  22086. renderer.setMRT( this._mrt );
  22087. renderer.render( scene, camera );
  22088. renderer.setRenderTarget( currentRenderTarget );
  22089. renderer.setMRT( currentMRT );
  22090. }
  22091. /**
  22092. * Sets the size of the pass's render target. Honors the pixel ratio.
  22093. *
  22094. * @param {Number} width - The width to set.
  22095. * @param {Number} height - The height to set.
  22096. */
  22097. setSize( width, height ) {
  22098. this._width = width;
  22099. this._height = height;
  22100. const effectiveWidth = this._width * this._pixelRatio;
  22101. const effectiveHeight = this._height * this._pixelRatio;
  22102. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  22103. }
  22104. /**
  22105. * Sets the pixel ratio the pass's render target and updates the size.
  22106. *
  22107. * @param {Number} pixelRatio - The pixel ratio to set.
  22108. */
  22109. setPixelRatio( pixelRatio ) {
  22110. this._pixelRatio = pixelRatio;
  22111. this.setSize( this._width, this._height );
  22112. }
  22113. /**
  22114. * Frees internal resources. Should be called when the node is no longer in use.
  22115. */
  22116. dispose() {
  22117. this.renderTarget.dispose();
  22118. }
  22119. }
  22120. PassNode.COLOR = 'color';
  22121. PassNode.DEPTH = 'depth';
  22122. /**
  22123. * TSL function for creating a pass node.
  22124. *
  22125. * @function
  22126. * @param {Scene} scene - A reference to the scene.
  22127. * @param {Camera} camera - A reference to the camera.
  22128. * @param {Object} options - Options for the internal render target.
  22129. * @returns {PassNode}
  22130. */
  22131. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  22132. /**
  22133. * TSL function for creating a pass texture node.
  22134. *
  22135. * @function
  22136. * @param {PassNode} pass - The pass node.
  22137. * @param {Texture} texture - The output texture.
  22138. * @returns {PassTextureNode}
  22139. */
  22140. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  22141. /**
  22142. * TSL function for creating a depth pass node.
  22143. *
  22144. * @function
  22145. * @param {Scene} scene - A reference to the scene.
  22146. * @param {Camera} camera - A reference to the camera.
  22147. * @param {Object} options - Options for the internal render target.
  22148. * @returns {PassNode}
  22149. */
  22150. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  22151. /** @module ToonOutlinePassNode **/
  22152. /**
  22153. * Represents a render pass for producing a toon outline effect on compatible objects.
  22154. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  22155. * will receive the outline.
  22156. *
  22157. * ```js
  22158. * const postProcessing = new PostProcessing( renderer );
  22159. *
  22160. * const scenePass = toonOutlinePass( scene, camera );
  22161. *
  22162. * postProcessing.outputNode = scenePass;
  22163. * ```
  22164. * @augments PassNode
  22165. */
  22166. class ToonOutlinePassNode extends PassNode {
  22167. static get type() {
  22168. return 'ToonOutlinePassNode';
  22169. }
  22170. /**
  22171. * Constructs a new outline pass node.
  22172. *
  22173. * @param {Scene} scene - A reference to the scene.
  22174. * @param {Camera} camera - A reference to the camera.
  22175. * @param {Node} colorNode - Defines the outline's color.
  22176. * @param {Node} thicknessNode - Defines the outline's thickness.
  22177. * @param {Node} alphaNode - Defines the outline's alpha.
  22178. */
  22179. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  22180. super( PassNode.COLOR, scene, camera );
  22181. /**
  22182. * Defines the outline's color.
  22183. *
  22184. * @type {Node}
  22185. */
  22186. this.colorNode = colorNode;
  22187. /**
  22188. * Defines the outline's thickness.
  22189. *
  22190. * @type {Node}
  22191. */
  22192. this.thicknessNode = thicknessNode;
  22193. /**
  22194. * Defines the outline's alpha.
  22195. *
  22196. * @type {Node}
  22197. */
  22198. this.alphaNode = alphaNode;
  22199. /**
  22200. * An internal material cache.
  22201. *
  22202. * @private
  22203. * @type {WeakMap<Material, NodeMaterial>}
  22204. */
  22205. this._materialCache = new WeakMap();
  22206. }
  22207. updateBefore( frame ) {
  22208. const { renderer } = frame;
  22209. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  22210. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  22211. // only render outline for supported materials
  22212. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  22213. if ( material.wireframe === false ) {
  22214. const outlineMaterial = this._getOutlineMaterial( material );
  22215. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  22216. }
  22217. }
  22218. // default
  22219. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  22220. } );
  22221. super.updateBefore( frame );
  22222. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  22223. }
  22224. /**
  22225. * Creates the material used for outline rendering.
  22226. *
  22227. * @private
  22228. * @return {NodeMaterial} The outline material.
  22229. */
  22230. _createMaterial() {
  22231. const material = new NodeMaterial();
  22232. material.isMeshToonOutlineMaterial = true;
  22233. material.name = 'Toon_Outline';
  22234. material.side = BackSide;
  22235. // vertex node
  22236. const outlineNormal = normalLocal.negate();
  22237. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  22238. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  22239. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  22240. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  22241. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  22242. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  22243. // color node
  22244. material.colorNode = vec4( this.colorNode, this.alphaNode );
  22245. return material;
  22246. }
  22247. /**
  22248. * For the given toon material, this method returns a corresponding
  22249. * outline material.
  22250. *
  22251. * @private
  22252. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  22253. * @return {NodeMaterial} The outline material.
  22254. */
  22255. _getOutlineMaterial( originalMaterial ) {
  22256. let outlineMaterial = this._materialCache.get( originalMaterial );
  22257. if ( outlineMaterial === undefined ) {
  22258. outlineMaterial = this._createMaterial();
  22259. this._materialCache.set( originalMaterial, outlineMaterial );
  22260. }
  22261. return outlineMaterial;
  22262. }
  22263. }
  22264. /**
  22265. * TSL function for creating a toon outline pass node.
  22266. *
  22267. * @function
  22268. * @param {Scene} scene - A reference to the scene.
  22269. * @param {Camera} camera - A reference to the camera.
  22270. * @param {Color} color - Defines the outline's color.
  22271. * @param {Number} [thickness=0.003] - Defines the outline's thickness.
  22272. * @param {Number} [alpha=1] - Defines the outline's alpha.
  22273. * @returns {ToonOutlinePassNode}
  22274. */
  22275. 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 ) ) );
  22276. /** @module ToneMappingFunctions **/
  22277. /**
  22278. * Linear tone mapping, exposure only.
  22279. *
  22280. * @method
  22281. * @param {Node<vec3>} color - The color that should be tone mapped.
  22282. * @param {Node<float>} exposure - The exposure.
  22283. * @return {Node<vec3>} The tone mapped color.
  22284. */
  22285. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22286. return color.mul( exposure ).clamp();
  22287. } ).setLayout( {
  22288. name: 'linearToneMapping',
  22289. type: 'vec3',
  22290. inputs: [
  22291. { name: 'color', type: 'vec3' },
  22292. { name: 'exposure', type: 'float' }
  22293. ]
  22294. } );
  22295. /**
  22296. * Reinhard tone mapping.
  22297. *
  22298. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  22299. *
  22300. * @method
  22301. * @param {Node<vec3>} color - The color that should be tone mapped.
  22302. * @param {Node<float>} exposure - The exposure.
  22303. * @return {Node<vec3>} The tone mapped color.
  22304. */
  22305. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22306. color = color.mul( exposure );
  22307. return color.div( color.add( 1.0 ) ).clamp();
  22308. } ).setLayout( {
  22309. name: 'reinhardToneMapping',
  22310. type: 'vec3',
  22311. inputs: [
  22312. { name: 'color', type: 'vec3' },
  22313. { name: 'exposure', type: 'float' }
  22314. ]
  22315. } );
  22316. /**
  22317. * Cineon tone mapping.
  22318. *
  22319. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  22320. *
  22321. * @method
  22322. * @param {Node<vec3>} color - The color that should be tone mapped.
  22323. * @param {Node<float>} exposure - The exposure.
  22324. * @return {Node<vec3>} The tone mapped color.
  22325. */
  22326. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22327. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  22328. color = color.mul( exposure );
  22329. color = color.sub( 0.004 ).max( 0.0 );
  22330. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  22331. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  22332. return a.div( b ).pow( 2.2 );
  22333. } ).setLayout( {
  22334. name: 'cineonToneMapping',
  22335. type: 'vec3',
  22336. inputs: [
  22337. { name: 'color', type: 'vec3' },
  22338. { name: 'exposure', type: 'float' }
  22339. ]
  22340. } );
  22341. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  22342. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  22343. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  22344. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  22345. return a.div( b );
  22346. } );
  22347. /**
  22348. * ACESFilmic tone mapping.
  22349. *
  22350. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  22351. *
  22352. * @method
  22353. * @param {Node<vec3>} color - The color that should be tone mapped.
  22354. * @param {Node<float>} exposure - The exposure.
  22355. * @return {Node<vec3>} The tone mapped color.
  22356. */
  22357. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22358. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  22359. const ACESInputMat = mat3(
  22360. 0.59719, 0.35458, 0.04823,
  22361. 0.07600, 0.90834, 0.01566,
  22362. 0.02840, 0.13383, 0.83777
  22363. );
  22364. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  22365. const ACESOutputMat = mat3(
  22366. 1.60475, - 0.53108, - 0.07367,
  22367. - 0.10208, 1.10813, - 0.00605,
  22368. - 0.00327, - 0.07276, 1.07602
  22369. );
  22370. color = color.mul( exposure ).div( 0.6 );
  22371. color = ACESInputMat.mul( color );
  22372. // Apply RRT and ODT
  22373. color = RRTAndODTFit( color );
  22374. color = ACESOutputMat.mul( color );
  22375. // Clamp to [0, 1]
  22376. return color.clamp();
  22377. } ).setLayout( {
  22378. name: 'acesFilmicToneMapping',
  22379. type: 'vec3',
  22380. inputs: [
  22381. { name: 'color', type: 'vec3' },
  22382. { name: 'exposure', type: 'float' }
  22383. ]
  22384. } );
  22385. 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 ) );
  22386. 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 ) );
  22387. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  22388. const x = vec3( x_immutable ).toVar();
  22389. const x2 = vec3( x.mul( x ) ).toVar();
  22390. const x4 = vec3( x2.mul( x2 ) ).toVar();
  22391. 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 ) ) ) );
  22392. } );
  22393. /**
  22394. * AgX tone mapping.
  22395. *
  22396. * @method
  22397. * @param {Node<vec3>} color - The color that should be tone mapped.
  22398. * @param {Node<float>} exposure - The exposure.
  22399. * @return {Node<vec3>} The tone mapped color.
  22400. */
  22401. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22402. const colortone = vec3( color ).toVar();
  22403. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  22404. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  22405. const AgxMinEv = float( - 12.47393 );
  22406. const AgxMaxEv = float( 4.026069 );
  22407. colortone.mulAssign( exposure );
  22408. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  22409. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  22410. colortone.assign( max$1( colortone, 1e-10 ) );
  22411. colortone.assign( log2( colortone ) );
  22412. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  22413. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  22414. colortone.assign( agxDefaultContrastApprox( colortone ) );
  22415. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  22416. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  22417. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  22418. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  22419. return colortone;
  22420. } ).setLayout( {
  22421. name: 'agxToneMapping',
  22422. type: 'vec3',
  22423. inputs: [
  22424. { name: 'color', type: 'vec3' },
  22425. { name: 'exposure', type: 'float' }
  22426. ]
  22427. } );
  22428. /**
  22429. * Neutral tone mapping.
  22430. *
  22431. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  22432. *
  22433. * @method
  22434. * @param {Node<vec3>} color - The color that should be tone mapped.
  22435. * @param {Node<float>} exposure - The exposure.
  22436. * @return {Node<vec3>} The tone mapped color.
  22437. */
  22438. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22439. const StartCompression = float( 0.8 - 0.04 );
  22440. const Desaturation = float( 0.15 );
  22441. color = color.mul( exposure );
  22442. const x = min$1( color.r, min$1( color.g, color.b ) );
  22443. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  22444. color.subAssign( offset );
  22445. const peak = max$1( color.r, max$1( color.g, color.b ) );
  22446. If( peak.lessThan( StartCompression ), () => {
  22447. return color;
  22448. } );
  22449. const d = sub( 1, StartCompression );
  22450. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  22451. color.mulAssign( newPeak.div( peak ) );
  22452. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  22453. return mix( color, vec3( newPeak ), g );
  22454. } ).setLayout( {
  22455. name: 'neutralToneMapping',
  22456. type: 'vec3',
  22457. inputs: [
  22458. { name: 'color', type: 'vec3' },
  22459. { name: 'exposure', type: 'float' }
  22460. ]
  22461. } );
  22462. /** @module CodeNode **/
  22463. /**
  22464. * This class represents native code sections. It is the base
  22465. * class for modules like {@link FunctionNode} which allows to implement
  22466. * functions with native shader languages.
  22467. *
  22468. * @augments Node
  22469. */
  22470. class CodeNode extends Node {
  22471. static get type() {
  22472. return 'CodeNode';
  22473. }
  22474. /**
  22475. * Constructs a new code node.
  22476. *
  22477. * @param {String} [code=''] - The native code.
  22478. * @param {Array<Node>} [includes=[]] - An array of includes.
  22479. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  22480. */
  22481. constructor( code = '', includes = [], language = '' ) {
  22482. super( 'code' );
  22483. /**
  22484. * This flag can be used for type testing.
  22485. *
  22486. * @type {Boolean}
  22487. * @readonly
  22488. * @default true
  22489. */
  22490. this.isCodeNode = true;
  22491. /**
  22492. * The native code.
  22493. *
  22494. * @type {String}
  22495. * @default ''
  22496. */
  22497. this.code = code;
  22498. /**
  22499. * An array of includes
  22500. *
  22501. * @type {Array<Node>}
  22502. * @default []
  22503. */
  22504. this.includes = includes;
  22505. /**
  22506. * The used language.
  22507. *
  22508. * @type {('js'|'wgsl'|'glsl')}
  22509. * @default ''
  22510. */
  22511. this.language = language;
  22512. }
  22513. /**
  22514. * The method is overwritten so it always returns `true`.
  22515. *
  22516. * @return {Boolean} Whether this node is global or not.
  22517. */
  22518. isGlobal() {
  22519. return true;
  22520. }
  22521. /**
  22522. * Sets the includes of this code node.
  22523. *
  22524. * @param {Array<Node>} includes - The includes to set.
  22525. * @return {CodeNode} A reference to this node.
  22526. */
  22527. setIncludes( includes ) {
  22528. this.includes = includes;
  22529. return this;
  22530. }
  22531. /**
  22532. * Returns the includes of this code node.
  22533. *
  22534. * @param {NodeBuilder} builder - The current node builder.
  22535. * @return {Array<Node>} The includes.
  22536. */
  22537. getIncludes( /*builder*/ ) {
  22538. return this.includes;
  22539. }
  22540. generate( builder ) {
  22541. const includes = this.getIncludes( builder );
  22542. for ( const include of includes ) {
  22543. include.build( builder );
  22544. }
  22545. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  22546. nodeCode.code = this.code;
  22547. return nodeCode.code;
  22548. }
  22549. serialize( data ) {
  22550. super.serialize( data );
  22551. data.code = this.code;
  22552. data.language = this.language;
  22553. }
  22554. deserialize( data ) {
  22555. super.deserialize( data );
  22556. this.code = data.code;
  22557. this.language = data.language;
  22558. }
  22559. }
  22560. /**
  22561. * TSL function for creating a code node.
  22562. *
  22563. * @function
  22564. * @param {String} [code=''] - The native code.
  22565. * @param {Array<Node>} [includes=[]] - An array of includes.
  22566. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  22567. * @returns {CodeNode}
  22568. */
  22569. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  22570. /**
  22571. * TSL function for creating a JS code node.
  22572. *
  22573. * @function
  22574. * @param {String} src - The native code.
  22575. * @param {Array<Node>} includes - An array of includes.
  22576. * @returns {CodeNode}
  22577. */
  22578. const js = ( src, includes ) => code( src, includes, 'js' );
  22579. /**
  22580. * TSL function for creating a WGSL code node.
  22581. *
  22582. * @function
  22583. * @param {String} src - The native code.
  22584. * @param {Array<Node>} includes - An array of includes.
  22585. * @returns {CodeNode}
  22586. */
  22587. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  22588. /**
  22589. * TSL function for creating a GLSL code node.
  22590. *
  22591. * @function
  22592. * @param {String} src - The native code.
  22593. * @param {Array<Node>} includes - An array of includes.
  22594. * @returns {CodeNode}
  22595. */
  22596. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  22597. /**
  22598. * This class represents a native shader function. It can be used to implement
  22599. * certain aspects of a node material with native shader code. There are two predefined
  22600. * TSL functions for easier usage.
  22601. *
  22602. * - `wgslFn`: Creates a WGSL function node.
  22603. * - `glslFn`: Creates a GLSL function node.
  22604. *
  22605. * A basic example with one include looks like so:
  22606. *
  22607. * ```js
  22608. * const desaturateWGSLFn = wgslFn( `
  22609. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  22610. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  22611. * return vec3<f32>( dot( lum, color ) );
  22612. * }`
  22613. *);
  22614. * const someWGSLFn = wgslFn( `
  22615. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  22616. * return desaturate( color );
  22617. * }
  22618. * `, [ desaturateWGSLFn ] );
  22619. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  22620. *```
  22621. * @augments CodeNode
  22622. */
  22623. class FunctionNode extends CodeNode {
  22624. static get type() {
  22625. return 'FunctionNode';
  22626. }
  22627. /**
  22628. * Constructs a new function node.
  22629. *
  22630. * @param {String} [code=''] - The native code.
  22631. * @param {Array<Node>} [includes=[]] - An array of includes.
  22632. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  22633. */
  22634. constructor( code = '', includes = [], language = '' ) {
  22635. super( code, includes, language );
  22636. }
  22637. getNodeType( builder ) {
  22638. return this.getNodeFunction( builder ).type;
  22639. }
  22640. /**
  22641. * Returns the inputs of this function node.
  22642. *
  22643. * @param {NodeBuilder} builder - The current node builder.
  22644. * @return {Array<NodeFunctionInput>} The inputs.
  22645. */
  22646. getInputs( builder ) {
  22647. return this.getNodeFunction( builder ).inputs;
  22648. }
  22649. /**
  22650. * Returns the node function for this function node.
  22651. *
  22652. * @param {NodeBuilder} builder - The current node builder.
  22653. * @return {NodeFunction} The node function.
  22654. */
  22655. getNodeFunction( builder ) {
  22656. const nodeData = builder.getDataFromNode( this );
  22657. let nodeFunction = nodeData.nodeFunction;
  22658. if ( nodeFunction === undefined ) {
  22659. nodeFunction = builder.parser.parseFunction( this.code );
  22660. nodeData.nodeFunction = nodeFunction;
  22661. }
  22662. return nodeFunction;
  22663. }
  22664. generate( builder, output ) {
  22665. super.generate( builder );
  22666. const nodeFunction = this.getNodeFunction( builder );
  22667. const name = nodeFunction.name;
  22668. const type = nodeFunction.type;
  22669. const nodeCode = builder.getCodeFromNode( this, type );
  22670. if ( name !== '' ) {
  22671. // use a custom property name
  22672. nodeCode.name = name;
  22673. }
  22674. const propertyName = builder.getPropertyName( nodeCode );
  22675. const code = this.getNodeFunction( builder ).getCode( propertyName );
  22676. nodeCode.code = code + '\n';
  22677. if ( output === 'property' ) {
  22678. return propertyName;
  22679. } else {
  22680. return builder.format( `${ propertyName }()`, type, output );
  22681. }
  22682. }
  22683. }
  22684. const nativeFn = ( code, includes = [], language = '' ) => {
  22685. for ( let i = 0; i < includes.length; i ++ ) {
  22686. const include = includes[ i ];
  22687. // TSL Function: glslFn, wgslFn
  22688. if ( typeof include === 'function' ) {
  22689. includes[ i ] = include.functionNode;
  22690. }
  22691. }
  22692. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  22693. const fn = ( ...params ) => functionNode.call( ...params );
  22694. fn.functionNode = functionNode;
  22695. return fn;
  22696. };
  22697. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  22698. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  22699. /** @module ScriptableValueNode **/
  22700. /**
  22701. * `ScriptableNode` uses this class to manage script inputs and outputs.
  22702. *
  22703. * @augments Node
  22704. */
  22705. class ScriptableValueNode extends Node {
  22706. static get type() {
  22707. return 'ScriptableValueNode';
  22708. }
  22709. /**
  22710. * Constructs a new scriptable node.
  22711. *
  22712. * @param {Any} [value=null] - The value.
  22713. */
  22714. constructor( value = null ) {
  22715. super();
  22716. /**
  22717. * A reference to the value.
  22718. *
  22719. * @private
  22720. * @default null
  22721. */
  22722. this._value = value;
  22723. /**
  22724. * Depending on the type of `_value`, this property might cache parsed data.
  22725. *
  22726. * @private
  22727. * @default null
  22728. */
  22729. this._cache = null;
  22730. /**
  22731. * If this node represents an input, this property represents the input type.
  22732. *
  22733. * @type {String?}
  22734. * @default null
  22735. */
  22736. this.inputType = null;
  22737. /**
  22738. * If this node represents an output, this property represents the output type.
  22739. *
  22740. * @type {String?}
  22741. * @default null
  22742. */
  22743. this.outputType = null;
  22744. /**
  22745. * An event dispatcher for managing events.
  22746. *
  22747. * @type {EventDispatcher}
  22748. */
  22749. this.events = new EventDispatcher();
  22750. /**
  22751. * This flag can be used for type testing.
  22752. *
  22753. * @type {Boolean}
  22754. * @readonly
  22755. * @default true
  22756. */
  22757. this.isScriptableValueNode = true;
  22758. }
  22759. /**
  22760. * Whether this node represents an output or not.
  22761. *
  22762. * @type {Boolean}
  22763. * @readonly
  22764. * @default true
  22765. */
  22766. get isScriptableOutputNode() {
  22767. return this.outputType !== null;
  22768. }
  22769. set value( val ) {
  22770. if ( this._value === val ) return;
  22771. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  22772. URL.revokeObjectURL( this._cache );
  22773. this._cache = null;
  22774. }
  22775. this._value = val;
  22776. this.events.dispatchEvent( { type: 'change' } );
  22777. this.refresh();
  22778. }
  22779. /**
  22780. * The node's value.
  22781. *
  22782. * @type {Any}
  22783. */
  22784. get value() {
  22785. return this._value;
  22786. }
  22787. /**
  22788. * Dispatches the `refresh` event.
  22789. */
  22790. refresh() {
  22791. this.events.dispatchEvent( { type: 'refresh' } );
  22792. }
  22793. /**
  22794. * The `value` property usually represents a node or even binary data in form of array buffers.
  22795. * In this case, this method tries to return the actual value behind the complex type.
  22796. *
  22797. * @return {Any} The value.
  22798. */
  22799. getValue() {
  22800. const value = this.value;
  22801. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  22802. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  22803. } else if ( value && value.value !== null && value.value !== undefined && (
  22804. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  22805. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  22806. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  22807. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  22808. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  22809. ( this.inputType === 'Color' && value.value.isColor ) ||
  22810. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  22811. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  22812. ) ) {
  22813. return value.value;
  22814. }
  22815. return this._cache || value;
  22816. }
  22817. /**
  22818. * Overwritten since the node type is inferred from the value.
  22819. *
  22820. * @param {NodeBuilder} builder - The current node builder.
  22821. * @return {String} The node type.
  22822. */
  22823. getNodeType( builder ) {
  22824. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  22825. }
  22826. setup() {
  22827. return this.value && this.value.isNode ? this.value : float();
  22828. }
  22829. serialize( data ) {
  22830. super.serialize( data );
  22831. if ( this.value !== null ) {
  22832. if ( this.inputType === 'ArrayBuffer' ) {
  22833. data.value = arrayBufferToBase64( this.value );
  22834. } else {
  22835. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  22836. }
  22837. } else {
  22838. data.value = null;
  22839. }
  22840. data.inputType = this.inputType;
  22841. data.outputType = this.outputType;
  22842. }
  22843. deserialize( data ) {
  22844. super.deserialize( data );
  22845. let value = null;
  22846. if ( data.value !== null ) {
  22847. if ( data.inputType === 'ArrayBuffer' ) {
  22848. value = base64ToArrayBuffer( data.value );
  22849. } else if ( data.inputType === 'Texture' ) {
  22850. value = data.meta.textures[ data.value ];
  22851. } else {
  22852. value = data.meta.nodes[ data.value ] || null;
  22853. }
  22854. }
  22855. this.value = value;
  22856. this.inputType = data.inputType;
  22857. this.outputType = data.outputType;
  22858. }
  22859. }
  22860. /**
  22861. * TSL function for creating a scriptable value node.
  22862. *
  22863. * @function
  22864. * @param {Any} [value=null] - The value.
  22865. * @returns {ScriptableValueNode}
  22866. */
  22867. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  22868. /** @module ScriptableNode **/
  22869. /**
  22870. * A Map-like data structure for managing resources of scriptable nodes.
  22871. *
  22872. * @augments Map
  22873. */
  22874. class Resources extends Map {
  22875. get( key, callback = null, ...params ) {
  22876. if ( this.has( key ) ) return super.get( key );
  22877. if ( callback !== null ) {
  22878. const value = callback( ...params );
  22879. this.set( key, value );
  22880. return value;
  22881. }
  22882. }
  22883. }
  22884. class Parameters {
  22885. constructor( scriptableNode ) {
  22886. this.scriptableNode = scriptableNode;
  22887. }
  22888. get parameters() {
  22889. return this.scriptableNode.parameters;
  22890. }
  22891. get layout() {
  22892. return this.scriptableNode.getLayout();
  22893. }
  22894. getInputLayout( id ) {
  22895. return this.scriptableNode.getInputLayout( id );
  22896. }
  22897. get( name ) {
  22898. const param = this.parameters[ name ];
  22899. const value = param ? param.getValue() : null;
  22900. return value;
  22901. }
  22902. }
  22903. /**
  22904. * Defines the resouces (e.g. namespaces) of scriptable nodes.
  22905. *
  22906. * @type {Resources}
  22907. */
  22908. const ScriptableNodeResources = new Resources();
  22909. /**
  22910. * This type of node allows to implement nodes with custom scripts. The script
  22911. * section is represented as an instance of `CodeNode` written with JavaScript.
  22912. * The script itself must adhere to a specific structure.
  22913. *
  22914. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  22915. * - layout: The layout object defines the script's interface (inputs and outputs).
  22916. *
  22917. * ```js
  22918. * ScriptableNodeResources.set( 'TSL', TSL );
  22919. *
  22920. * const scriptableNode = scriptable( js( `
  22921. * layout = {
  22922. * outputType: 'node',
  22923. * elements: [
  22924. * { name: 'source', inputType: 'node' },
  22925. * ]
  22926. * };
  22927. *
  22928. * const { mul, oscSine } = TSL;
  22929. *
  22930. * function main() {
  22931. * const source = parameters.get( 'source' ) || float();
  22932. * return mul( source, oscSine() ) );
  22933. * }
  22934. *
  22935. * ` ) );
  22936. *
  22937. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  22938. *
  22939. * const material = new THREE.MeshBasicNodeMaterial();
  22940. * material.colorNode = scriptableNode;
  22941. * ```
  22942. *
  22943. * @augments Node
  22944. */
  22945. class ScriptableNode extends Node {
  22946. static get type() {
  22947. return 'ScriptableNode';
  22948. }
  22949. /**
  22950. * Constructs a new scriptable node.
  22951. *
  22952. * @param {CodeNode?} [codeNode=null] - The code node.
  22953. * @param {Object} [parameters={}] - The parameters definition.
  22954. */
  22955. constructor( codeNode = null, parameters = {} ) {
  22956. super();
  22957. /**
  22958. * The code node.
  22959. *
  22960. * @type {CodeNode?}
  22961. * @default null
  22962. */
  22963. this.codeNode = codeNode;
  22964. /**
  22965. * The parameters definition.
  22966. *
  22967. * @type {Object}
  22968. * @default {}
  22969. */
  22970. this.parameters = parameters;
  22971. this._local = new Resources();
  22972. this._output = scriptableValue();
  22973. this._outputs = {};
  22974. this._source = this.source;
  22975. this._method = null;
  22976. this._object = null;
  22977. this._value = null;
  22978. this._needsOutputUpdate = true;
  22979. this.onRefresh = this.onRefresh.bind( this );
  22980. /**
  22981. * This flag can be used for type testing.
  22982. *
  22983. * @type {Boolean}
  22984. * @readonly
  22985. * @default true
  22986. */
  22987. this.isScriptableNode = true;
  22988. }
  22989. /**
  22990. * The source code of the scriptable node.
  22991. *
  22992. * @type {String}
  22993. */
  22994. get source() {
  22995. return this.codeNode ? this.codeNode.code : '';
  22996. }
  22997. /**
  22998. * Sets the reference of a local script variable.
  22999. *
  23000. * @param {String} name - The variable name.
  23001. * @param {Object} value - The reference to set.
  23002. * @return {Resources} The resource map
  23003. */
  23004. setLocal( name, value ) {
  23005. return this._local.set( name, value );
  23006. }
  23007. /**
  23008. * Gets the value of a local script variable.
  23009. *
  23010. * @param {String} name - The variable name.
  23011. * @return {Object} The value.
  23012. */
  23013. getLocal( name ) {
  23014. return this._local.get( name );
  23015. }
  23016. /**
  23017. * Event listener for the `refresh` event.
  23018. */
  23019. onRefresh() {
  23020. this._refresh();
  23021. }
  23022. /**
  23023. * Returns an input from the layout with the given id/name.
  23024. *
  23025. * @param {String} id - The id/name of the input.
  23026. * @return {Object} The element entry.
  23027. */
  23028. getInputLayout( id ) {
  23029. for ( const element of this.getLayout() ) {
  23030. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  23031. return element;
  23032. }
  23033. }
  23034. }
  23035. /**
  23036. * Returns an output from the layout with the given id/name.
  23037. *
  23038. * @param {String} id - The id/name of the output.
  23039. * @return {Object} The element entry.
  23040. */
  23041. getOutputLayout( id ) {
  23042. for ( const element of this.getLayout() ) {
  23043. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  23044. return element;
  23045. }
  23046. }
  23047. }
  23048. /**
  23049. * Defines a script output for the given name and value.
  23050. *
  23051. * @param {String} name - The name of the output.
  23052. * @param {Node} value - The node value.
  23053. * @return {ScriptableNode} A reference to this node.
  23054. */
  23055. setOutput( name, value ) {
  23056. const outputs = this._outputs;
  23057. if ( outputs[ name ] === undefined ) {
  23058. outputs[ name ] = scriptableValue( value );
  23059. } else {
  23060. outputs[ name ].value = value;
  23061. }
  23062. return this;
  23063. }
  23064. /**
  23065. * Returns a script output for the given name.
  23066. *
  23067. * @param {String} name - The name of the output.
  23068. * @return {ScriptableValueNode} The node value.
  23069. */
  23070. getOutput( name ) {
  23071. return this._outputs[ name ];
  23072. }
  23073. /**
  23074. * Returns a paramater for the given name
  23075. *
  23076. * @param {String} name - The name of the parameter.
  23077. * @return {ScriptableValueNode} The node value.
  23078. */
  23079. getParameter( name ) {
  23080. return this.parameters[ name ];
  23081. }
  23082. /**
  23083. * Sets a value for the given parameter name.
  23084. *
  23085. * @param {String} name - The parameter name.
  23086. * @param {Any} value - The parameter value.
  23087. * @return {ScriptableNode} A reference to this node.
  23088. */
  23089. setParameter( name, value ) {
  23090. const parameters = this.parameters;
  23091. if ( value && value.isScriptableNode ) {
  23092. this.deleteParameter( name );
  23093. parameters[ name ] = value;
  23094. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  23095. } else if ( value && value.isScriptableValueNode ) {
  23096. this.deleteParameter( name );
  23097. parameters[ name ] = value;
  23098. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  23099. } else if ( parameters[ name ] === undefined ) {
  23100. parameters[ name ] = scriptableValue( value );
  23101. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  23102. } else {
  23103. parameters[ name ].value = value;
  23104. }
  23105. return this;
  23106. }
  23107. /**
  23108. * Returns the value of this node which is the value of
  23109. * the default output.
  23110. *
  23111. * @return {Node} The value.
  23112. */
  23113. getValue() {
  23114. return this.getDefaultOutput().getValue();
  23115. }
  23116. /**
  23117. * Deletes a parameter from the script.
  23118. *
  23119. * @param {String} name - The parameter to remove.
  23120. * @return {ScriptableNode} A reference to this node.
  23121. */
  23122. deleteParameter( name ) {
  23123. let valueNode = this.parameters[ name ];
  23124. if ( valueNode ) {
  23125. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  23126. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  23127. }
  23128. return this;
  23129. }
  23130. /**
  23131. * Deletes all parameters from the script.
  23132. *
  23133. * @return {ScriptableNode} A reference to this node.
  23134. */
  23135. clearParameters() {
  23136. for ( const name of Object.keys( this.parameters ) ) {
  23137. this.deleteParameter( name );
  23138. }
  23139. this.needsUpdate = true;
  23140. return this;
  23141. }
  23142. /**
  23143. * Calls a function from the script.
  23144. *
  23145. * @param {String} name - The function name.
  23146. * @param {...Any} params - A list of parameters.
  23147. * @return {Any} The result of the function call.
  23148. */
  23149. call( name, ...params ) {
  23150. const object = this.getObject();
  23151. const method = object[ name ];
  23152. if ( typeof method === 'function' ) {
  23153. return method( ...params );
  23154. }
  23155. }
  23156. /**
  23157. * Asynchronously calls a function from the script.
  23158. *
  23159. * @param {String} name - The function name.
  23160. * @param {...Any} params - A list of parameters.
  23161. * @return {Any} The result of the function call.
  23162. */
  23163. async callAsync( name, ...params ) {
  23164. const object = this.getObject();
  23165. const method = object[ name ];
  23166. if ( typeof method === 'function' ) {
  23167. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  23168. }
  23169. }
  23170. /**
  23171. * Overwritten since the node types is inferred from the script's output.
  23172. *
  23173. * @param {NodeBuilder} builder - The current node builder
  23174. * @return {String} The node type.
  23175. */
  23176. getNodeType( builder ) {
  23177. return this.getDefaultOutputNode().getNodeType( builder );
  23178. }
  23179. /**
  23180. * Refreshes the script node.
  23181. *
  23182. * @param {String?} [output=null] - An optional output.
  23183. */
  23184. refresh( output = null ) {
  23185. if ( output !== null ) {
  23186. this.getOutput( output ).refresh();
  23187. } else {
  23188. this._refresh();
  23189. }
  23190. }
  23191. /**
  23192. * Returns an object representation of the script.
  23193. *
  23194. * @return {Object} The result object.
  23195. */
  23196. getObject() {
  23197. if ( this.needsUpdate ) this.dispose();
  23198. if ( this._object !== null ) return this._object;
  23199. //
  23200. const refresh = () => this.refresh();
  23201. const setOutput = ( id, value ) => this.setOutput( id, value );
  23202. const parameters = new Parameters( this );
  23203. const THREE = ScriptableNodeResources.get( 'THREE' );
  23204. const TSL = ScriptableNodeResources.get( 'TSL' );
  23205. const method = this.getMethod();
  23206. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  23207. this._object = method( ...params );
  23208. const layout = this._object.layout;
  23209. if ( layout ) {
  23210. if ( layout.cache === false ) {
  23211. this._local.clear();
  23212. }
  23213. // default output
  23214. this._output.outputType = layout.outputType || null;
  23215. if ( Array.isArray( layout.elements ) ) {
  23216. for ( const element of layout.elements ) {
  23217. const id = element.id || element.name;
  23218. if ( element.inputType ) {
  23219. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  23220. this.getParameter( id ).inputType = element.inputType;
  23221. }
  23222. if ( element.outputType ) {
  23223. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  23224. this.getOutput( id ).outputType = element.outputType;
  23225. }
  23226. }
  23227. }
  23228. }
  23229. return this._object;
  23230. }
  23231. deserialize( data ) {
  23232. super.deserialize( data );
  23233. for ( const name in this.parameters ) {
  23234. let valueNode = this.parameters[ name ];
  23235. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  23236. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  23237. }
  23238. }
  23239. /**
  23240. * Returns the layout of the script.
  23241. *
  23242. * @return {Object} The script's layout.
  23243. */
  23244. getLayout() {
  23245. return this.getObject().layout;
  23246. }
  23247. /**
  23248. * Returns default node output of the script.
  23249. *
  23250. * @return {Node} The default node output.
  23251. */
  23252. getDefaultOutputNode() {
  23253. const output = this.getDefaultOutput().value;
  23254. if ( output && output.isNode ) {
  23255. return output;
  23256. }
  23257. return float();
  23258. }
  23259. /**
  23260. * Returns default output of the script.
  23261. *
  23262. * @return {ScriptableValueNode} The default output.
  23263. */
  23264. getDefaultOutput() {
  23265. return this._exec()._output;
  23266. }
  23267. /**
  23268. * Returns a function created from the node's script.
  23269. *
  23270. * @return {Function} The function representing the node's code.
  23271. */
  23272. getMethod() {
  23273. if ( this.needsUpdate ) this.dispose();
  23274. if ( this._method !== null ) return this._method;
  23275. //
  23276. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  23277. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  23278. const properties = interfaceProps.join( ', ' );
  23279. const declarations = 'var ' + properties + '; var output = {};\n';
  23280. const returns = '\nreturn { ...output, ' + properties + ' };';
  23281. const code = declarations + this.codeNode.code + returns;
  23282. //
  23283. this._method = new Function( ...parametersProps, code );
  23284. return this._method;
  23285. }
  23286. /**
  23287. * Frees all internal resources.
  23288. */
  23289. dispose() {
  23290. if ( this._method === null ) return;
  23291. if ( this._object && typeof this._object.dispose === 'function' ) {
  23292. this._object.dispose();
  23293. }
  23294. this._method = null;
  23295. this._object = null;
  23296. this._source = null;
  23297. this._value = null;
  23298. this._needsOutputUpdate = true;
  23299. this._output.value = null;
  23300. this._outputs = {};
  23301. }
  23302. setup() {
  23303. return this.getDefaultOutputNode();
  23304. }
  23305. getCacheKey( force ) {
  23306. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  23307. for ( const param in this.parameters ) {
  23308. values.push( this.parameters[ param ].getCacheKey( force ) );
  23309. }
  23310. return hashArray( values );
  23311. }
  23312. set needsUpdate( value ) {
  23313. if ( value === true ) this.dispose();
  23314. }
  23315. get needsUpdate() {
  23316. return this.source !== this._source;
  23317. }
  23318. /**
  23319. * Executes the `main` function of the script.
  23320. *
  23321. * @private
  23322. * @return {ScriptableNode} A reference to this node.
  23323. */
  23324. _exec() {
  23325. if ( this.codeNode === null ) return this;
  23326. if ( this._needsOutputUpdate === true ) {
  23327. this._value = this.call( 'main' );
  23328. this._needsOutputUpdate = false;
  23329. }
  23330. this._output.value = this._value;
  23331. return this;
  23332. }
  23333. /**
  23334. * Executes the refresh.
  23335. *
  23336. * @private
  23337. */
  23338. _refresh() {
  23339. this.needsUpdate = true;
  23340. this._exec();
  23341. this._output.refresh();
  23342. }
  23343. }
  23344. /**
  23345. * TSL function for creating a scriptable node.
  23346. *
  23347. * @function
  23348. * @param {CodeNode?} [codeNode=null] - The code node.
  23349. * @param {Object} [parameters={}] - The parameters definition.
  23350. * @returns {ScriptableNode}
  23351. */
  23352. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  23353. /** @module Fog **/
  23354. /**
  23355. * Returns a node that represents the `z` coordinate in view space
  23356. * for the current fragment. It's a different representation of the
  23357. * default depth value.
  23358. *
  23359. * This value can be part of a computation that defines how the fog
  23360. * density increases when moving away from the camera.
  23361. *
  23362. * @param {NodeBuilder} builder - The current node builder.
  23363. * @return {Node} The viewZ node.
  23364. */
  23365. function getViewZNode( builder ) {
  23366. let viewZ;
  23367. const getViewZ = builder.context.getViewZ;
  23368. if ( getViewZ !== undefined ) {
  23369. viewZ = getViewZ( this );
  23370. }
  23371. return ( viewZ || positionView.z ).negate();
  23372. }
  23373. /**
  23374. * Constructs a new range factor node.
  23375. *
  23376. * @function
  23377. * @param {Node} near - Defines the near value.
  23378. * @param {Node} far - Defines the far value.
  23379. */
  23380. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  23381. const viewZ = getViewZNode( builder );
  23382. return smoothstep( near, far, viewZ );
  23383. } );
  23384. /**
  23385. * Represents an exponential squared fog. This type of fog gives
  23386. * a clear view near the camera and a faster than exponentially
  23387. * densening fog farther from the camera.
  23388. *
  23389. * @function
  23390. * @param {Node} density - Defines the fog density.
  23391. */
  23392. const densityFogFactor = Fn( ( [ density ], builder ) => {
  23393. const viewZ = getViewZNode( builder );
  23394. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  23395. } );
  23396. /**
  23397. * This class can be used to configure a fog for the scene.
  23398. * Nodes of this type are assigned to `Scene.fogNode`.
  23399. *
  23400. * @function
  23401. * @param {Node} color - Defines the color of the fog.
  23402. * @param {Node} factor - Defines how the fog is factored in the scene.
  23403. */
  23404. const fog = Fn( ( [ color, factor ] ) => {
  23405. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  23406. } );
  23407. // Deprecated
  23408. function rangeFog( color, near, far ) { // @deprecated, r171
  23409. console.warn( 'THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  23410. return fog( color, rangeFogFactor( near, far ) );
  23411. }
  23412. function densityFog( color, density ) { // @deprecated, r171
  23413. console.warn( 'THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  23414. return fog( color, densityFogFactor( density ) );
  23415. }
  23416. /** @module RangeNode **/
  23417. let min = null;
  23418. let max = null;
  23419. /**
  23420. * `RangeNode` generates random instanced attribute data in a defined range.
  23421. * An exemplary use case for this utility node is to generate random per-instance
  23422. * colors:
  23423. * ```js
  23424. * const material = new MeshBasicNodeMaterial();
  23425. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  23426. * const mesh = new InstancedMesh( geometry, material, count );
  23427. * ```
  23428. * @augments Node
  23429. */
  23430. class RangeNode extends Node {
  23431. static get type() {
  23432. return 'RangeNode';
  23433. }
  23434. /**
  23435. * Constructs a new range node.
  23436. *
  23437. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  23438. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  23439. */
  23440. constructor( minNode = float(), maxNode = float() ) {
  23441. super();
  23442. /**
  23443. * A node defining the lower bound of the range.
  23444. *
  23445. * @type {Node<any>}
  23446. * @default float()
  23447. */
  23448. this.minNode = minNode;
  23449. /**
  23450. * A node defining the upper bound of the range.
  23451. *
  23452. * @type {Node<any>}
  23453. * @default float()
  23454. */
  23455. this.maxNode = maxNode;
  23456. }
  23457. /**
  23458. * Returns the vector length which is computed based on the range definition.
  23459. *
  23460. * @param {NodeBuilder} builder - The current node builder.
  23461. * @return {Number} The vector length.
  23462. */
  23463. getVectorLength( builder ) {
  23464. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  23465. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  23466. return minLength > maxLength ? minLength : maxLength;
  23467. }
  23468. /**
  23469. * This method is overwritten since the node type is inferred from range definition.
  23470. *
  23471. * @param {NodeBuilder} builder - The current node builder.
  23472. * @return {String} The node type.
  23473. */
  23474. getNodeType( builder ) {
  23475. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  23476. }
  23477. setup( builder ) {
  23478. const object = builder.object;
  23479. let output = null;
  23480. if ( object.count > 1 ) {
  23481. const minValue = this.minNode.value;
  23482. const maxValue = this.maxNode.value;
  23483. const minLength = builder.getTypeLength( getValueType( minValue ) );
  23484. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  23485. min = min || new Vector4();
  23486. max = max || new Vector4();
  23487. min.setScalar( 0 );
  23488. max.setScalar( 0 );
  23489. if ( minLength === 1 ) min.setScalar( minValue );
  23490. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  23491. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  23492. if ( maxLength === 1 ) max.setScalar( maxValue );
  23493. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  23494. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  23495. const stride = 4;
  23496. const length = stride * object.count;
  23497. const array = new Float32Array( length );
  23498. for ( let i = 0; i < length; i ++ ) {
  23499. const index = i % stride;
  23500. const minElementValue = min.getComponent( index );
  23501. const maxElementValue = max.getComponent( index );
  23502. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  23503. }
  23504. const nodeType = this.getNodeType( builder );
  23505. if ( object.count <= 4096 ) {
  23506. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  23507. } else {
  23508. // TODO: Improve anonymous buffer attribute creation removing this part
  23509. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  23510. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  23511. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  23512. }
  23513. } else {
  23514. output = float( 0 );
  23515. }
  23516. return output;
  23517. }
  23518. }
  23519. /**
  23520. * TSL function for creating a range node.
  23521. *
  23522. * @function
  23523. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  23524. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  23525. * @returns {RangeNode}
  23526. */
  23527. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  23528. /** @module ComputeBuiltinNode **/
  23529. /**
  23530. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  23531. * about the currently running dispatch and/or the device it is running on.
  23532. *
  23533. * This node can only be used with a WebGPU backend.
  23534. *
  23535. * @augments Node
  23536. */
  23537. class ComputeBuiltinNode extends Node {
  23538. static get type() {
  23539. return 'ComputeBuiltinNode';
  23540. }
  23541. /**
  23542. * Constructs a new compute builtin node.
  23543. *
  23544. * @param {String} builtinName - The built-in name.
  23545. * @param {String} nodeType - The node type.
  23546. */
  23547. constructor( builtinName, nodeType ) {
  23548. super( nodeType );
  23549. /**
  23550. * The built-in name.
  23551. *
  23552. * @private
  23553. * @type {String}
  23554. */
  23555. this._builtinName = builtinName;
  23556. }
  23557. /**
  23558. * This method is overwritten since hash is derived from the built-in name.
  23559. *
  23560. * @param {NodeBuilder} builder - The current node builder.
  23561. * @return {String} The hash.
  23562. */
  23563. getHash( builder ) {
  23564. return this.getBuiltinName( builder );
  23565. }
  23566. /**
  23567. * This method is overwritten since the node type is simply derived from `nodeType`..
  23568. *
  23569. * @param {NodeBuilder} builder - The current node builder.
  23570. * @return {String} The node type.
  23571. */
  23572. getNodeType( /*builder*/ ) {
  23573. return this.nodeType;
  23574. }
  23575. /**
  23576. * Sets the builtin name.
  23577. *
  23578. * @param {String} builtinName - The built-in name.
  23579. * @return {ComputeBuiltinNode} A reference to this node.
  23580. */
  23581. setBuiltinName( builtinName ) {
  23582. this._builtinName = builtinName;
  23583. return this;
  23584. }
  23585. /**
  23586. * Returns the builtin name.
  23587. *
  23588. * @param {NodeBuilder} builder - The current node builder.
  23589. * @return {String} The builtin name.
  23590. */
  23591. getBuiltinName( /*builder*/ ) {
  23592. return this._builtinName;
  23593. }
  23594. /**
  23595. * Whether the current node builder has the builtin or not.
  23596. *
  23597. * @param {NodeBuilder} builder - The current node builder.
  23598. */
  23599. hasBuiltin( builder ) {
  23600. builder.hasBuiltin( this._builtinName );
  23601. }
  23602. generate( builder, output ) {
  23603. const builtinName = this.getBuiltinName( builder );
  23604. const nodeType = this.getNodeType( builder );
  23605. if ( builder.shaderStage === 'compute' ) {
  23606. return builder.format( builtinName, nodeType, output );
  23607. } else {
  23608. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  23609. return builder.generateConst( nodeType );
  23610. }
  23611. }
  23612. serialize( data ) {
  23613. super.serialize( data );
  23614. data.global = this.global;
  23615. data._builtinName = this._builtinName;
  23616. }
  23617. deserialize( data ) {
  23618. super.deserialize( data );
  23619. this.global = data.global;
  23620. this._builtinName = data._builtinName;
  23621. }
  23622. }
  23623. /**
  23624. * TSL function for creating a compute builtin node.
  23625. *
  23626. * @function
  23627. * @param {String} name - The built-in name.
  23628. * @param {String} nodeType - The node type.
  23629. * @returns {ComputeBuiltinNode}
  23630. */
  23631. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  23632. /**
  23633. * TSL function for creating a `numWorkgroups` builtin node.
  23634. * Represents the number of workgroups dispatched by the compute shader.
  23635. * ```js
  23636. * // Run 512 invocations/threads with a workgroup size of 128.
  23637. * const computeFn = Fn(() => {
  23638. *
  23639. * // numWorkgroups.x = 4
  23640. * storageBuffer.element(0).assign(numWorkgroups.x)
  23641. *
  23642. * })().compute(512, [128]);
  23643. *
  23644. * // Run 512 invocations/threads with the default workgroup size of 64.
  23645. * const computeFn = Fn(() => {
  23646. *
  23647. * // numWorkgroups.x = 8
  23648. * storageBuffer.element(0).assign(numWorkgroups.x)
  23649. *
  23650. * })().compute(512);
  23651. * ```
  23652. *
  23653. * @function
  23654. * @returns {ComputeBuiltinNode<uvec3>}
  23655. */
  23656. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  23657. /**
  23658. * TSL function for creating a `workgroupId` builtin node.
  23659. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  23660. * ```js
  23661. * // Execute 12 compute threads with a workgroup size of 3.
  23662. * const computeFn = Fn( () => {
  23663. *
  23664. * If( workgroupId.x.modInt( 2 ).equal( 0 ), () => {
  23665. *
  23666. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  23667. *
  23668. * } ).Else( () => {
  23669. *
  23670. * storageBuffer.element( instanceIndex ).assign( 0 );
  23671. *
  23672. * } );
  23673. *
  23674. * } )().compute( 12, [ 3 ] );
  23675. *
  23676. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  23677. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  23678. * ```
  23679. *
  23680. * @function
  23681. * @returns {ComputeBuiltinNode<uvec3>}
  23682. */
  23683. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  23684. /**
  23685. * TSL function for creating a `localId` builtin node. A non-linearized 3-dimensional
  23686. * representation of the current invocation's position within a 3D workgroup grid.
  23687. *
  23688. * @function
  23689. * @returns {ComputeBuiltinNode<uvec3>}
  23690. */
  23691. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  23692. /**
  23693. * TSL function for creating a `subgroupSize` builtin node. A device dependent variable
  23694. * that exposes the size of the current invocation's subgroup.
  23695. *
  23696. * @function
  23697. * @returns {ComputeBuiltinNode<uint>}
  23698. */
  23699. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  23700. /** @module BarrierNode **/
  23701. /**
  23702. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  23703. *
  23704. * This node can only be used with a WebGPU backend.
  23705. *
  23706. * @augments Node
  23707. */
  23708. class BarrierNode extends Node {
  23709. /**
  23710. * Constructs a new barrier node.
  23711. *
  23712. * @param {String} scope - The scope defines the behavior of the node.
  23713. */
  23714. constructor( scope ) {
  23715. super();
  23716. this.scope = scope;
  23717. }
  23718. generate( builder ) {
  23719. const { scope } = this;
  23720. const { renderer } = builder;
  23721. if ( renderer.backend.isWebGLBackend === true ) {
  23722. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  23723. } else {
  23724. builder.addLineFlowCode( `${scope}Barrier()`, this );
  23725. }
  23726. }
  23727. }
  23728. /**
  23729. * TSL function for creating a barrier node.
  23730. *
  23731. * @function
  23732. * @param {String} scope - The scope defines the behavior of the node..
  23733. * @returns {BarrierNode}
  23734. */
  23735. const barrier = nodeProxy( BarrierNode );
  23736. /**
  23737. * TSL function for creating a workgroup barrier. All compute shader
  23738. * invocations must wait for each invocation within a workgroup to
  23739. * complete before the barrier can be surpassed.
  23740. *
  23741. * @function
  23742. * @returns {BarrierNode}
  23743. */
  23744. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  23745. /**
  23746. * TSL function for creating a storage barrier. All invocations must
  23747. * wait for each access to variables within the 'storage' address space
  23748. * to complete before the barrier can be passed.
  23749. *
  23750. * @function
  23751. * @returns {BarrierNode}
  23752. */
  23753. const storageBarrier = () => barrier( 'storage' ).append();
  23754. /**
  23755. * TSL function for creating a texture barrier. All invocations must
  23756. * wait for each access to variables within the 'texture' address space
  23757. * to complete before the barrier can be passed.
  23758. *
  23759. * @function
  23760. * @returns {BarrierNode}
  23761. */
  23762. const textureBarrier = () => barrier( 'texture' ).append();
  23763. /** @module WorkgroupInfoNode **/
  23764. /**
  23765. * Represents an element of a 'workgroup' scoped buffer.
  23766. *
  23767. * @augments ArrayElementNode
  23768. */
  23769. class WorkgroupInfoElementNode extends ArrayElementNode {
  23770. /**
  23771. * Constructs a new workgroup info element node.
  23772. *
  23773. * @param {Node} workgroupInfoNode - The workgroup info node.
  23774. * @param {Node} indexNode - The index node that defines the element access.
  23775. */
  23776. constructor( workgroupInfoNode, indexNode ) {
  23777. super( workgroupInfoNode, indexNode );
  23778. /**
  23779. * This flag can be used for type testing.
  23780. *
  23781. * @type {Boolean}
  23782. * @readonly
  23783. * @default true
  23784. */
  23785. this.isWorkgroupInfoElementNode = true;
  23786. }
  23787. generate( builder, output ) {
  23788. let snippet;
  23789. const isAssignContext = builder.context.assign;
  23790. snippet = super.generate( builder );
  23791. if ( isAssignContext !== true ) {
  23792. const type = this.getNodeType( builder );
  23793. snippet = builder.format( snippet, type, output );
  23794. }
  23795. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  23796. return snippet;
  23797. }
  23798. }
  23799. /**
  23800. * A node allowing the user to create a 'workgroup' scoped buffer within the
  23801. * context of a compute shader. Typically, workgroup scoped buffers are
  23802. * created to hold data that is transfered from a global storage scope into
  23803. * a local workgroup scope. For invocations within a workgroup, data
  23804. * access speeds on 'workgroup' scoped buffers can be significantly faster
  23805. * than similar access operations on globally accessible storage buffers.
  23806. *
  23807. * This node can only be used with a WebGPU backend.
  23808. *
  23809. * @augments Node
  23810. */
  23811. class WorkgroupInfoNode extends Node {
  23812. /**
  23813. * Constructs a new buffer scoped to type scope.
  23814. *
  23815. * @param {String} scope - TODO.
  23816. * @param {String} bufferType - The data type of a 'workgroup' scoped buffer element.
  23817. * @param {Number} [bufferCount=0] - The number of elements in the buffer.
  23818. */
  23819. constructor( scope, bufferType, bufferCount = 0 ) {
  23820. super( bufferType );
  23821. /**
  23822. * The buffer type.
  23823. *
  23824. * @type {String}
  23825. */
  23826. this.bufferType = bufferType;
  23827. /**
  23828. * The buffer count.
  23829. *
  23830. * @type {Number}
  23831. * @default 0
  23832. */
  23833. this.bufferCount = bufferCount;
  23834. /**
  23835. * This flag can be used for type testing.
  23836. *
  23837. * @type {Boolean}
  23838. * @readonly
  23839. * @default true
  23840. */
  23841. this.isWorkgroupInfoNode = true;
  23842. /**
  23843. * The data type of the array buffer.
  23844. *
  23845. * @type {String}
  23846. */
  23847. this.elementType = bufferType;
  23848. /**
  23849. * TODO.
  23850. *
  23851. * @type {String}
  23852. */
  23853. this.scope = scope;
  23854. }
  23855. /**
  23856. * Sets the name/label of this node.
  23857. *
  23858. * @param {String} name - The name to set.
  23859. * @return {WorkgroupInfoNode} A reference to this node.
  23860. */
  23861. label( name ) {
  23862. this.name = name;
  23863. return this;
  23864. }
  23865. /**
  23866. * Sets the scope of this node.
  23867. *
  23868. * @param {String} scope - The scope to set.
  23869. * @return {WorkgroupInfoNode} A reference to this node.
  23870. */
  23871. setScope( scope ) {
  23872. this.scope = scope;
  23873. return this;
  23874. }
  23875. /**
  23876. * The data type of the array buffer.
  23877. *
  23878. * @return {String} The element type.
  23879. */
  23880. getElementType() {
  23881. return this.elementType;
  23882. }
  23883. /**
  23884. * Overwrites the default implementation since the input type
  23885. * is inferred from the scope.
  23886. *
  23887. * @param {NodeBuilder} builder - The current node builder.
  23888. * @return {String} The input type.
  23889. */
  23890. getInputType( /*builder*/ ) {
  23891. return `${this.scope}Array`;
  23892. }
  23893. /**
  23894. * This method can be used to access elements via an index node.
  23895. *
  23896. * @param {IndexNode} indexNode - indexNode.
  23897. * @return {WorkgroupInfoElementNode} A reference to an element.
  23898. */
  23899. element( indexNode ) {
  23900. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  23901. }
  23902. generate( builder ) {
  23903. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  23904. }
  23905. }
  23906. /**
  23907. * TSL function for creating a workgroup info node.
  23908. * Creates a new 'workgroup' scoped array buffer.
  23909. *
  23910. * @function
  23911. * @param {String} type - The data type of a 'workgroup' scoped buffer element.
  23912. * @param {Number} [count=0] - The number of elements in the buffer.
  23913. * @returns {WorkgroupInfoNode}
  23914. */
  23915. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  23916. /** @module AtomicFunctionNode **/
  23917. /**
  23918. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  23919. * within a shader. In an atomic function, any modifiation to an atomic variable will
  23920. * occur as an indivisble step with a defined order relative to other modifications.
  23921. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  23922. * atomic operations will not interfer with each other.
  23923. *
  23924. * This node can only be used with a WebGPU backend.
  23925. *
  23926. * @augments TempNode
  23927. */
  23928. class AtomicFunctionNode extends TempNode {
  23929. static get type() {
  23930. return 'AtomicFunctionNode';
  23931. }
  23932. /**
  23933. * Constructs a new atomic function node.
  23934. *
  23935. * @param {String} method - The signature of the atomic function to construct.
  23936. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  23937. * @param {Node} valueNode - The value that mutates the atomic variable.
  23938. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  23939. */
  23940. constructor( method, pointerNode, valueNode, storeNode = null ) {
  23941. super( 'uint' );
  23942. /**
  23943. * The signature of the atomic function to construct.
  23944. *
  23945. * @type {String}
  23946. */
  23947. this.method = method;
  23948. /**
  23949. * An atomic variable or element of an atomic buffer.
  23950. *
  23951. * @type {Node}
  23952. */
  23953. this.pointerNode = pointerNode;
  23954. /**
  23955. * A value that modifies the atomic variable.
  23956. *
  23957. * @type {Node}
  23958. */
  23959. this.valueNode = valueNode;
  23960. /**
  23961. * A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  23962. *
  23963. * @type {Node?}
  23964. * @default null
  23965. */
  23966. this.storeNode = storeNode;
  23967. }
  23968. /**
  23969. * Overwrites the default implementation to return the type of
  23970. * the pointer node.
  23971. *
  23972. * @param {NodeBuilder} builder - The current node builder.
  23973. * @return {String} The input type.
  23974. */
  23975. getInputType( builder ) {
  23976. return this.pointerNode.getNodeType( builder );
  23977. }
  23978. /**
  23979. * Overwritten since the node type is inferred from the input type.
  23980. *
  23981. * @param {NodeBuilder} builder - The current node builder.
  23982. * @return {String} The node type.
  23983. */
  23984. getNodeType( builder ) {
  23985. return this.getInputType( builder );
  23986. }
  23987. generate( builder ) {
  23988. const method = this.method;
  23989. const type = this.getNodeType( builder );
  23990. const inputType = this.getInputType( builder );
  23991. const a = this.pointerNode;
  23992. const b = this.valueNode;
  23993. const params = [];
  23994. params.push( `&${ a.build( builder, inputType ) }` );
  23995. params.push( b.build( builder, inputType ) );
  23996. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  23997. if ( this.storeNode !== null ) {
  23998. const varSnippet = this.storeNode.build( builder, inputType );
  23999. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this );
  24000. } else {
  24001. builder.addLineFlowCode( methodSnippet, this );
  24002. }
  24003. }
  24004. }
  24005. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  24006. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  24007. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  24008. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  24009. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  24010. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  24011. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  24012. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  24013. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  24014. /**
  24015. * TSL function for creating an atomic function node.
  24016. *
  24017. * @function
  24018. * @param {String} method - The signature of the atomic function to construct.
  24019. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24020. * @param {Node} valueNode - The value that mutates the atomic variable.
  24021. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24022. * @returns {AtomicFunctionNode}
  24023. */
  24024. const atomicNode = nodeProxy( AtomicFunctionNode );
  24025. /**
  24026. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  24027. *
  24028. * @function
  24029. * @param {String} method - The signature of the atomic function to construct.
  24030. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24031. * @param {Node} valueNode - The value that mutates the atomic variable.
  24032. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24033. * @returns {AtomicFunctionNode}
  24034. */
  24035. const atomicFunc = ( method, pointerNode, valueNode, storeNode = null ) => {
  24036. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  24037. node.append();
  24038. return node;
  24039. };
  24040. /**
  24041. * Stores a value in the atomic variable.
  24042. *
  24043. * @function
  24044. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24045. * @param {Node} valueNode - The value that mutates the atomic variable.
  24046. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24047. * @returns {AtomicFunctionNode}
  24048. */
  24049. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  24050. /**
  24051. * Increments the value stored in the atomic variable.
  24052. *
  24053. * @function
  24054. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24055. * @param {Node} valueNode - The value that mutates the atomic variable.
  24056. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24057. * @returns {AtomicFunctionNode}
  24058. */
  24059. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  24060. /**
  24061. * Decrements the value stored in the atomic variable.
  24062. *
  24063. * @function
  24064. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24065. * @param {Node} valueNode - The value that mutates the atomic variable.
  24066. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24067. * @returns {AtomicFunctionNode}
  24068. */
  24069. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  24070. /**
  24071. * Stores in an atomic variable the maximum between its current value and a parameter.
  24072. *
  24073. * @function
  24074. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24075. * @param {Node} valueNode - The value that mutates the atomic variable.
  24076. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24077. * @returns {AtomicFunctionNode}
  24078. */
  24079. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  24080. /**
  24081. * Stores in an atomic variable the minimum between its current value and a parameter.
  24082. *
  24083. * @function
  24084. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24085. * @param {Node} valueNode - The value that mutates the atomic variable.
  24086. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24087. * @returns {AtomicFunctionNode}
  24088. */
  24089. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  24090. /**
  24091. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  24092. *
  24093. * @function
  24094. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24095. * @param {Node} valueNode - The value that mutates the atomic variable.
  24096. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24097. * @returns {AtomicFunctionNode}
  24098. */
  24099. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  24100. /**
  24101. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  24102. *
  24103. * @function
  24104. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24105. * @param {Node} valueNode - The value that mutates the atomic variable.
  24106. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24107. * @returns {AtomicFunctionNode}
  24108. */
  24109. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  24110. /**
  24111. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  24112. *
  24113. * @function
  24114. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24115. * @param {Node} valueNode - The value that mutates the atomic variable.
  24116. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24117. * @returns {AtomicFunctionNode}
  24118. */
  24119. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  24120. /** @module Lights **/
  24121. let uniformsLib;
  24122. function getLightData( light ) {
  24123. uniformsLib = uniformsLib || new WeakMap();
  24124. let uniforms = uniformsLib.get( light );
  24125. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  24126. return uniforms;
  24127. }
  24128. /**
  24129. * TSL function for getting a shadow matrix uniform node for the given light.
  24130. *
  24131. * @function
  24132. * @param {Light} light -The light source.
  24133. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  24134. */
  24135. function lightShadowMatrix( light ) {
  24136. const data = getLightData( light );
  24137. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( () => {
  24138. if ( light.castShadow !== true ) {
  24139. light.shadow.updateMatrices( light );
  24140. }
  24141. return light.shadow.matrix;
  24142. } ) );
  24143. }
  24144. /**
  24145. * TSL function for getting projected uv coordinates for the given light.
  24146. * Relevant when using maps with spot lights.
  24147. *
  24148. * @function
  24149. * @param {Light} light -The light source.
  24150. * @returns {Node<vec3>} The projected uvs.
  24151. */
  24152. function lightProjectionUV( light ) {
  24153. const data = getLightData( light );
  24154. if ( data.projectionUV === undefined ) {
  24155. const spotLightCoord = lightShadowMatrix( light ).mul( positionWorld );
  24156. data.projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  24157. }
  24158. return data.projectionUV;
  24159. }
  24160. /**
  24161. * TSL function for getting the position in world space for the given light.
  24162. *
  24163. * @function
  24164. * @param {Light} light -The light source.
  24165. * @returns {UniformNode<vec3>} The light's position in world space.
  24166. */
  24167. function lightPosition( light ) {
  24168. const data = getLightData( light );
  24169. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  24170. }
  24171. /**
  24172. * TSL function for getting the light target position in world space for the given light.
  24173. *
  24174. * @function
  24175. * @param {Light} light -The light source.
  24176. * @returns {UniformNode<vec3>} The light target position in world space.
  24177. */
  24178. function lightTargetPosition( light ) {
  24179. const data = getLightData( light );
  24180. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  24181. }
  24182. /**
  24183. * TSL function for getting the position in view space for the given light.
  24184. *
  24185. * @function
  24186. * @param {Light} light -The light source.
  24187. * @returns {UniformNode<vec3>} The light's position in view space.
  24188. */
  24189. function lightViewPosition( light ) {
  24190. const data = getLightData( light );
  24191. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  24192. self.value = self.value || new Vector3();
  24193. self.value.setFromMatrixPosition( light.matrixWorld );
  24194. self.value.applyMatrix4( camera.matrixWorldInverse );
  24195. } ) );
  24196. }
  24197. /**
  24198. * TSL function for getting the light target direction for the given light.
  24199. *
  24200. * @function
  24201. * @param {Light} light -The light source.
  24202. * @returns {Node<vec3>} The light's target direction.
  24203. */
  24204. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  24205. /** @module LightsNode **/
  24206. const sortLights = ( lights ) => {
  24207. return lights.sort( ( a, b ) => a.id - b.id );
  24208. };
  24209. const getLightNodeById = ( id, lightNodes ) => {
  24210. for ( const lightNode of lightNodes ) {
  24211. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  24212. return lightNode;
  24213. }
  24214. }
  24215. return null;
  24216. };
  24217. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  24218. /**
  24219. * This node represents the scene's lighting and manages the lighting model's life cycle
  24220. * for the current build 3D object. It is responsible for computing the total outgoing
  24221. * light in a given lighting context.
  24222. *
  24223. * @augments Node
  24224. */
  24225. class LightsNode extends Node {
  24226. static get type() {
  24227. return 'LightsNode';
  24228. }
  24229. /**
  24230. * Constructs a new lights node.
  24231. */
  24232. constructor() {
  24233. super( 'vec3' );
  24234. /**
  24235. * A node representing the total diffuse light.
  24236. *
  24237. * @type {Node<vec3>}
  24238. */
  24239. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  24240. /**
  24241. * A node representing the total specular light.
  24242. *
  24243. * @type {Node<vec3>}
  24244. */
  24245. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  24246. /**
  24247. * A node representing the outgoing light.
  24248. *
  24249. * @type {Node<vec3>}
  24250. */
  24251. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  24252. /**
  24253. * An array representing the lights in the scene.
  24254. *
  24255. * @private
  24256. * @type {Array<Light>}
  24257. */
  24258. this._lights = [];
  24259. /**
  24260. * For each light in the scene, this node will create a
  24261. * corresponding light node.
  24262. *
  24263. * @private
  24264. * @type {Array<LightingNode>?}
  24265. * @default null
  24266. */
  24267. this._lightNodes = null;
  24268. /**
  24269. * A hash for identifying the current light nodes setup.
  24270. *
  24271. * @private
  24272. * @type {String?}
  24273. * @default null
  24274. */
  24275. this._lightNodesHash = null;
  24276. /**
  24277. * `LightsNode` sets this property to `true` by default.
  24278. *
  24279. * @type {Boolean}
  24280. * @default true
  24281. */
  24282. this.global = true;
  24283. }
  24284. /**
  24285. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  24286. * light IDs into the cache key.
  24287. *
  24288. * @return {Number} The custom cache key.
  24289. */
  24290. customCacheKey() {
  24291. const lightIDs = [];
  24292. const lights = this._lights;
  24293. for ( let i = 0; i < lights.length; i ++ ) {
  24294. lightIDs.push( lights[ i ].id );
  24295. }
  24296. return hashArray( lightIDs );
  24297. }
  24298. /**
  24299. * Computes a hash value for identifying the current light nodes setup.
  24300. *
  24301. * @param {NodeBuilder} builder - A reference to the current node builder.
  24302. * @return {String} The computed hash.
  24303. */
  24304. getHash( builder ) {
  24305. if ( this._lightNodesHash === null ) {
  24306. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  24307. const hash = [];
  24308. for ( const lightNode of this._lightNodes ) {
  24309. hash.push( lightNode.getSelf().getHash() );
  24310. }
  24311. this._lightNodesHash = 'lights-' + hash.join( ',' );
  24312. }
  24313. return this._lightNodesHash;
  24314. }
  24315. analyze( builder ) {
  24316. const properties = builder.getDataFromNode( this );
  24317. for ( const node of properties.nodes ) {
  24318. node.build( builder );
  24319. }
  24320. }
  24321. /**
  24322. * Creates lighting nodes for each scene light. This makes it possible to further
  24323. * process lights in the node system.
  24324. *
  24325. * @param {NodeBuilder} builder - A reference to the current node builder.
  24326. */
  24327. setupLightsNode( builder ) {
  24328. const lightNodes = [];
  24329. const previousLightNodes = this._lightNodes;
  24330. const lights = sortLights( this._lights );
  24331. const nodeLibrary = builder.renderer.library;
  24332. for ( const light of lights ) {
  24333. if ( light.isNode ) {
  24334. lightNodes.push( nodeObject( light ) );
  24335. } else {
  24336. let lightNode = null;
  24337. if ( previousLightNodes !== null ) {
  24338. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  24339. }
  24340. if ( lightNode === null ) {
  24341. // find the corresponding node type for a given light
  24342. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  24343. if ( lightNodeClass === null ) {
  24344. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  24345. continue;
  24346. }
  24347. let lightNode = null;
  24348. if ( ! _lightsNodeRef.has( light ) ) {
  24349. lightNode = nodeObject( new lightNodeClass( light ) );
  24350. _lightsNodeRef.set( light, lightNode );
  24351. } else {
  24352. lightNode = _lightsNodeRef.get( light );
  24353. }
  24354. lightNodes.push( lightNode );
  24355. }
  24356. }
  24357. }
  24358. this._lightNodes = lightNodes;
  24359. }
  24360. /**
  24361. * Setups the internal lights by building all respective
  24362. * light nodes.
  24363. *
  24364. * @param {NodeBuilder} builder - A reference to the current node builder.
  24365. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  24366. */
  24367. setupLights( builder, lightNodes ) {
  24368. for ( const lightNode of lightNodes ) {
  24369. lightNode.build( builder );
  24370. }
  24371. }
  24372. /**
  24373. * The implementation makes sure that for each light in the scene
  24374. * there is a corresponding light node. By building the light nodes
  24375. * and evaluating the lighting model the outgoing light is computed.
  24376. *
  24377. * @param {NodeBuilder} builder - A reference to the current node builder.
  24378. * @return {Node<vec3>} A node representing the outgoing light.
  24379. */
  24380. setup( builder ) {
  24381. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  24382. const context = builder.context;
  24383. const lightingModel = context.lightingModel;
  24384. let outgoingLightNode = this.outgoingLightNode;
  24385. if ( lightingModel ) {
  24386. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  24387. context.outgoingLight = outgoingLightNode;
  24388. const stack = builder.addStack();
  24389. //
  24390. const properties = builder.getDataFromNode( this );
  24391. properties.nodes = stack.nodes;
  24392. //
  24393. lightingModel.start( context, stack, builder );
  24394. // lights
  24395. this.setupLights( builder, _lightNodes );
  24396. //
  24397. lightingModel.indirect( context, stack, builder );
  24398. //
  24399. const { backdrop, backdropAlpha } = context;
  24400. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  24401. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  24402. if ( backdrop !== null ) {
  24403. if ( backdropAlpha !== null ) {
  24404. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  24405. } else {
  24406. totalDiffuse = vec3( backdrop );
  24407. }
  24408. context.material.transparent = true;
  24409. }
  24410. totalDiffuseNode.assign( totalDiffuse );
  24411. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  24412. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  24413. //
  24414. lightingModel.finish( context, stack, builder );
  24415. //
  24416. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  24417. }
  24418. return outgoingLightNode;
  24419. }
  24420. /**
  24421. * Configures this node with an array of lights.
  24422. *
  24423. * @param {Array<Light>} lights - An array of lights.
  24424. * @return {LightsNode} A reference to this node.
  24425. */
  24426. setLights( lights ) {
  24427. this._lights = lights;
  24428. this._lightNodes = null;
  24429. this._lightNodesHash = null;
  24430. return this;
  24431. }
  24432. /**
  24433. * Returns an array of the scene's lights.
  24434. *
  24435. * @return {Array<Light>} The scene's lights.
  24436. */
  24437. getLights() {
  24438. return this._lights;
  24439. }
  24440. /**
  24441. * Whether the scene has lights or not.
  24442. *
  24443. * @type {Boolean}
  24444. */
  24445. get hasLights() {
  24446. return this._lights.length > 0;
  24447. }
  24448. }
  24449. /**
  24450. * TSL function for creating an instance of `LightsNode` and configuring
  24451. * it with the given array of lights.
  24452. *
  24453. * @function
  24454. * @param {Array<Light>} lights - An array of lights.
  24455. * @return {LightsNode} The created lights node.
  24456. */
  24457. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  24458. /** @module ShadowBaseNode **/
  24459. /**
  24460. * Base class for all shadow nodes.
  24461. *
  24462. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  24463. * Lighting nodes might share the same shadow node type or use specific ones depending on
  24464. * their requirements.
  24465. *
  24466. * @augments Node
  24467. */
  24468. class ShadowBaseNode extends Node {
  24469. static get type() {
  24470. return 'ShadowBaseNode';
  24471. }
  24472. /**
  24473. * Constructs a new shadow base node.
  24474. *
  24475. * @param {Light} light - The shadow casting light.
  24476. */
  24477. constructor( light ) {
  24478. super();
  24479. /**
  24480. * The shadow casting light.
  24481. *
  24482. * @type {Light}
  24483. */
  24484. this.light = light;
  24485. /**
  24486. * Overwritten since shadows are updated by default per render.
  24487. *
  24488. * @type {String}
  24489. * @default 'render'
  24490. */
  24491. this.updateBeforeType = NodeUpdateType.RENDER;
  24492. /**
  24493. * This flag can be used for type testing.
  24494. *
  24495. * @type {Boolean}
  24496. * @readonly
  24497. * @default true
  24498. */
  24499. this.isShadowBaseNode = true;
  24500. }
  24501. /**
  24502. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  24503. *
  24504. * @param {(NodeBuilder|{Material})} object - A configuration object that must at least hold a material reference.
  24505. */
  24506. setupShadowPosition( { material } ) {
  24507. // Use assign inside an Fn()
  24508. shadowPositionWorld.assign( material.shadowPositionNode || positionWorld );
  24509. }
  24510. /**
  24511. * Can be called when the shadow isn't required anymore. That can happen when
  24512. * a lighting node stops casting shadows by setting {@link Object3D#castShadow}
  24513. * to `false`.
  24514. */
  24515. dispose() {
  24516. this.updateBeforeType = NodeUpdateType.NONE;
  24517. }
  24518. }
  24519. /**
  24520. * TSL object that represents the vertex position in world space during the shadow pass.
  24521. *
  24522. * @type {Node<vec3>}
  24523. */
  24524. const shadowPositionWorld = /*@__PURE__*/ vec3().toVar( 'shadowPositionWorld' );
  24525. /** @module RendererUtils **/
  24526. /**
  24527. * Saves the state of the given renderer and stores it into the given state object.
  24528. *
  24529. * If not state object is provided, the function creates one.
  24530. *
  24531. * @function
  24532. * @param {Renderer} renderer - The renderer.
  24533. * @param {Object} [state={}] - The state.
  24534. * @return {Object} The state.
  24535. */
  24536. function saveRendererState( renderer, state = {} ) {
  24537. state.toneMapping = renderer.toneMapping;
  24538. state.toneMappingExposure = renderer.toneMappingExposure;
  24539. state.outputColorSpace = renderer.outputColorSpace;
  24540. state.renderTarget = renderer.getRenderTarget();
  24541. state.activeCubeFace = renderer.getActiveCubeFace();
  24542. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  24543. state.renderObjectFunction = renderer.getRenderObjectFunction();
  24544. state.pixelRatio = renderer.getPixelRatio();
  24545. state.mrt = renderer.getMRT();
  24546. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  24547. state.clearAlpha = renderer.getClearAlpha();
  24548. state.autoClear = renderer.autoClear;
  24549. state.scissorTest = renderer.getScissorTest();
  24550. return state;
  24551. }
  24552. /**
  24553. * Saves the state of the given renderer and stores it into the given state object.
  24554. * Besides, the function also resets the state of the renderer to its default values.
  24555. *
  24556. * If not state object is provided, the function creates one.
  24557. *
  24558. * @function
  24559. * @param {Renderer} renderer - The renderer.
  24560. * @param {Object} [state={}] - The state.
  24561. * @return {Object} The state.
  24562. */
  24563. function resetRendererState( renderer, state ) {
  24564. state = saveRendererState( renderer, state );
  24565. renderer.setMRT( null );
  24566. renderer.setRenderObjectFunction( null );
  24567. renderer.setClearColor( 0x000000, 1 );
  24568. renderer.autoClear = true;
  24569. return state;
  24570. }
  24571. /**
  24572. * Restores the state of the given renderer from the given state object.
  24573. *
  24574. * @function
  24575. * @param {Renderer} renderer - The renderer.
  24576. * @param {Object} state - The state to restore.
  24577. */
  24578. function restoreRendererState( renderer, state ) {
  24579. renderer.toneMapping = state.toneMapping;
  24580. renderer.toneMappingExposure = state.toneMappingExposure;
  24581. renderer.outputColorSpace = state.outputColorSpace;
  24582. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  24583. renderer.setRenderObjectFunction( state.renderObjectFunction );
  24584. renderer.setPixelRatio( state.pixelRatio );
  24585. renderer.setMRT( state.mrt );
  24586. renderer.setClearColor( state.clearColor, state.clearAlpha );
  24587. renderer.autoClear = state.autoClear;
  24588. renderer.setScissorTest( state.scissorTest );
  24589. }
  24590. /**
  24591. * Saves the state of the given scene and stores it into the given state object.
  24592. *
  24593. * If not state object is provided, the function creates one.
  24594. *
  24595. * @function
  24596. * @param {Scene} scene - The scene.
  24597. * @param {Object} [state={}] - The state.
  24598. * @return {Object} The state.
  24599. */
  24600. function saveSceneState( scene, state = {} ) {
  24601. state.background = scene.background;
  24602. state.backgroundNode = scene.backgroundNode;
  24603. state.overrideMaterial = scene.overrideMaterial;
  24604. return state;
  24605. }
  24606. /**
  24607. * Saves the state of the given scene and stores it into the given state object.
  24608. * Besides, the function also resets the state of the scene to its default values.
  24609. *
  24610. * If not state object is provided, the function creates one.
  24611. *
  24612. * @function
  24613. * @param {Scene} scene - The scene.
  24614. * @param {Object} [state={}] - The state.
  24615. * @return {Object} The state.
  24616. */
  24617. function resetSceneState( scene, state ) {
  24618. state = saveSceneState( scene, state );
  24619. scene.background = null;
  24620. scene.backgroundNode = null;
  24621. scene.overrideMaterial = null;
  24622. return state;
  24623. }
  24624. /**
  24625. * Restores the state of the given scene from the given state object.
  24626. *
  24627. * @function
  24628. * @param {Scene} scene - The scene.
  24629. * @param {Object} state - The state to restore.
  24630. */
  24631. function restoreSceneState( scene, state ) {
  24632. scene.background = state.background;
  24633. scene.backgroundNode = state.backgroundNode;
  24634. scene.overrideMaterial = state.overrideMaterial;
  24635. }
  24636. /**
  24637. * Saves the state of the given renderer and scene and stores it into the given state object.
  24638. *
  24639. * If not state object is provided, the function creates one.
  24640. *
  24641. * @function
  24642. * @param {Renderer} renderer - The renderer.
  24643. * @param {Scene} scene - The scene.
  24644. * @param {Object} [state={}] - The state.
  24645. * @return {Object} The state.
  24646. */
  24647. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  24648. state = saveRendererState( renderer, state );
  24649. state = saveSceneState( scene, state );
  24650. return state;
  24651. }
  24652. /**
  24653. * Saves the state of the given renderer and scene and stores it into the given state object.
  24654. * Besides, the function also resets the state of the renderer and scene to its default values.
  24655. *
  24656. * If not state object is provided, the function creates one.
  24657. *
  24658. * @function
  24659. * @param {Renderer} renderer - The renderer.
  24660. * @param {Scene} scene - The scene.
  24661. * @param {Object} [state={}] - The state.
  24662. * @return {Object} The state.
  24663. */
  24664. function resetRendererAndSceneState( renderer, scene, state ) {
  24665. state = resetRendererState( renderer, state );
  24666. state = resetSceneState( scene, state );
  24667. return state;
  24668. }
  24669. /**
  24670. * Restores the state of the given renderer and scene from the given state object.
  24671. *
  24672. * @function
  24673. * @param {Renderer} renderer - The renderer.
  24674. * @param {Scene} scene - The scene.
  24675. * @param {Object} state - The state to restore.
  24676. */
  24677. function restoreRendererAndSceneState( renderer, scene, state ) {
  24678. restoreRendererState( renderer, state );
  24679. restoreSceneState( scene, state );
  24680. }
  24681. var RendererUtils = /*#__PURE__*/Object.freeze({
  24682. __proto__: null,
  24683. resetRendererAndSceneState: resetRendererAndSceneState,
  24684. resetRendererState: resetRendererState,
  24685. resetSceneState: resetSceneState,
  24686. restoreRendererAndSceneState: restoreRendererAndSceneState,
  24687. restoreRendererState: restoreRendererState,
  24688. restoreSceneState: restoreSceneState,
  24689. saveRendererAndSceneState: saveRendererAndSceneState,
  24690. saveRendererState: saveRendererState,
  24691. saveSceneState: saveSceneState
  24692. });
  24693. /** @module ShadowNode **/
  24694. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  24695. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  24696. let dist = positionWorld.sub( position ).length();
  24697. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  24698. dist = dist.saturate(); // clamp to [ 0, 1 ]
  24699. return dist;
  24700. } );
  24701. const linearShadowDistance = ( light ) => {
  24702. const camera = light.shadow.camera;
  24703. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  24704. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  24705. const referencePosition = objectPosition( light );
  24706. return linearDistance( referencePosition, nearDistance, farDistance );
  24707. };
  24708. const getShadowMaterial = ( light ) => {
  24709. let material = shadowMaterialLib.get( light );
  24710. if ( material === undefined ) {
  24711. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  24712. material = new NodeMaterial();
  24713. material.colorNode = vec4( 0, 0, 0, 1 );
  24714. material.depthNode = depthNode;
  24715. material.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  24716. material.name = 'ShadowMaterial';
  24717. material.fog = false;
  24718. shadowMaterialLib.set( light, material );
  24719. }
  24720. return material;
  24721. };
  24722. /**
  24723. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  24724. * with a binary `[0,1]` result.
  24725. *
  24726. * @method
  24727. * @param {Object} inputs - The input parameter object.
  24728. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  24729. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  24730. * @return {Node<float>} The filtering result.
  24731. */
  24732. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  24733. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  24734. } );
  24735. /**
  24736. * A shadow filtering function performing PCF filtering.
  24737. *
  24738. * @method
  24739. * @param {Object} inputs - The input parameter object.
  24740. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  24741. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  24742. * @param {LightShadow} inputs.shadow - The light shadow.
  24743. * @return {Node<float>} The filtering result.
  24744. */
  24745. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  24746. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  24747. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  24748. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  24749. const texelSize = vec2( 1 ).div( mapSize );
  24750. const dx0 = texelSize.x.negate().mul( radius );
  24751. const dy0 = texelSize.y.negate().mul( radius );
  24752. const dx1 = texelSize.x.mul( radius );
  24753. const dy1 = texelSize.y.mul( radius );
  24754. const dx2 = dx0.div( 2 );
  24755. const dy2 = dy0.div( 2 );
  24756. const dx3 = dx1.div( 2 );
  24757. const dy3 = dy1.div( 2 );
  24758. return add(
  24759. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  24760. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  24761. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  24762. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  24763. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  24764. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  24765. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  24766. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  24767. depthCompare( shadowCoord.xy, shadowCoord.z ),
  24768. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  24769. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  24770. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  24771. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  24772. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  24773. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  24774. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  24775. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  24776. ).mul( 1 / 17 );
  24777. } );
  24778. /**
  24779. * A shadow filtering function performing PCF soft filtering.
  24780. *
  24781. * @method
  24782. * @param {Object} inputs - The input parameter object.
  24783. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  24784. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  24785. * @param {LightShadow} inputs.shadow - The light shadow.
  24786. * @return {Node<float>} The filtering result.
  24787. */
  24788. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  24789. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  24790. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  24791. const texelSize = vec2( 1 ).div( mapSize );
  24792. const dx = texelSize.x;
  24793. const dy = texelSize.y;
  24794. const uv = shadowCoord.xy;
  24795. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  24796. uv.subAssign( f.mul( texelSize ) );
  24797. return add(
  24798. depthCompare( uv, shadowCoord.z ),
  24799. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  24800. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  24801. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  24802. mix(
  24803. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  24804. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  24805. f.x
  24806. ),
  24807. mix(
  24808. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  24809. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  24810. f.x
  24811. ),
  24812. mix(
  24813. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  24814. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  24815. f.y
  24816. ),
  24817. mix(
  24818. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  24819. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  24820. f.y
  24821. ),
  24822. mix(
  24823. mix(
  24824. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  24825. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  24826. f.x
  24827. ),
  24828. mix(
  24829. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  24830. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  24831. f.x
  24832. ),
  24833. f.y
  24834. )
  24835. ).mul( 1 / 9 );
  24836. } );
  24837. /**
  24838. * A shadow filtering function performing VSM filtering.
  24839. *
  24840. * @method
  24841. * @param {Object} inputs - The input parameter object.
  24842. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  24843. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  24844. * @return {Node<float>} The filtering result.
  24845. */
  24846. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  24847. const occlusion = float( 1 ).toVar();
  24848. const distribution = texture( depthTexture ).sample( shadowCoord.xy ).rg;
  24849. const hardShadow = step( shadowCoord.z, distribution.x );
  24850. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  24851. const distance = shadowCoord.z.sub( distribution.x );
  24852. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  24853. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  24854. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  24855. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  24856. } );
  24857. return occlusion;
  24858. } );
  24859. /**
  24860. * Represents the shader code for the first VSM render pass.
  24861. *
  24862. * @method
  24863. * @param {Object} inputs - The input parameter object.
  24864. * @param {Node<float>} inputs.samples - The number of samples
  24865. * @param {Node<float>} inputs.radius - The radius.
  24866. * @param {Node<float>} inputs.size - The size.
  24867. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  24868. * @return {Node<vec2>} The VSM output.
  24869. */
  24870. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  24871. const mean = float( 0 ).toVar();
  24872. const squaredMean = float( 0 ).toVar();
  24873. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  24874. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  24875. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  24876. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  24877. const depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  24878. mean.addAssign( depth );
  24879. squaredMean.addAssign( depth.mul( depth ) );
  24880. } );
  24881. mean.divAssign( samples );
  24882. squaredMean.divAssign( samples );
  24883. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  24884. return vec2( mean, std_dev );
  24885. } );
  24886. /**
  24887. * Represents the shader code for the second VSM render pass.
  24888. *
  24889. * @method
  24890. * @param {Object} inputs - The input parameter object.
  24891. * @param {Node<float>} inputs.samples - The number of samples
  24892. * @param {Node<float>} inputs.radius - The radius.
  24893. * @param {Node<float>} inputs.size - The size.
  24894. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  24895. * @return {Node<vec2>} The VSM output.
  24896. */
  24897. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  24898. const mean = float( 0 ).toVar();
  24899. const squaredMean = float( 0 ).toVar();
  24900. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  24901. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  24902. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  24903. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  24904. const distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  24905. mean.addAssign( distribution.x );
  24906. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  24907. } );
  24908. mean.divAssign( samples );
  24909. squaredMean.divAssign( samples );
  24910. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  24911. return vec2( mean, std_dev );
  24912. } );
  24913. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  24914. //
  24915. let _rendererState;
  24916. const _quadMesh$1 = /*@__PURE__*/ new QuadMesh();
  24917. /**
  24918. * Represents the default shadow implementation for lighting nodes.
  24919. *
  24920. * @augments module:ShadowBaseNode~ShadowBaseNode
  24921. */
  24922. class ShadowNode extends ShadowBaseNode {
  24923. static get type() {
  24924. return 'ShadowNode';
  24925. }
  24926. /**
  24927. * Constructs a new shadow node.
  24928. *
  24929. * @param {Light} light - The shadow casting light.
  24930. * @param {LightShadow?} [shadow=null] - An optional light shadow.
  24931. */
  24932. constructor( light, shadow = null ) {
  24933. super( light );
  24934. /**
  24935. * The light shadow which defines the properties light's
  24936. * shadow.
  24937. *
  24938. * @type {LightShadow?}
  24939. * @default null
  24940. */
  24941. this.shadow = shadow || light.shadow;
  24942. /**
  24943. * A reference to the shadow map which is a render target.
  24944. *
  24945. * @type {RenderTarget?}
  24946. * @default null
  24947. */
  24948. this.shadowMap = null;
  24949. /**
  24950. * Only relevant for VSM shadows. Render target for the
  24951. * first VSM render pass.
  24952. *
  24953. * @type {RenderTarget?}
  24954. * @default null
  24955. */
  24956. this.vsmShadowMapVertical = null;
  24957. /**
  24958. * Only relevant for VSM shadows. Render target for the
  24959. * second VSM render pass.
  24960. *
  24961. * @type {RenderTarget?}
  24962. * @default null
  24963. */
  24964. this.vsmShadowMapHorizontal = null;
  24965. /**
  24966. * Only relevant for VSM shadows. Node material which
  24967. * is used to render the first VSM pass.
  24968. *
  24969. * @type {NodeMaterial?}
  24970. * @default null
  24971. */
  24972. this.vsmMaterialVertical = null;
  24973. /**
  24974. * Only relevant for VSM shadows. Node material which
  24975. * is used to render the second VSM pass.
  24976. *
  24977. * @type {NodeMaterial?}
  24978. * @default null
  24979. */
  24980. this.vsmMaterialHorizontal = null;
  24981. /**
  24982. * A reference to the output node which defines the
  24983. * final result of this shadow node.
  24984. *
  24985. * @type {Node?}
  24986. * @private
  24987. * @default null
  24988. */
  24989. this._node = null;
  24990. /**
  24991. * This flag can be used for type testing.
  24992. *
  24993. * @type {Boolean}
  24994. * @readonly
  24995. * @default true
  24996. */
  24997. this.isShadowNode = true;
  24998. }
  24999. /**
  25000. * Setups the shadow filtering.
  25001. *
  25002. * @param {NodeBuilder} builder - A reference to the current node builder.
  25003. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  25004. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  25005. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25006. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  25007. * @param {LightShadow} inputs.shadow - The light shadow.
  25008. * @return {Node<float>} The result node of the shadow filtering.
  25009. */
  25010. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  25011. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  25012. .and( shadowCoord.x.lessThanEqual( 1 ) )
  25013. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  25014. .and( shadowCoord.y.lessThanEqual( 1 ) )
  25015. .and( shadowCoord.z.lessThanEqual( 1 ) );
  25016. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow } );
  25017. return frustumTest.select( shadowNode, float( 1 ) );
  25018. }
  25019. /**
  25020. * Setups the shadow coordinates.
  25021. *
  25022. * @param {NodeBuilder} builder - A reference to the current node builder.
  25023. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  25024. * @return {Node<vec3>} The shadow coordinates.
  25025. */
  25026. setupShadowCoord( builder, shadowPosition ) {
  25027. const { shadow } = this;
  25028. const { renderer } = builder;
  25029. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  25030. let shadowCoord = shadowPosition;
  25031. let coordZ;
  25032. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  25033. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  25034. coordZ = shadowCoord.z;
  25035. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  25036. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  25037. }
  25038. } else {
  25039. const w = shadowCoord.w;
  25040. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  25041. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  25042. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  25043. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  25044. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  25045. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  25046. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  25047. }
  25048. shadowCoord = vec3(
  25049. shadowCoord.x,
  25050. shadowCoord.y.oneMinus(), // follow webgpu standards
  25051. coordZ.add( bias )
  25052. );
  25053. return shadowCoord;
  25054. }
  25055. /**
  25056. * Returns the shadow filtering function for the given shadow type.
  25057. *
  25058. * @param {Number} type - The shadow type.
  25059. * @return {Function} The filtering function.
  25060. */
  25061. getShadowFilterFn( type ) {
  25062. return _shadowFilterLib[ type ];
  25063. }
  25064. /**
  25065. * Setups the shadow output node.
  25066. *
  25067. * @param {NodeBuilder} builder - A reference to the current node builder.
  25068. * @return {Node<vec3>} The shadow output node.
  25069. */
  25070. setupShadow( builder ) {
  25071. const { renderer } = builder;
  25072. const { light, shadow } = this;
  25073. const shadowMapType = renderer.shadowMap.type;
  25074. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  25075. depthTexture.compareFunction = LessCompare;
  25076. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  25077. shadowMap.depthTexture = depthTexture;
  25078. shadow.camera.updateProjectionMatrix();
  25079. // VSM
  25080. if ( shadowMapType === VSMShadowMap ) {
  25081. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  25082. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  25083. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  25084. const shadowPassVertical = texture( depthTexture );
  25085. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  25086. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  25087. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  25088. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  25089. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  25090. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  25091. material.name = 'VSMVertical';
  25092. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  25093. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  25094. material.name = 'VSMHorizontal';
  25095. }
  25096. //
  25097. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  25098. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  25099. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( transformedNormalWorld.mul( normalBias ) ) );
  25100. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  25101. //
  25102. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  25103. if ( filterFn === null ) {
  25104. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  25105. }
  25106. const shadowDepthTexture = ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  25107. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow } );
  25108. const shadowColor = texture( shadowMap.texture, shadowCoord );
  25109. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  25110. this.shadowMap = shadowMap;
  25111. this.shadow.map = shadowMap;
  25112. return shadowOutput;
  25113. }
  25114. /**
  25115. * The implementation performs the setup of the output node. An output is only
  25116. * produces if shadow mapping is globally enabled in the renderer.
  25117. *
  25118. * @param {NodeBuilder} builder - A reference to the current node builder.
  25119. * @return {ShaderCallNodeInternal} The output node.
  25120. */
  25121. setup( builder ) {
  25122. if ( builder.renderer.shadowMap.enabled === false ) return;
  25123. return Fn( () => {
  25124. let node = this._node;
  25125. this.setupShadowPosition( builder );
  25126. if ( node === null ) {
  25127. this._node = node = this.setupShadow( builder );
  25128. }
  25129. if ( builder.material.shadowNode ) { // @deprecated, r171
  25130. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  25131. }
  25132. if ( builder.material.receivedShadowNode ) {
  25133. node = builder.material.receivedShadowNode( node );
  25134. }
  25135. return node;
  25136. } )();
  25137. }
  25138. /**
  25139. * Renders the shadow. The logic of this function could be included
  25140. * into {@link ShadowNode#updateShadow} however more specialized shadow
  25141. * nodes might require a custom shadow map rendering. By having a
  25142. * dedicated method, it's easier to overwrite the default behavior.
  25143. *
  25144. * @param {NodeFrame} frame - A reference to the current node frame.
  25145. */
  25146. renderShadow( frame ) {
  25147. const { shadow, shadowMap, light } = this;
  25148. const { renderer, scene } = frame;
  25149. shadow.updateMatrices( light );
  25150. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  25151. renderer.render( scene, shadow.camera );
  25152. }
  25153. /**
  25154. * Updates the shadow.
  25155. *
  25156. * @param {NodeFrame} frame - A reference to the current node frame.
  25157. */
  25158. updateShadow( frame ) {
  25159. const { shadowMap, light, shadow } = this;
  25160. const { renderer, scene, camera } = frame;
  25161. const shadowType = renderer.shadowMap.type;
  25162. const depthVersion = shadowMap.depthTexture.version;
  25163. this._depthVersionCached = depthVersion;
  25164. shadow.camera.layers.mask = camera.layers.mask;
  25165. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  25166. const currentMRT = renderer.getMRT();
  25167. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  25168. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  25169. scene.overrideMaterial = getShadowMaterial( light );
  25170. renderer.setRenderObjectFunction( ( object, scene, _camera, geometry, material, group, ...params ) => {
  25171. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  25172. if ( useVelocity ) {
  25173. getDataFromObject( object ).useVelocity = true;
  25174. }
  25175. object.onBeforeShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  25176. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  25177. object.onAfterShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  25178. }
  25179. } );
  25180. renderer.setRenderTarget( shadowMap );
  25181. this.renderShadow( frame );
  25182. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  25183. // vsm blur pass
  25184. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  25185. this.vsmPass( renderer );
  25186. }
  25187. restoreRendererAndSceneState( renderer, scene, _rendererState );
  25188. }
  25189. /**
  25190. * For VSM additional render passes are required.
  25191. *
  25192. * @param {Renderer} renderer - A reference to the current renderer.
  25193. */
  25194. vsmPass( renderer ) {
  25195. const { shadow } = this;
  25196. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  25197. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  25198. renderer.setRenderTarget( this.vsmShadowMapVertical );
  25199. _quadMesh$1.material = this.vsmMaterialVertical;
  25200. _quadMesh$1.render( renderer );
  25201. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  25202. _quadMesh$1.material = this.vsmMaterialHorizontal;
  25203. _quadMesh$1.render( renderer );
  25204. }
  25205. /**
  25206. * Frees the internal resources of this shadow node.
  25207. */
  25208. dispose() {
  25209. this.shadowMap.dispose();
  25210. this.shadowMap = null;
  25211. if ( this.vsmShadowMapVertical !== null ) {
  25212. this.vsmShadowMapVertical.dispose();
  25213. this.vsmShadowMapVertical = null;
  25214. this.vsmMaterialVertical.dispose();
  25215. this.vsmMaterialVertical = null;
  25216. }
  25217. if ( this.vsmShadowMapHorizontal !== null ) {
  25218. this.vsmShadowMapHorizontal.dispose();
  25219. this.vsmShadowMapHorizontal = null;
  25220. this.vsmMaterialHorizontal.dispose();
  25221. this.vsmMaterialHorizontal = null;
  25222. }
  25223. super.dispose();
  25224. }
  25225. /**
  25226. * The implementation performs the update of the shadow map if necessary.
  25227. *
  25228. * @param {NodeFrame} frame - A reference to the current node frame.
  25229. */
  25230. updateBefore( frame ) {
  25231. const { shadow } = this;
  25232. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  25233. if ( needsUpdate ) {
  25234. this.updateShadow( frame );
  25235. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  25236. shadow.needsUpdate = false;
  25237. }
  25238. }
  25239. }
  25240. }
  25241. /**
  25242. * TSL function for creating an instance of `ShadowNode`.
  25243. *
  25244. * @function
  25245. * @param {Light} light - The shadow casting light.
  25246. * @param {LightShadow} shadow - The light shadow.
  25247. * @return {ShadowNode} The created shadow node.
  25248. */
  25249. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  25250. /**
  25251. * Base class for analytic light nodes.
  25252. *
  25253. * @augments LightingNode
  25254. */
  25255. class AnalyticLightNode extends LightingNode {
  25256. static get type() {
  25257. return 'AnalyticLightNode';
  25258. }
  25259. /**
  25260. * Constructs a new analytic light node.
  25261. *
  25262. * @param {Light?} [light=null] - The light source.
  25263. */
  25264. constructor( light = null ) {
  25265. super();
  25266. /**
  25267. * The light source.
  25268. *
  25269. * @type {Light?}
  25270. * @default null
  25271. */
  25272. this.light = light;
  25273. /**
  25274. * The light's color value.
  25275. *
  25276. * @type {Color}
  25277. */
  25278. this.color = new Color();
  25279. /**
  25280. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  25281. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  25282. *
  25283. * @type {Node}
  25284. */
  25285. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  25286. /**
  25287. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  25288. * The final color node is represented by a different node when using shadows.
  25289. *
  25290. * @type {Node?}
  25291. * @default null
  25292. */
  25293. this.baseColorNode = null;
  25294. /**
  25295. * Represents the light's shadow.
  25296. *
  25297. * @type {ShadowNode?}
  25298. * @default null
  25299. */
  25300. this.shadowNode = null;
  25301. /**
  25302. * Represents the light's shadow color.
  25303. *
  25304. * @type {Node?}
  25305. * @default null
  25306. */
  25307. this.shadowColorNode = null;
  25308. /**
  25309. * This flag can be used for type testing.
  25310. *
  25311. * @type {Boolean}
  25312. * @readonly
  25313. * @default true
  25314. */
  25315. this.isAnalyticLightNode = true;
  25316. /**
  25317. * Overwritten since analytic light nodes are updated
  25318. * once per frame.
  25319. *
  25320. * @type {String}
  25321. * @default 'frame'
  25322. */
  25323. this.updateType = NodeUpdateType.FRAME;
  25324. }
  25325. /**
  25326. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  25327. * `light.id` and `light.castShadow` into the cache key.
  25328. *
  25329. * @return {Number} The custom cache key.
  25330. */
  25331. customCacheKey() {
  25332. return hash$1( this.light.id, this.light.castShadow ? 1 : 0 );
  25333. }
  25334. getHash() {
  25335. return this.light.uuid;
  25336. }
  25337. /**
  25338. * Setups the shadow node for this light. The method exists so concrete light classes
  25339. * can setup different types of shadow nodes.
  25340. *
  25341. * @return {ShadowNode} The created shadow node.
  25342. */
  25343. setupShadowNode() {
  25344. return shadow( this.light );
  25345. }
  25346. /**
  25347. * Setups the shadow for this light. This method is only executed if the light
  25348. * cast shadows and the current build object receives shadows. It incorporates
  25349. * shadows into the lighting computation.
  25350. *
  25351. * @param {NodeBuilder} builder - The current node builder.
  25352. */
  25353. setupShadow( builder ) {
  25354. const { renderer } = builder;
  25355. if ( renderer.shadowMap.enabled === false ) return;
  25356. let shadowColorNode = this.shadowColorNode;
  25357. if ( shadowColorNode === null ) {
  25358. const customShadowNode = this.light.shadow.shadowNode;
  25359. let shadowNode;
  25360. if ( customShadowNode !== undefined ) {
  25361. shadowNode = nodeObject( customShadowNode );
  25362. } else {
  25363. shadowNode = this.setupShadowNode( builder );
  25364. }
  25365. this.shadowNode = shadowNode;
  25366. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  25367. this.baseColorNode = this.colorNode;
  25368. }
  25369. //
  25370. this.colorNode = shadowColorNode;
  25371. }
  25372. /**
  25373. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  25374. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  25375. * invocate the respective interface methods.
  25376. *
  25377. * @param {NodeBuilder} builder - The current node builder.
  25378. */
  25379. setup( builder ) {
  25380. this.colorNode = this.baseColorNode || this.colorNode;
  25381. if ( this.light.castShadow ) {
  25382. if ( builder.object.receiveShadow ) {
  25383. this.setupShadow( builder );
  25384. }
  25385. } else if ( this.shadowNode !== null ) {
  25386. this.shadowNode.dispose();
  25387. this.shadowNode = null;
  25388. this.shadowColorNode = null;
  25389. }
  25390. }
  25391. /**
  25392. * The update method is used to update light uniforms per frame.
  25393. * Potentially overwritten in concrete light nodes to update light
  25394. * specific uniforms.
  25395. *
  25396. * @param {NodeFrame} frame - A reference to the current node frame.
  25397. */
  25398. update( /*frame*/ ) {
  25399. const { light } = this;
  25400. this.color.copy( light.color ).multiplyScalar( light.intensity );
  25401. }
  25402. }
  25403. /** @module LightUtils **/
  25404. /**
  25405. * Represents a `discard` shader operation in TSL.
  25406. *
  25407. * @method
  25408. * @param {Object} inputs - The input parameter object.
  25409. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  25410. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  25411. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  25412. * @return {Node<float>} The distance falloff.
  25413. */
  25414. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  25415. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  25416. // based upon Frostbite 3 Moving to Physically-based Rendering
  25417. // page 32, equation 26: E[window1]
  25418. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  25419. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  25420. return cutoffDistance.greaterThan( 0 ).select(
  25421. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  25422. distanceFalloff
  25423. );
  25424. } ); // validated
  25425. /** @module PointShadowNode **/
  25426. const _clearColor$2 = /*@__PURE__*/ new Color();
  25427. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  25428. // vector suitable for 2D texture mapping. This code uses the following layout for the
  25429. // 2D texture:
  25430. //
  25431. // xzXZ
  25432. // y Y
  25433. //
  25434. // Y - Positive y direction
  25435. // y - Negative y direction
  25436. // X - Positive x direction
  25437. // x - Negative x direction
  25438. // Z - Positive z direction
  25439. // z - Negative z direction
  25440. //
  25441. // Source and test bed:
  25442. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  25443. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  25444. const v = pos.toVar();
  25445. // Number of texels to avoid at the edge of each square
  25446. const absV = abs( v );
  25447. // Intersect unit cube
  25448. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  25449. absV.mulAssign( scaleToCube );
  25450. // Apply scale to avoid seams
  25451. // two texels less per square (one texel will do for NEAREST)
  25452. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  25453. // Unwrap
  25454. // space: -1 ... 1 range for each square
  25455. //
  25456. // #X## dim := ( 4 , 2 )
  25457. // # # center := ( 1 , 1 )
  25458. const planar = vec2( v.xy ).toVar();
  25459. const almostATexel = texelSizeY.mul( 1.5 );
  25460. const almostOne = almostATexel.oneMinus();
  25461. If( absV.z.greaterThanEqual( almostOne ), () => {
  25462. If( v.z.greaterThan( 0.0 ), () => {
  25463. planar.x.assign( sub( 4.0, v.x ) );
  25464. } );
  25465. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  25466. const signX = sign( v.x );
  25467. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  25468. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  25469. const signY = sign( v.y );
  25470. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  25471. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  25472. } );
  25473. // Transform to UV space
  25474. // scale := 0.5 / dim
  25475. // translate := ( center + 0.5 ) / dim
  25476. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  25477. } ).setLayout( {
  25478. name: 'cubeToUV',
  25479. type: 'vec2',
  25480. inputs: [
  25481. { name: 'pos', type: 'vec3' },
  25482. { name: 'texelSizeY', type: 'float' }
  25483. ]
  25484. } );
  25485. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  25486. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  25487. } );
  25488. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  25489. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  25490. const offset = vec2( - 1.0, 1.0 ).mul( radius ).mul( texelSize.y );
  25491. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  25492. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  25493. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  25494. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  25495. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  25496. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  25497. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  25498. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  25499. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  25500. .mul( 1.0 / 9.0 );
  25501. } );
  25502. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  25503. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  25504. // the vector from the light to the world-space position of the fragment.
  25505. const lightToPosition = shadowCoord.xyz.toVar();
  25506. const lightToPositionLength = lightToPosition.length();
  25507. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  25508. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  25509. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  25510. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  25511. const result = float( 1.0 ).toVar();
  25512. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  25513. // dp = normalized distance from light to fragment position
  25514. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  25515. dp.addAssign( bias );
  25516. // bd3D = base direction 3D
  25517. const bd3D = lightToPosition.normalize();
  25518. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  25519. // percentage-closer filtering
  25520. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  25521. } );
  25522. return result;
  25523. } );
  25524. const _viewport = /*@__PURE__*/ new Vector4();
  25525. const _viewportSize = /*@__PURE__*/ new Vector2();
  25526. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  25527. /**
  25528. * Represents the shadow implementation for point light nodes.
  25529. *
  25530. * @augments module:ShadowNode~ShadowNode
  25531. */
  25532. class PointShadowNode extends ShadowNode {
  25533. static get type() {
  25534. return 'PointShadowNode';
  25535. }
  25536. /**
  25537. * Constructs a new point shadow node.
  25538. *
  25539. * @param {PointLight} light - The shadow casting point light.
  25540. * @param {PointLightShadow?} [shadow=null] - An optional point light shadow.
  25541. */
  25542. constructor( light, shadow = null ) {
  25543. super( light, shadow );
  25544. }
  25545. /**
  25546. * Overwrites the default implementation to return point light shadow specific
  25547. * filtering functions.
  25548. *
  25549. * @param {Number} type - The shadow type.
  25550. * @return {Function} The filtering function.
  25551. */
  25552. getShadowFilterFn( type ) {
  25553. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  25554. }
  25555. /**
  25556. * Overwrites the default implementation so the unaltered shadow position is used.
  25557. *
  25558. * @param {NodeBuilder} builder - A reference to the current node builder.
  25559. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  25560. * @return {Node<vec3>} The shadow coordinates.
  25561. */
  25562. setupShadowCoord( builder, shadowPosition ) {
  25563. return shadowPosition;
  25564. }
  25565. /**
  25566. * Overwrites the default implementation to only use point light specific
  25567. * shadow filter functions.
  25568. *
  25569. * @param {NodeBuilder} builder - A reference to the current node builder.
  25570. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  25571. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  25572. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  25573. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25574. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  25575. * @param {LightShadow} inputs.shadow - The light shadow.
  25576. * @return {Node<float>} The result node of the shadow filtering.
  25577. */
  25578. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  25579. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  25580. }
  25581. /**
  25582. * Overwrites the default implementation with point light specific
  25583. * rendering code.
  25584. *
  25585. * @param {NodeFrame} frame - A reference to the current node frame.
  25586. */
  25587. renderShadow( frame ) {
  25588. const { shadow, shadowMap, light } = this;
  25589. const { renderer, scene } = frame;
  25590. const shadowFrameExtents = shadow.getFrameExtents();
  25591. _shadowMapSize.copy( shadow.mapSize );
  25592. _shadowMapSize.multiply( shadowFrameExtents );
  25593. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  25594. _viewportSize.copy( shadow.mapSize );
  25595. //
  25596. const previousAutoClear = renderer.autoClear;
  25597. const previousClearColor = renderer.getClearColor( _clearColor$2 );
  25598. const previousClearAlpha = renderer.getClearAlpha();
  25599. renderer.autoClear = false;
  25600. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  25601. renderer.clear();
  25602. const viewportCount = shadow.getViewportCount();
  25603. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  25604. const viewport = shadow.getViewport( vp );
  25605. const x = _viewportSize.x * viewport.x;
  25606. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  25607. _viewport.set(
  25608. x,
  25609. y,
  25610. _viewportSize.x * viewport.z,
  25611. _viewportSize.y * viewport.w
  25612. );
  25613. shadowMap.viewport.copy( _viewport );
  25614. shadow.updateMatrices( light, vp );
  25615. renderer.render( scene, shadow.camera );
  25616. }
  25617. //
  25618. renderer.autoClear = previousAutoClear;
  25619. renderer.setClearColor( previousClearColor, previousClearAlpha );
  25620. }
  25621. }
  25622. /**
  25623. * TSL function for creating an instance of `PointShadowNode`.
  25624. *
  25625. * @function
  25626. * @param {PointLight} light - The shadow casting point light.
  25627. * @param {PointLightShadow?} [shadow=null] - An optional point light shadow.
  25628. * @return {PointShadowNode} The created point shadow node.
  25629. */
  25630. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  25631. const directPointLight = Fn( ( { color, lightViewPosition, cutoffDistance, decayExponent }, builder ) => {
  25632. const lightingModel = builder.context.lightingModel;
  25633. const lVector = lightViewPosition.sub( positionView ); // @TODO: Add it into LightNode
  25634. const lightDirection = lVector.normalize();
  25635. const lightDistance = lVector.length();
  25636. const lightAttenuation = getDistanceAttenuation( {
  25637. lightDistance,
  25638. cutoffDistance,
  25639. decayExponent
  25640. } );
  25641. const lightColor = color.mul( lightAttenuation );
  25642. const reflectedLight = builder.context.reflectedLight;
  25643. lightingModel.direct( {
  25644. lightDirection,
  25645. lightColor,
  25646. reflectedLight
  25647. }, builder.stack, builder );
  25648. } );
  25649. /**
  25650. * Module for representing point lights as nodes.
  25651. *
  25652. * @augments AnalyticLightNode
  25653. */
  25654. class PointLightNode extends AnalyticLightNode {
  25655. static get type() {
  25656. return 'PointLightNode';
  25657. }
  25658. /**
  25659. * Constructs a new point light node.
  25660. *
  25661. * @param {PointLight?} [light=null] - The point light source.
  25662. */
  25663. constructor( light = null ) {
  25664. super( light );
  25665. /**
  25666. * Uniform node representing the cutoff distance.
  25667. *
  25668. * @type {UniformNode<float>}
  25669. */
  25670. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  25671. /**
  25672. * Uniform node representing the decay exponent.
  25673. *
  25674. * @type {UniformNode<float>}
  25675. */
  25676. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  25677. }
  25678. /**
  25679. * Overwritten to updated point light specific uniforms.
  25680. *
  25681. * @param {NodeFrame} frame - A reference to the current node frame.
  25682. */
  25683. update( frame ) {
  25684. const { light } = this;
  25685. super.update( frame );
  25686. this.cutoffDistanceNode.value = light.distance;
  25687. this.decayExponentNode.value = light.decay;
  25688. }
  25689. /**
  25690. * Overwritten to setup point light specific shadow.
  25691. *
  25692. * @return {PointShadowNode}
  25693. */
  25694. setupShadowNode() {
  25695. return pointShadow( this.light );
  25696. }
  25697. setup( builder ) {
  25698. super.setup( builder );
  25699. directPointLight( {
  25700. color: this.colorNode,
  25701. lightViewPosition: lightViewPosition( this.light ),
  25702. cutoffDistance: this.cutoffDistanceNode,
  25703. decayExponent: this.decayExponentNode
  25704. } ).append();
  25705. }
  25706. }
  25707. /** @module Procedural **/
  25708. /**
  25709. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  25710. *
  25711. * @method
  25712. * @param {Node<vec2>} coord - The uv coordinates.
  25713. * @return {Node<float>} The result data.
  25714. */
  25715. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  25716. const uv = coord.mul( 2.0 );
  25717. const cx = uv.x.floor();
  25718. const cy = uv.y.floor();
  25719. const result = cx.add( cy ).mod( 2.0 );
  25720. return result.sign();
  25721. } );
  25722. // Three.js Transpiler
  25723. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  25724. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  25725. const f = float( f_immutable ).toVar();
  25726. const t = float( t_immutable ).toVar();
  25727. const b = bool( b_immutable ).toVar();
  25728. return select( b, t, f );
  25729. } ).setLayout( {
  25730. name: 'mx_select',
  25731. type: 'float',
  25732. inputs: [
  25733. { name: 'b', type: 'bool' },
  25734. { name: 't', type: 'float' },
  25735. { name: 'f', type: 'float' }
  25736. ]
  25737. } );
  25738. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  25739. const b = bool( b_immutable ).toVar();
  25740. const val = float( val_immutable ).toVar();
  25741. return select( b, val.negate(), val );
  25742. } ).setLayout( {
  25743. name: 'mx_negate_if',
  25744. type: 'float',
  25745. inputs: [
  25746. { name: 'val', type: 'float' },
  25747. { name: 'b', type: 'bool' }
  25748. ]
  25749. } );
  25750. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  25751. const x = float( x_immutable ).toVar();
  25752. return int( floor( x ) );
  25753. } ).setLayout( {
  25754. name: 'mx_floor',
  25755. type: 'int',
  25756. inputs: [
  25757. { name: 'x', type: 'float' }
  25758. ]
  25759. } );
  25760. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  25761. const x = float( x_immutable ).toVar();
  25762. i.assign( mx_floor( x ) );
  25763. return x.sub( float( i ) );
  25764. } );
  25765. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  25766. const t = float( t_immutable ).toVar();
  25767. const s = float( s_immutable ).toVar();
  25768. const v3 = float( v3_immutable ).toVar();
  25769. const v2 = float( v2_immutable ).toVar();
  25770. const v1 = float( v1_immutable ).toVar();
  25771. const v0 = float( v0_immutable ).toVar();
  25772. const s1 = float( sub( 1.0, s ) ).toVar();
  25773. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  25774. } ).setLayout( {
  25775. name: 'mx_bilerp_0',
  25776. type: 'float',
  25777. inputs: [
  25778. { name: 'v0', type: 'float' },
  25779. { name: 'v1', type: 'float' },
  25780. { name: 'v2', type: 'float' },
  25781. { name: 'v3', type: 'float' },
  25782. { name: 's', type: 'float' },
  25783. { name: 't', type: 'float' }
  25784. ]
  25785. } );
  25786. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  25787. const t = float( t_immutable ).toVar();
  25788. const s = float( s_immutable ).toVar();
  25789. const v3 = vec3( v3_immutable ).toVar();
  25790. const v2 = vec3( v2_immutable ).toVar();
  25791. const v1 = vec3( v1_immutable ).toVar();
  25792. const v0 = vec3( v0_immutable ).toVar();
  25793. const s1 = float( sub( 1.0, s ) ).toVar();
  25794. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  25795. } ).setLayout( {
  25796. name: 'mx_bilerp_1',
  25797. type: 'vec3',
  25798. inputs: [
  25799. { name: 'v0', type: 'vec3' },
  25800. { name: 'v1', type: 'vec3' },
  25801. { name: 'v2', type: 'vec3' },
  25802. { name: 'v3', type: 'vec3' },
  25803. { name: 's', type: 'float' },
  25804. { name: 't', type: 'float' }
  25805. ]
  25806. } );
  25807. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  25808. 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 ] ) => {
  25809. const r = float( r_immutable ).toVar();
  25810. const t = float( t_immutable ).toVar();
  25811. const s = float( s_immutable ).toVar();
  25812. const v7 = float( v7_immutable ).toVar();
  25813. const v6 = float( v6_immutable ).toVar();
  25814. const v5 = float( v5_immutable ).toVar();
  25815. const v4 = float( v4_immutable ).toVar();
  25816. const v3 = float( v3_immutable ).toVar();
  25817. const v2 = float( v2_immutable ).toVar();
  25818. const v1 = float( v1_immutable ).toVar();
  25819. const v0 = float( v0_immutable ).toVar();
  25820. const s1 = float( sub( 1.0, s ) ).toVar();
  25821. const t1 = float( sub( 1.0, t ) ).toVar();
  25822. const r1 = float( sub( 1.0, r ) ).toVar();
  25823. 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 ) ) ) ) ) );
  25824. } ).setLayout( {
  25825. name: 'mx_trilerp_0',
  25826. type: 'float',
  25827. inputs: [
  25828. { name: 'v0', type: 'float' },
  25829. { name: 'v1', type: 'float' },
  25830. { name: 'v2', type: 'float' },
  25831. { name: 'v3', type: 'float' },
  25832. { name: 'v4', type: 'float' },
  25833. { name: 'v5', type: 'float' },
  25834. { name: 'v6', type: 'float' },
  25835. { name: 'v7', type: 'float' },
  25836. { name: 's', type: 'float' },
  25837. { name: 't', type: 'float' },
  25838. { name: 'r', type: 'float' }
  25839. ]
  25840. } );
  25841. 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 ] ) => {
  25842. const r = float( r_immutable ).toVar();
  25843. const t = float( t_immutable ).toVar();
  25844. const s = float( s_immutable ).toVar();
  25845. const v7 = vec3( v7_immutable ).toVar();
  25846. const v6 = vec3( v6_immutable ).toVar();
  25847. const v5 = vec3( v5_immutable ).toVar();
  25848. const v4 = vec3( v4_immutable ).toVar();
  25849. const v3 = vec3( v3_immutable ).toVar();
  25850. const v2 = vec3( v2_immutable ).toVar();
  25851. const v1 = vec3( v1_immutable ).toVar();
  25852. const v0 = vec3( v0_immutable ).toVar();
  25853. const s1 = float( sub( 1.0, s ) ).toVar();
  25854. const t1 = float( sub( 1.0, t ) ).toVar();
  25855. const r1 = float( sub( 1.0, r ) ).toVar();
  25856. 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 ) ) ) ) ) );
  25857. } ).setLayout( {
  25858. name: 'mx_trilerp_1',
  25859. type: 'vec3',
  25860. inputs: [
  25861. { name: 'v0', type: 'vec3' },
  25862. { name: 'v1', type: 'vec3' },
  25863. { name: 'v2', type: 'vec3' },
  25864. { name: 'v3', type: 'vec3' },
  25865. { name: 'v4', type: 'vec3' },
  25866. { name: 'v5', type: 'vec3' },
  25867. { name: 'v6', type: 'vec3' },
  25868. { name: 'v7', type: 'vec3' },
  25869. { name: 's', type: 'float' },
  25870. { name: 't', type: 'float' },
  25871. { name: 'r', type: 'float' }
  25872. ]
  25873. } );
  25874. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  25875. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  25876. const y = float( y_immutable ).toVar();
  25877. const x = float( x_immutable ).toVar();
  25878. const hash = uint( hash_immutable ).toVar();
  25879. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  25880. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  25881. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  25882. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  25883. } ).setLayout( {
  25884. name: 'mx_gradient_float_0',
  25885. type: 'float',
  25886. inputs: [
  25887. { name: 'hash', type: 'uint' },
  25888. { name: 'x', type: 'float' },
  25889. { name: 'y', type: 'float' }
  25890. ]
  25891. } );
  25892. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  25893. const z = float( z_immutable ).toVar();
  25894. const y = float( y_immutable ).toVar();
  25895. const x = float( x_immutable ).toVar();
  25896. const hash = uint( hash_immutable ).toVar();
  25897. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  25898. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  25899. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  25900. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  25901. } ).setLayout( {
  25902. name: 'mx_gradient_float_1',
  25903. type: 'float',
  25904. inputs: [
  25905. { name: 'hash', type: 'uint' },
  25906. { name: 'x', type: 'float' },
  25907. { name: 'y', type: 'float' },
  25908. { name: 'z', type: 'float' }
  25909. ]
  25910. } );
  25911. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  25912. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  25913. const y = float( y_immutable ).toVar();
  25914. const x = float( x_immutable ).toVar();
  25915. const hash = uvec3( hash_immutable ).toVar();
  25916. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  25917. } ).setLayout( {
  25918. name: 'mx_gradient_vec3_0',
  25919. type: 'vec3',
  25920. inputs: [
  25921. { name: 'hash', type: 'uvec3' },
  25922. { name: 'x', type: 'float' },
  25923. { name: 'y', type: 'float' }
  25924. ]
  25925. } );
  25926. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  25927. const z = float( z_immutable ).toVar();
  25928. const y = float( y_immutable ).toVar();
  25929. const x = float( x_immutable ).toVar();
  25930. const hash = uvec3( hash_immutable ).toVar();
  25931. 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 ) );
  25932. } ).setLayout( {
  25933. name: 'mx_gradient_vec3_1',
  25934. type: 'vec3',
  25935. inputs: [
  25936. { name: 'hash', type: 'uvec3' },
  25937. { name: 'x', type: 'float' },
  25938. { name: 'y', type: 'float' },
  25939. { name: 'z', type: 'float' }
  25940. ]
  25941. } );
  25942. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  25943. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  25944. const v = float( v_immutable ).toVar();
  25945. return mul( 0.6616, v );
  25946. } ).setLayout( {
  25947. name: 'mx_gradient_scale2d_0',
  25948. type: 'float',
  25949. inputs: [
  25950. { name: 'v', type: 'float' }
  25951. ]
  25952. } );
  25953. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  25954. const v = float( v_immutable ).toVar();
  25955. return mul( 0.9820, v );
  25956. } ).setLayout( {
  25957. name: 'mx_gradient_scale3d_0',
  25958. type: 'float',
  25959. inputs: [
  25960. { name: 'v', type: 'float' }
  25961. ]
  25962. } );
  25963. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  25964. const v = vec3( v_immutable ).toVar();
  25965. return mul( 0.6616, v );
  25966. } ).setLayout( {
  25967. name: 'mx_gradient_scale2d_1',
  25968. type: 'vec3',
  25969. inputs: [
  25970. { name: 'v', type: 'vec3' }
  25971. ]
  25972. } );
  25973. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  25974. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  25975. const v = vec3( v_immutable ).toVar();
  25976. return mul( 0.9820, v );
  25977. } ).setLayout( {
  25978. name: 'mx_gradient_scale3d_1',
  25979. type: 'vec3',
  25980. inputs: [
  25981. { name: 'v', type: 'vec3' }
  25982. ]
  25983. } );
  25984. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  25985. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  25986. const k = int( k_immutable ).toVar();
  25987. const x = uint( x_immutable ).toVar();
  25988. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  25989. } ).setLayout( {
  25990. name: 'mx_rotl32',
  25991. type: 'uint',
  25992. inputs: [
  25993. { name: 'x', type: 'uint' },
  25994. { name: 'k', type: 'int' }
  25995. ]
  25996. } );
  25997. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  25998. a.subAssign( c );
  25999. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  26000. c.addAssign( b );
  26001. b.subAssign( a );
  26002. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  26003. a.addAssign( c );
  26004. c.subAssign( b );
  26005. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  26006. b.addAssign( a );
  26007. a.subAssign( c );
  26008. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  26009. c.addAssign( b );
  26010. b.subAssign( a );
  26011. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  26012. a.addAssign( c );
  26013. c.subAssign( b );
  26014. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  26015. b.addAssign( a );
  26016. } );
  26017. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  26018. const c = uint( c_immutable ).toVar();
  26019. const b = uint( b_immutable ).toVar();
  26020. const a = uint( a_immutable ).toVar();
  26021. c.bitXorAssign( b );
  26022. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  26023. a.bitXorAssign( c );
  26024. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  26025. b.bitXorAssign( a );
  26026. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  26027. c.bitXorAssign( b );
  26028. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  26029. a.bitXorAssign( c );
  26030. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  26031. b.bitXorAssign( a );
  26032. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  26033. c.bitXorAssign( b );
  26034. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  26035. return c;
  26036. } ).setLayout( {
  26037. name: 'mx_bjfinal',
  26038. type: 'uint',
  26039. inputs: [
  26040. { name: 'a', type: 'uint' },
  26041. { name: 'b', type: 'uint' },
  26042. { name: 'c', type: 'uint' }
  26043. ]
  26044. } );
  26045. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  26046. const bits = uint( bits_immutable ).toVar();
  26047. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  26048. } ).setLayout( {
  26049. name: 'mx_bits_to_01',
  26050. type: 'float',
  26051. inputs: [
  26052. { name: 'bits', type: 'uint' }
  26053. ]
  26054. } );
  26055. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  26056. const t = float( t_immutable ).toVar();
  26057. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  26058. } ).setLayout( {
  26059. name: 'mx_fade',
  26060. type: 'float',
  26061. inputs: [
  26062. { name: 't', type: 'float' }
  26063. ]
  26064. } );
  26065. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  26066. const x = int( x_immutable ).toVar();
  26067. const len = uint( uint( 1 ) ).toVar();
  26068. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  26069. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  26070. } ).setLayout( {
  26071. name: 'mx_hash_int_0',
  26072. type: 'uint',
  26073. inputs: [
  26074. { name: 'x', type: 'int' }
  26075. ]
  26076. } );
  26077. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  26078. const y = int( y_immutable ).toVar();
  26079. const x = int( x_immutable ).toVar();
  26080. const len = uint( uint( 2 ) ).toVar();
  26081. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26082. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26083. a.addAssign( uint( x ) );
  26084. b.addAssign( uint( y ) );
  26085. return mx_bjfinal( a, b, c );
  26086. } ).setLayout( {
  26087. name: 'mx_hash_int_1',
  26088. type: 'uint',
  26089. inputs: [
  26090. { name: 'x', type: 'int' },
  26091. { name: 'y', type: 'int' }
  26092. ]
  26093. } );
  26094. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  26095. const z = int( z_immutable ).toVar();
  26096. const y = int( y_immutable ).toVar();
  26097. const x = int( x_immutable ).toVar();
  26098. const len = uint( uint( 3 ) ).toVar();
  26099. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26100. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26101. a.addAssign( uint( x ) );
  26102. b.addAssign( uint( y ) );
  26103. c.addAssign( uint( z ) );
  26104. return mx_bjfinal( a, b, c );
  26105. } ).setLayout( {
  26106. name: 'mx_hash_int_2',
  26107. type: 'uint',
  26108. inputs: [
  26109. { name: 'x', type: 'int' },
  26110. { name: 'y', type: 'int' },
  26111. { name: 'z', type: 'int' }
  26112. ]
  26113. } );
  26114. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  26115. const xx = int( xx_immutable ).toVar();
  26116. const z = int( z_immutable ).toVar();
  26117. const y = int( y_immutable ).toVar();
  26118. const x = int( x_immutable ).toVar();
  26119. const len = uint( uint( 4 ) ).toVar();
  26120. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26121. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26122. a.addAssign( uint( x ) );
  26123. b.addAssign( uint( y ) );
  26124. c.addAssign( uint( z ) );
  26125. mx_bjmix( a, b, c );
  26126. a.addAssign( uint( xx ) );
  26127. return mx_bjfinal( a, b, c );
  26128. } ).setLayout( {
  26129. name: 'mx_hash_int_3',
  26130. type: 'uint',
  26131. inputs: [
  26132. { name: 'x', type: 'int' },
  26133. { name: 'y', type: 'int' },
  26134. { name: 'z', type: 'int' },
  26135. { name: 'xx', type: 'int' }
  26136. ]
  26137. } );
  26138. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  26139. const yy = int( yy_immutable ).toVar();
  26140. const xx = int( xx_immutable ).toVar();
  26141. const z = int( z_immutable ).toVar();
  26142. const y = int( y_immutable ).toVar();
  26143. const x = int( x_immutable ).toVar();
  26144. const len = uint( uint( 5 ) ).toVar();
  26145. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26146. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26147. a.addAssign( uint( x ) );
  26148. b.addAssign( uint( y ) );
  26149. c.addAssign( uint( z ) );
  26150. mx_bjmix( a, b, c );
  26151. a.addAssign( uint( xx ) );
  26152. b.addAssign( uint( yy ) );
  26153. return mx_bjfinal( a, b, c );
  26154. } ).setLayout( {
  26155. name: 'mx_hash_int_4',
  26156. type: 'uint',
  26157. inputs: [
  26158. { name: 'x', type: 'int' },
  26159. { name: 'y', type: 'int' },
  26160. { name: 'z', type: 'int' },
  26161. { name: 'xx', type: 'int' },
  26162. { name: 'yy', type: 'int' }
  26163. ]
  26164. } );
  26165. 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 ] );
  26166. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  26167. const y = int( y_immutable ).toVar();
  26168. const x = int( x_immutable ).toVar();
  26169. const h = uint( mx_hash_int( x, y ) ).toVar();
  26170. const result = uvec3().toVar();
  26171. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  26172. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  26173. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  26174. return result;
  26175. } ).setLayout( {
  26176. name: 'mx_hash_vec3_0',
  26177. type: 'uvec3',
  26178. inputs: [
  26179. { name: 'x', type: 'int' },
  26180. { name: 'y', type: 'int' }
  26181. ]
  26182. } );
  26183. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  26184. const z = int( z_immutable ).toVar();
  26185. const y = int( y_immutable ).toVar();
  26186. const x = int( x_immutable ).toVar();
  26187. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  26188. const result = uvec3().toVar();
  26189. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  26190. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  26191. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  26192. return result;
  26193. } ).setLayout( {
  26194. name: 'mx_hash_vec3_1',
  26195. type: 'uvec3',
  26196. inputs: [
  26197. { name: 'x', type: 'int' },
  26198. { name: 'y', type: 'int' },
  26199. { name: 'z', type: 'int' }
  26200. ]
  26201. } );
  26202. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  26203. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26204. const p = vec2( p_immutable ).toVar();
  26205. const X = int().toVar(), Y = int().toVar();
  26206. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26207. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26208. const u = float( mx_fade( fx ) ).toVar();
  26209. const v = float( mx_fade( fy ) ).toVar();
  26210. 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();
  26211. return mx_gradient_scale2d( result );
  26212. } ).setLayout( {
  26213. name: 'mx_perlin_noise_float_0',
  26214. type: 'float',
  26215. inputs: [
  26216. { name: 'p', type: 'vec2' }
  26217. ]
  26218. } );
  26219. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26220. const p = vec3( p_immutable ).toVar();
  26221. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26222. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26223. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26224. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  26225. const u = float( mx_fade( fx ) ).toVar();
  26226. const v = float( mx_fade( fy ) ).toVar();
  26227. const w = float( mx_fade( fz ) ).toVar();
  26228. 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();
  26229. return mx_gradient_scale3d( result );
  26230. } ).setLayout( {
  26231. name: 'mx_perlin_noise_float_1',
  26232. type: 'float',
  26233. inputs: [
  26234. { name: 'p', type: 'vec3' }
  26235. ]
  26236. } );
  26237. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  26238. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26239. const p = vec2( p_immutable ).toVar();
  26240. const X = int().toVar(), Y = int().toVar();
  26241. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26242. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26243. const u = float( mx_fade( fx ) ).toVar();
  26244. const v = float( mx_fade( fy ) ).toVar();
  26245. 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();
  26246. return mx_gradient_scale2d( result );
  26247. } ).setLayout( {
  26248. name: 'mx_perlin_noise_vec3_0',
  26249. type: 'vec3',
  26250. inputs: [
  26251. { name: 'p', type: 'vec2' }
  26252. ]
  26253. } );
  26254. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26255. const p = vec3( p_immutable ).toVar();
  26256. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26257. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26258. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26259. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  26260. const u = float( mx_fade( fx ) ).toVar();
  26261. const v = float( mx_fade( fy ) ).toVar();
  26262. const w = float( mx_fade( fz ) ).toVar();
  26263. 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();
  26264. return mx_gradient_scale3d( result );
  26265. } ).setLayout( {
  26266. name: 'mx_perlin_noise_vec3_1',
  26267. type: 'vec3',
  26268. inputs: [
  26269. { name: 'p', type: 'vec3' }
  26270. ]
  26271. } );
  26272. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  26273. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26274. const p = float( p_immutable ).toVar();
  26275. const ix = int( mx_floor( p ) ).toVar();
  26276. return mx_bits_to_01( mx_hash_int( ix ) );
  26277. } ).setLayout( {
  26278. name: 'mx_cell_noise_float_0',
  26279. type: 'float',
  26280. inputs: [
  26281. { name: 'p', type: 'float' }
  26282. ]
  26283. } );
  26284. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26285. const p = vec2( p_immutable ).toVar();
  26286. const ix = int( mx_floor( p.x ) ).toVar();
  26287. const iy = int( mx_floor( p.y ) ).toVar();
  26288. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  26289. } ).setLayout( {
  26290. name: 'mx_cell_noise_float_1',
  26291. type: 'float',
  26292. inputs: [
  26293. { name: 'p', type: 'vec2' }
  26294. ]
  26295. } );
  26296. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26297. const p = vec3( p_immutable ).toVar();
  26298. const ix = int( mx_floor( p.x ) ).toVar();
  26299. const iy = int( mx_floor( p.y ) ).toVar();
  26300. const iz = int( mx_floor( p.z ) ).toVar();
  26301. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  26302. } ).setLayout( {
  26303. name: 'mx_cell_noise_float_2',
  26304. type: 'float',
  26305. inputs: [
  26306. { name: 'p', type: 'vec3' }
  26307. ]
  26308. } );
  26309. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26310. const p = vec4( p_immutable ).toVar();
  26311. const ix = int( mx_floor( p.x ) ).toVar();
  26312. const iy = int( mx_floor( p.y ) ).toVar();
  26313. const iz = int( mx_floor( p.z ) ).toVar();
  26314. const iw = int( mx_floor( p.w ) ).toVar();
  26315. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  26316. } ).setLayout( {
  26317. name: 'mx_cell_noise_float_3',
  26318. type: 'float',
  26319. inputs: [
  26320. { name: 'p', type: 'vec4' }
  26321. ]
  26322. } );
  26323. 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 ] );
  26324. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26325. const p = float( p_immutable ).toVar();
  26326. const ix = int( mx_floor( p ) ).toVar();
  26327. 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 ) ) ) );
  26328. } ).setLayout( {
  26329. name: 'mx_cell_noise_vec3_0',
  26330. type: 'vec3',
  26331. inputs: [
  26332. { name: 'p', type: 'float' }
  26333. ]
  26334. } );
  26335. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26336. const p = vec2( p_immutable ).toVar();
  26337. const ix = int( mx_floor( p.x ) ).toVar();
  26338. const iy = int( mx_floor( p.y ) ).toVar();
  26339. 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 ) ) ) );
  26340. } ).setLayout( {
  26341. name: 'mx_cell_noise_vec3_1',
  26342. type: 'vec3',
  26343. inputs: [
  26344. { name: 'p', type: 'vec2' }
  26345. ]
  26346. } );
  26347. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26348. const p = vec3( p_immutable ).toVar();
  26349. const ix = int( mx_floor( p.x ) ).toVar();
  26350. const iy = int( mx_floor( p.y ) ).toVar();
  26351. const iz = int( mx_floor( p.z ) ).toVar();
  26352. 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 ) ) ) );
  26353. } ).setLayout( {
  26354. name: 'mx_cell_noise_vec3_2',
  26355. type: 'vec3',
  26356. inputs: [
  26357. { name: 'p', type: 'vec3' }
  26358. ]
  26359. } );
  26360. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26361. const p = vec4( p_immutable ).toVar();
  26362. const ix = int( mx_floor( p.x ) ).toVar();
  26363. const iy = int( mx_floor( p.y ) ).toVar();
  26364. const iz = int( mx_floor( p.z ) ).toVar();
  26365. const iw = int( mx_floor( p.w ) ).toVar();
  26366. 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 ) ) ) );
  26367. } ).setLayout( {
  26368. name: 'mx_cell_noise_vec3_3',
  26369. type: 'vec3',
  26370. inputs: [
  26371. { name: 'p', type: 'vec4' }
  26372. ]
  26373. } );
  26374. 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 ] );
  26375. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26376. const diminish = float( diminish_immutable ).toVar();
  26377. const lacunarity = float( lacunarity_immutable ).toVar();
  26378. const octaves = int( octaves_immutable ).toVar();
  26379. const p = vec3( p_immutable ).toVar();
  26380. const result = float( 0.0 ).toVar();
  26381. const amplitude = float( 1.0 ).toVar();
  26382. Loop( octaves, () => {
  26383. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  26384. amplitude.mulAssign( diminish );
  26385. p.mulAssign( lacunarity );
  26386. } );
  26387. return result;
  26388. } ).setLayout( {
  26389. name: 'mx_fractal_noise_float',
  26390. type: 'float',
  26391. inputs: [
  26392. { name: 'p', type: 'vec3' },
  26393. { name: 'octaves', type: 'int' },
  26394. { name: 'lacunarity', type: 'float' },
  26395. { name: 'diminish', type: 'float' }
  26396. ]
  26397. } );
  26398. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26399. const diminish = float( diminish_immutable ).toVar();
  26400. const lacunarity = float( lacunarity_immutable ).toVar();
  26401. const octaves = int( octaves_immutable ).toVar();
  26402. const p = vec3( p_immutable ).toVar();
  26403. const result = vec3( 0.0 ).toVar();
  26404. const amplitude = float( 1.0 ).toVar();
  26405. Loop( octaves, () => {
  26406. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  26407. amplitude.mulAssign( diminish );
  26408. p.mulAssign( lacunarity );
  26409. } );
  26410. return result;
  26411. } ).setLayout( {
  26412. name: 'mx_fractal_noise_vec3',
  26413. type: 'vec3',
  26414. inputs: [
  26415. { name: 'p', type: 'vec3' },
  26416. { name: 'octaves', type: 'int' },
  26417. { name: 'lacunarity', type: 'float' },
  26418. { name: 'diminish', type: 'float' }
  26419. ]
  26420. } );
  26421. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26422. const diminish = float( diminish_immutable ).toVar();
  26423. const lacunarity = float( lacunarity_immutable ).toVar();
  26424. const octaves = int( octaves_immutable ).toVar();
  26425. const p = vec3( p_immutable ).toVar();
  26426. 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 ) );
  26427. } ).setLayout( {
  26428. name: 'mx_fractal_noise_vec2',
  26429. type: 'vec2',
  26430. inputs: [
  26431. { name: 'p', type: 'vec3' },
  26432. { name: 'octaves', type: 'int' },
  26433. { name: 'lacunarity', type: 'float' },
  26434. { name: 'diminish', type: 'float' }
  26435. ]
  26436. } );
  26437. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26438. const diminish = float( diminish_immutable ).toVar();
  26439. const lacunarity = float( lacunarity_immutable ).toVar();
  26440. const octaves = int( octaves_immutable ).toVar();
  26441. const p = vec3( p_immutable ).toVar();
  26442. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  26443. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  26444. return vec4( c, f );
  26445. } ).setLayout( {
  26446. name: 'mx_fractal_noise_vec4',
  26447. type: 'vec4',
  26448. inputs: [
  26449. { name: 'p', type: 'vec3' },
  26450. { name: 'octaves', type: 'int' },
  26451. { name: 'lacunarity', type: 'float' },
  26452. { name: 'diminish', type: 'float' }
  26453. ]
  26454. } );
  26455. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  26456. const metric = int( metric_immutable ).toVar();
  26457. const jitter = float( jitter_immutable ).toVar();
  26458. const yoff = int( yoff_immutable ).toVar();
  26459. const xoff = int( xoff_immutable ).toVar();
  26460. const y = int( y_immutable ).toVar();
  26461. const x = int( x_immutable ).toVar();
  26462. const p = vec2( p_immutable ).toVar();
  26463. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  26464. const off = vec2( tmp.x, tmp.y ).toVar();
  26465. off.subAssign( 0.5 );
  26466. off.mulAssign( jitter );
  26467. off.addAssign( 0.5 );
  26468. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  26469. const diff = vec2( cellpos.sub( p ) ).toVar();
  26470. If( metric.equal( int( 2 ) ), () => {
  26471. return abs( diff.x ).add( abs( diff.y ) );
  26472. } );
  26473. If( metric.equal( int( 3 ) ), () => {
  26474. return max$1( abs( diff.x ), abs( diff.y ) );
  26475. } );
  26476. return dot( diff, diff );
  26477. } ).setLayout( {
  26478. name: 'mx_worley_distance_0',
  26479. type: 'float',
  26480. inputs: [
  26481. { name: 'p', type: 'vec2' },
  26482. { name: 'x', type: 'int' },
  26483. { name: 'y', type: 'int' },
  26484. { name: 'xoff', type: 'int' },
  26485. { name: 'yoff', type: 'int' },
  26486. { name: 'jitter', type: 'float' },
  26487. { name: 'metric', type: 'int' }
  26488. ]
  26489. } );
  26490. 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 ] ) => {
  26491. const metric = int( metric_immutable ).toVar();
  26492. const jitter = float( jitter_immutable ).toVar();
  26493. const zoff = int( zoff_immutable ).toVar();
  26494. const yoff = int( yoff_immutable ).toVar();
  26495. const xoff = int( xoff_immutable ).toVar();
  26496. const z = int( z_immutable ).toVar();
  26497. const y = int( y_immutable ).toVar();
  26498. const x = int( x_immutable ).toVar();
  26499. const p = vec3( p_immutable ).toVar();
  26500. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  26501. off.subAssign( 0.5 );
  26502. off.mulAssign( jitter );
  26503. off.addAssign( 0.5 );
  26504. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  26505. const diff = vec3( cellpos.sub( p ) ).toVar();
  26506. If( metric.equal( int( 2 ) ), () => {
  26507. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  26508. } );
  26509. If( metric.equal( int( 3 ) ), () => {
  26510. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  26511. } );
  26512. return dot( diff, diff );
  26513. } ).setLayout( {
  26514. name: 'mx_worley_distance_1',
  26515. type: 'float',
  26516. inputs: [
  26517. { name: 'p', type: 'vec3' },
  26518. { name: 'x', type: 'int' },
  26519. { name: 'y', type: 'int' },
  26520. { name: 'z', type: 'int' },
  26521. { name: 'xoff', type: 'int' },
  26522. { name: 'yoff', type: 'int' },
  26523. { name: 'zoff', type: 'int' },
  26524. { name: 'jitter', type: 'float' },
  26525. { name: 'metric', type: 'int' }
  26526. ]
  26527. } );
  26528. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  26529. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26530. const metric = int( metric_immutable ).toVar();
  26531. const jitter = float( jitter_immutable ).toVar();
  26532. const p = vec2( p_immutable ).toVar();
  26533. const X = int().toVar(), Y = int().toVar();
  26534. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  26535. const sqdist = float( 1e6 ).toVar();
  26536. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26537. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26538. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  26539. sqdist.assign( min$1( sqdist, dist ) );
  26540. } );
  26541. } );
  26542. If( metric.equal( int( 0 ) ), () => {
  26543. sqdist.assign( sqrt( sqdist ) );
  26544. } );
  26545. return sqdist;
  26546. } ).setLayout( {
  26547. name: 'mx_worley_noise_float_0',
  26548. type: 'float',
  26549. inputs: [
  26550. { name: 'p', type: 'vec2' },
  26551. { name: 'jitter', type: 'float' },
  26552. { name: 'metric', type: 'int' }
  26553. ]
  26554. } );
  26555. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26556. const metric = int( metric_immutable ).toVar();
  26557. const jitter = float( jitter_immutable ).toVar();
  26558. const p = vec2( p_immutable ).toVar();
  26559. const X = int().toVar(), Y = int().toVar();
  26560. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  26561. const sqdist = vec2( 1e6, 1e6 ).toVar();
  26562. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26563. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26564. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  26565. If( dist.lessThan( sqdist.x ), () => {
  26566. sqdist.y.assign( sqdist.x );
  26567. sqdist.x.assign( dist );
  26568. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  26569. sqdist.y.assign( dist );
  26570. } );
  26571. } );
  26572. } );
  26573. If( metric.equal( int( 0 ) ), () => {
  26574. sqdist.assign( sqrt( sqdist ) );
  26575. } );
  26576. return sqdist;
  26577. } ).setLayout( {
  26578. name: 'mx_worley_noise_vec2_0',
  26579. type: 'vec2',
  26580. inputs: [
  26581. { name: 'p', type: 'vec2' },
  26582. { name: 'jitter', type: 'float' },
  26583. { name: 'metric', type: 'int' }
  26584. ]
  26585. } );
  26586. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26587. const metric = int( metric_immutable ).toVar();
  26588. const jitter = float( jitter_immutable ).toVar();
  26589. const p = vec2( p_immutable ).toVar();
  26590. const X = int().toVar(), Y = int().toVar();
  26591. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  26592. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  26593. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26594. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26595. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  26596. If( dist.lessThan( sqdist.x ), () => {
  26597. sqdist.z.assign( sqdist.y );
  26598. sqdist.y.assign( sqdist.x );
  26599. sqdist.x.assign( dist );
  26600. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  26601. sqdist.z.assign( sqdist.y );
  26602. sqdist.y.assign( dist );
  26603. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  26604. sqdist.z.assign( dist );
  26605. } );
  26606. } );
  26607. } );
  26608. If( metric.equal( int( 0 ) ), () => {
  26609. sqdist.assign( sqrt( sqdist ) );
  26610. } );
  26611. return sqdist;
  26612. } ).setLayout( {
  26613. name: 'mx_worley_noise_vec3_0',
  26614. type: 'vec3',
  26615. inputs: [
  26616. { name: 'p', type: 'vec2' },
  26617. { name: 'jitter', type: 'float' },
  26618. { name: 'metric', type: 'int' }
  26619. ]
  26620. } );
  26621. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26622. const metric = int( metric_immutable ).toVar();
  26623. const jitter = float( jitter_immutable ).toVar();
  26624. const p = vec3( p_immutable ).toVar();
  26625. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26626. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  26627. const sqdist = float( 1e6 ).toVar();
  26628. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26629. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26630. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  26631. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  26632. sqdist.assign( min$1( sqdist, dist ) );
  26633. } );
  26634. } );
  26635. } );
  26636. If( metric.equal( int( 0 ) ), () => {
  26637. sqdist.assign( sqrt( sqdist ) );
  26638. } );
  26639. return sqdist;
  26640. } ).setLayout( {
  26641. name: 'mx_worley_noise_float_1',
  26642. type: 'float',
  26643. inputs: [
  26644. { name: 'p', type: 'vec3' },
  26645. { name: 'jitter', type: 'float' },
  26646. { name: 'metric', type: 'int' }
  26647. ]
  26648. } );
  26649. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  26650. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26651. const metric = int( metric_immutable ).toVar();
  26652. const jitter = float( jitter_immutable ).toVar();
  26653. const p = vec3( p_immutable ).toVar();
  26654. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26655. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  26656. const sqdist = vec2( 1e6, 1e6 ).toVar();
  26657. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26658. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26659. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  26660. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  26661. If( dist.lessThan( sqdist.x ), () => {
  26662. sqdist.y.assign( sqdist.x );
  26663. sqdist.x.assign( dist );
  26664. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  26665. sqdist.y.assign( dist );
  26666. } );
  26667. } );
  26668. } );
  26669. } );
  26670. If( metric.equal( int( 0 ) ), () => {
  26671. sqdist.assign( sqrt( sqdist ) );
  26672. } );
  26673. return sqdist;
  26674. } ).setLayout( {
  26675. name: 'mx_worley_noise_vec2_1',
  26676. type: 'vec2',
  26677. inputs: [
  26678. { name: 'p', type: 'vec3' },
  26679. { name: 'jitter', type: 'float' },
  26680. { name: 'metric', type: 'int' }
  26681. ]
  26682. } );
  26683. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  26684. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26685. const metric = int( metric_immutable ).toVar();
  26686. const jitter = float( jitter_immutable ).toVar();
  26687. const p = vec3( p_immutable ).toVar();
  26688. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26689. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  26690. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  26691. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26692. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26693. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  26694. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  26695. If( dist.lessThan( sqdist.x ), () => {
  26696. sqdist.z.assign( sqdist.y );
  26697. sqdist.y.assign( sqdist.x );
  26698. sqdist.x.assign( dist );
  26699. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  26700. sqdist.z.assign( sqdist.y );
  26701. sqdist.y.assign( dist );
  26702. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  26703. sqdist.z.assign( dist );
  26704. } );
  26705. } );
  26706. } );
  26707. } );
  26708. If( metric.equal( int( 0 ) ), () => {
  26709. sqdist.assign( sqrt( sqdist ) );
  26710. } );
  26711. return sqdist;
  26712. } ).setLayout( {
  26713. name: 'mx_worley_noise_vec3_1',
  26714. type: 'vec3',
  26715. inputs: [
  26716. { name: 'p', type: 'vec3' },
  26717. { name: 'jitter', type: 'float' },
  26718. { name: 'metric', type: 'int' }
  26719. ]
  26720. } );
  26721. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  26722. // Three.js Transpiler
  26723. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  26724. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  26725. const s = hsv.y;
  26726. const v = hsv.z;
  26727. const result = vec3().toVar();
  26728. If( s.lessThan( 0.0001 ), () => {
  26729. result.assign( vec3( v, v, v ) );
  26730. } ).Else( () => {
  26731. let h = hsv.x;
  26732. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  26733. const hi = int( trunc( h ) );
  26734. const f = h.sub( float( hi ) );
  26735. const p = v.mul( s.oneMinus() );
  26736. const q = v.mul( s.mul( f ).oneMinus() );
  26737. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  26738. If( hi.equal( int( 0 ) ), () => {
  26739. result.assign( vec3( v, t, p ) );
  26740. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  26741. result.assign( vec3( q, v, p ) );
  26742. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  26743. result.assign( vec3( p, v, t ) );
  26744. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  26745. result.assign( vec3( p, q, v ) );
  26746. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  26747. result.assign( vec3( t, p, v ) );
  26748. } ).Else( () => {
  26749. result.assign( vec3( v, p, q ) );
  26750. } );
  26751. } );
  26752. return result;
  26753. } ).setLayout( {
  26754. name: 'mx_hsvtorgb',
  26755. type: 'vec3',
  26756. inputs: [
  26757. { name: 'hsv', type: 'vec3' }
  26758. ]
  26759. } );
  26760. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  26761. const c = vec3( c_immutable ).toVar();
  26762. const r = float( c.x ).toVar();
  26763. const g = float( c.y ).toVar();
  26764. const b = float( c.z ).toVar();
  26765. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  26766. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  26767. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  26768. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  26769. v.assign( maxcomp );
  26770. If( maxcomp.greaterThan( 0.0 ), () => {
  26771. s.assign( delta.div( maxcomp ) );
  26772. } ).Else( () => {
  26773. s.assign( 0.0 );
  26774. } );
  26775. If( s.lessThanEqual( 0.0 ), () => {
  26776. h.assign( 0.0 );
  26777. } ).Else( () => {
  26778. If( r.greaterThanEqual( maxcomp ), () => {
  26779. h.assign( g.sub( b ).div( delta ) );
  26780. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  26781. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  26782. } ).Else( () => {
  26783. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  26784. } );
  26785. h.mulAssign( 1.0 / 6.0 );
  26786. If( h.lessThan( 0.0 ), () => {
  26787. h.addAssign( 1.0 );
  26788. } );
  26789. } );
  26790. return vec3( h, s, v );
  26791. } ).setLayout( {
  26792. name: 'mx_rgbtohsv',
  26793. type: 'vec3',
  26794. inputs: [
  26795. { name: 'c', type: 'vec3' }
  26796. ]
  26797. } );
  26798. // Three.js Transpiler
  26799. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  26800. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  26801. const color = vec3( color_immutable ).toVar();
  26802. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  26803. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  26804. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  26805. return mix( linSeg, powSeg, isAbove );
  26806. } ).setLayout( {
  26807. name: 'mx_srgb_texture_to_lin_rec709',
  26808. type: 'vec3',
  26809. inputs: [
  26810. { name: 'color', type: 'vec3' }
  26811. ]
  26812. } );
  26813. const mx_aastep = ( threshold, value ) => {
  26814. threshold = float( threshold );
  26815. value = float( value );
  26816. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  26817. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  26818. };
  26819. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  26820. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  26821. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  26822. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  26823. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  26824. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  26825. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  26826. const mx_safepower = ( in1, in2 = 1 ) => {
  26827. in1 = float( in1 );
  26828. return in1.abs().pow( in2 ).mul( in1.sign() );
  26829. };
  26830. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  26831. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  26832. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  26833. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  26834. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  26835. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  26836. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  26837. return noise_vec4.mul( amplitude ).add( pivot );
  26838. };
  26839. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  26840. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  26841. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  26842. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  26843. 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 );
  26844. 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 );
  26845. 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 );
  26846. 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 );
  26847. /** @module getParallaxCorrectNormal **/
  26848. /**
  26849. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  26850. *
  26851. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  26852. *
  26853. * ```js
  26854. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  26855. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  26856. * ```
  26857. * @function
  26858. * @param {Node<vec3>} normal - The normal to correct.
  26859. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  26860. * @param {Node<vec3>} cubePos - The cube position.
  26861. * @return {Node<vec3>} The parallax corrected normal.
  26862. */
  26863. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  26864. const nDir = normalize( normal ).toVar( 'nDir' );
  26865. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmax' );
  26866. const rbmin = sub( float( - 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmin' );
  26867. const rbminmax = vec3().toVar( 'rbminmax' );
  26868. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  26869. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  26870. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  26871. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar( 'correction' );
  26872. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar( 'boxIntersection' );
  26873. return boxIntersection.sub( cubePos );
  26874. } );
  26875. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  26876. // normal is assumed to have unit length
  26877. const x = normal.x, y = normal.y, z = normal.z;
  26878. // band 0
  26879. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  26880. // band 1
  26881. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  26882. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  26883. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  26884. // band 2
  26885. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  26886. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  26887. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  26888. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  26889. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  26890. return result;
  26891. } );
  26892. // constants
  26893. var TSL = /*#__PURE__*/Object.freeze({
  26894. __proto__: null,
  26895. BRDF_GGX: BRDF_GGX,
  26896. BRDF_Lambert: BRDF_Lambert,
  26897. BasicShadowFilter: BasicShadowFilter,
  26898. Break: Break,
  26899. Continue: Continue,
  26900. DFGApprox: DFGApprox,
  26901. D_GGX: D_GGX,
  26902. Discard: Discard,
  26903. EPSILON: EPSILON,
  26904. F_Schlick: F_Schlick,
  26905. Fn: Fn,
  26906. INFINITY: INFINITY,
  26907. If: If,
  26908. Loop: Loop,
  26909. NodeAccess: NodeAccess,
  26910. NodeShaderStage: NodeShaderStage,
  26911. NodeType: NodeType,
  26912. NodeUpdateType: NodeUpdateType,
  26913. PCFShadowFilter: PCFShadowFilter,
  26914. PCFSoftShadowFilter: PCFSoftShadowFilter,
  26915. PI: PI,
  26916. PI2: PI2,
  26917. Return: Return,
  26918. Schlick_to_F0: Schlick_to_F0,
  26919. ScriptableNodeResources: ScriptableNodeResources,
  26920. ShaderNode: ShaderNode,
  26921. TBNViewMatrix: TBNViewMatrix,
  26922. VSMShadowFilter: VSMShadowFilter,
  26923. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  26924. abs: abs,
  26925. acesFilmicToneMapping: acesFilmicToneMapping,
  26926. acos: acos,
  26927. add: add,
  26928. addMethodChaining: addMethodChaining,
  26929. addNodeElement: addNodeElement,
  26930. agxToneMapping: agxToneMapping,
  26931. all: all,
  26932. alphaT: alphaT,
  26933. and: and,
  26934. anisotropy: anisotropy,
  26935. anisotropyB: anisotropyB,
  26936. anisotropyT: anisotropyT,
  26937. any: any,
  26938. append: append,
  26939. arrayBuffer: arrayBuffer,
  26940. asin: asin,
  26941. assign: assign,
  26942. atan: atan,
  26943. atan2: atan2,
  26944. atomicAdd: atomicAdd,
  26945. atomicAnd: atomicAnd,
  26946. atomicFunc: atomicFunc,
  26947. atomicMax: atomicMax,
  26948. atomicMin: atomicMin,
  26949. atomicOr: atomicOr,
  26950. atomicStore: atomicStore,
  26951. atomicSub: atomicSub,
  26952. atomicXor: atomicXor,
  26953. attenuationColor: attenuationColor,
  26954. attenuationDistance: attenuationDistance,
  26955. attribute: attribute,
  26956. attributeArray: attributeArray,
  26957. backgroundBlurriness: backgroundBlurriness,
  26958. backgroundIntensity: backgroundIntensity,
  26959. backgroundRotation: backgroundRotation,
  26960. batch: batch,
  26961. billboarding: billboarding,
  26962. bitAnd: bitAnd,
  26963. bitNot: bitNot,
  26964. bitOr: bitOr,
  26965. bitXor: bitXor,
  26966. bitangentGeometry: bitangentGeometry,
  26967. bitangentLocal: bitangentLocal,
  26968. bitangentView: bitangentView,
  26969. bitangentWorld: bitangentWorld,
  26970. bitcast: bitcast,
  26971. blendBurn: blendBurn,
  26972. blendColor: blendColor,
  26973. blendDodge: blendDodge,
  26974. blendOverlay: blendOverlay,
  26975. blendScreen: blendScreen,
  26976. blur: blur,
  26977. bool: bool,
  26978. buffer: buffer,
  26979. bufferAttribute: bufferAttribute,
  26980. bumpMap: bumpMap,
  26981. burn: burn,
  26982. bvec2: bvec2,
  26983. bvec3: bvec3,
  26984. bvec4: bvec4,
  26985. bypass: bypass,
  26986. cache: cache,
  26987. call: call,
  26988. cameraFar: cameraFar,
  26989. cameraNear: cameraNear,
  26990. cameraNormalMatrix: cameraNormalMatrix,
  26991. cameraPosition: cameraPosition,
  26992. cameraProjectionMatrix: cameraProjectionMatrix,
  26993. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  26994. cameraViewMatrix: cameraViewMatrix,
  26995. cameraWorldMatrix: cameraWorldMatrix,
  26996. cbrt: cbrt,
  26997. cdl: cdl,
  26998. ceil: ceil,
  26999. checker: checker,
  27000. cineonToneMapping: cineonToneMapping,
  27001. clamp: clamp,
  27002. clearcoat: clearcoat,
  27003. clearcoatRoughness: clearcoatRoughness,
  27004. code: code,
  27005. color: color,
  27006. colorSpaceToWorking: colorSpaceToWorking,
  27007. colorToDirection: colorToDirection,
  27008. compute: compute,
  27009. cond: cond,
  27010. context: context,
  27011. convert: convert,
  27012. convertColorSpace: convertColorSpace,
  27013. convertToTexture: convertToTexture,
  27014. cos: cos,
  27015. cross: cross,
  27016. cubeTexture: cubeTexture,
  27017. dFdx: dFdx,
  27018. dFdy: dFdy,
  27019. dashSize: dashSize,
  27020. defaultBuildStages: defaultBuildStages,
  27021. defaultShaderStages: defaultShaderStages,
  27022. defined: defined,
  27023. degrees: degrees,
  27024. deltaTime: deltaTime,
  27025. densityFog: densityFog,
  27026. densityFogFactor: densityFogFactor,
  27027. depth: depth,
  27028. depthPass: depthPass,
  27029. difference: difference,
  27030. diffuseColor: diffuseColor,
  27031. directPointLight: directPointLight,
  27032. directionToColor: directionToColor,
  27033. dispersion: dispersion,
  27034. distance: distance,
  27035. div: div,
  27036. dodge: dodge,
  27037. dot: dot,
  27038. drawIndex: drawIndex,
  27039. dynamicBufferAttribute: dynamicBufferAttribute,
  27040. element: element,
  27041. emissive: emissive,
  27042. equal: equal,
  27043. equals: equals,
  27044. equirectUV: equirectUV,
  27045. exp: exp,
  27046. exp2: exp2,
  27047. expression: expression,
  27048. faceDirection: faceDirection,
  27049. faceForward: faceForward,
  27050. faceforward: faceforward,
  27051. float: float,
  27052. floor: floor,
  27053. fog: fog,
  27054. fract: fract,
  27055. frameGroup: frameGroup,
  27056. frameId: frameId,
  27057. frontFacing: frontFacing,
  27058. fwidth: fwidth,
  27059. gain: gain,
  27060. gapSize: gapSize,
  27061. getConstNodeType: getConstNodeType,
  27062. getCurrentStack: getCurrentStack,
  27063. getDirection: getDirection,
  27064. getDistanceAttenuation: getDistanceAttenuation,
  27065. getGeometryRoughness: getGeometryRoughness,
  27066. getNormalFromDepth: getNormalFromDepth,
  27067. getParallaxCorrectNormal: getParallaxCorrectNormal,
  27068. getRoughness: getRoughness,
  27069. getScreenPosition: getScreenPosition,
  27070. getShIrradianceAt: getShIrradianceAt,
  27071. getTextureIndex: getTextureIndex,
  27072. getViewPosition: getViewPosition,
  27073. glsl: glsl,
  27074. glslFn: glslFn,
  27075. grayscale: grayscale,
  27076. greaterThan: greaterThan,
  27077. greaterThanEqual: greaterThanEqual,
  27078. hash: hash,
  27079. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  27080. highpModelViewMatrix: highpModelViewMatrix,
  27081. hue: hue,
  27082. instance: instance,
  27083. instanceIndex: instanceIndex,
  27084. instancedArray: instancedArray,
  27085. instancedBufferAttribute: instancedBufferAttribute,
  27086. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  27087. instancedMesh: instancedMesh,
  27088. int: int,
  27089. inverseSqrt: inverseSqrt,
  27090. inversesqrt: inversesqrt,
  27091. invocationLocalIndex: invocationLocalIndex,
  27092. invocationSubgroupIndex: invocationSubgroupIndex,
  27093. ior: ior,
  27094. iridescence: iridescence,
  27095. iridescenceIOR: iridescenceIOR,
  27096. iridescenceThickness: iridescenceThickness,
  27097. ivec2: ivec2,
  27098. ivec3: ivec3,
  27099. ivec4: ivec4,
  27100. js: js,
  27101. label: label,
  27102. length: length,
  27103. lengthSq: lengthSq,
  27104. lessThan: lessThan,
  27105. lessThanEqual: lessThanEqual,
  27106. lightPosition: lightPosition,
  27107. lightProjectionUV: lightProjectionUV,
  27108. lightShadowMatrix: lightShadowMatrix,
  27109. lightTargetDirection: lightTargetDirection,
  27110. lightTargetPosition: lightTargetPosition,
  27111. lightViewPosition: lightViewPosition,
  27112. lightingContext: lightingContext,
  27113. lights: lights,
  27114. linearDepth: linearDepth,
  27115. linearToneMapping: linearToneMapping,
  27116. localId: localId,
  27117. log: log,
  27118. log2: log2,
  27119. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  27120. loop: loop,
  27121. luminance: luminance,
  27122. mat2: mat2,
  27123. mat3: mat3,
  27124. mat4: mat4,
  27125. matcapUV: matcapUV,
  27126. materialAO: materialAO,
  27127. materialAlphaTest: materialAlphaTest,
  27128. materialAnisotropy: materialAnisotropy,
  27129. materialAnisotropyVector: materialAnisotropyVector,
  27130. materialAttenuationColor: materialAttenuationColor,
  27131. materialAttenuationDistance: materialAttenuationDistance,
  27132. materialClearcoat: materialClearcoat,
  27133. materialClearcoatNormal: materialClearcoatNormal,
  27134. materialClearcoatRoughness: materialClearcoatRoughness,
  27135. materialColor: materialColor,
  27136. materialDispersion: materialDispersion,
  27137. materialEmissive: materialEmissive,
  27138. materialIOR: materialIOR,
  27139. materialIridescence: materialIridescence,
  27140. materialIridescenceIOR: materialIridescenceIOR,
  27141. materialIridescenceThickness: materialIridescenceThickness,
  27142. materialLightMap: materialLightMap,
  27143. materialLineDashOffset: materialLineDashOffset,
  27144. materialLineDashSize: materialLineDashSize,
  27145. materialLineGapSize: materialLineGapSize,
  27146. materialLineScale: materialLineScale,
  27147. materialLineWidth: materialLineWidth,
  27148. materialMetalness: materialMetalness,
  27149. materialNormal: materialNormal,
  27150. materialOpacity: materialOpacity,
  27151. materialPointWidth: materialPointWidth,
  27152. materialReference: materialReference,
  27153. materialReflectivity: materialReflectivity,
  27154. materialRefractionRatio: materialRefractionRatio,
  27155. materialRotation: materialRotation,
  27156. materialRoughness: materialRoughness,
  27157. materialSheen: materialSheen,
  27158. materialSheenRoughness: materialSheenRoughness,
  27159. materialShininess: materialShininess,
  27160. materialSpecular: materialSpecular,
  27161. materialSpecularColor: materialSpecularColor,
  27162. materialSpecularIntensity: materialSpecularIntensity,
  27163. materialSpecularStrength: materialSpecularStrength,
  27164. materialThickness: materialThickness,
  27165. materialTransmission: materialTransmission,
  27166. max: max$1,
  27167. maxMipLevel: maxMipLevel,
  27168. mediumpModelViewMatrix: mediumpModelViewMatrix,
  27169. metalness: metalness,
  27170. min: min$1,
  27171. mix: mix,
  27172. mixElement: mixElement,
  27173. mod: mod,
  27174. modInt: modInt,
  27175. modelDirection: modelDirection,
  27176. modelNormalMatrix: modelNormalMatrix,
  27177. modelPosition: modelPosition,
  27178. modelScale: modelScale,
  27179. modelViewMatrix: modelViewMatrix,
  27180. modelViewPosition: modelViewPosition,
  27181. modelViewProjection: modelViewProjection,
  27182. modelWorldMatrix: modelWorldMatrix,
  27183. modelWorldMatrixInverse: modelWorldMatrixInverse,
  27184. morphReference: morphReference,
  27185. mrt: mrt,
  27186. mul: mul,
  27187. mx_aastep: mx_aastep,
  27188. mx_cell_noise_float: mx_cell_noise_float,
  27189. mx_contrast: mx_contrast,
  27190. mx_fractal_noise_float: mx_fractal_noise_float,
  27191. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  27192. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  27193. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  27194. mx_hsvtorgb: mx_hsvtorgb,
  27195. mx_noise_float: mx_noise_float,
  27196. mx_noise_vec3: mx_noise_vec3,
  27197. mx_noise_vec4: mx_noise_vec4,
  27198. mx_ramplr: mx_ramplr,
  27199. mx_ramptb: mx_ramptb,
  27200. mx_rgbtohsv: mx_rgbtohsv,
  27201. mx_safepower: mx_safepower,
  27202. mx_splitlr: mx_splitlr,
  27203. mx_splittb: mx_splittb,
  27204. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  27205. mx_transform_uv: mx_transform_uv,
  27206. mx_worley_noise_float: mx_worley_noise_float,
  27207. mx_worley_noise_vec2: mx_worley_noise_vec2,
  27208. mx_worley_noise_vec3: mx_worley_noise_vec3,
  27209. negate: negate,
  27210. neutralToneMapping: neutralToneMapping,
  27211. nodeArray: nodeArray,
  27212. nodeImmutable: nodeImmutable,
  27213. nodeObject: nodeObject,
  27214. nodeObjects: nodeObjects,
  27215. nodeProxy: nodeProxy,
  27216. normalFlat: normalFlat,
  27217. normalGeometry: normalGeometry,
  27218. normalLocal: normalLocal,
  27219. normalMap: normalMap,
  27220. normalView: normalView,
  27221. normalWorld: normalWorld,
  27222. normalize: normalize,
  27223. not: not,
  27224. notEqual: notEqual,
  27225. numWorkgroups: numWorkgroups,
  27226. objectDirection: objectDirection,
  27227. objectGroup: objectGroup,
  27228. objectPosition: objectPosition,
  27229. objectScale: objectScale,
  27230. objectViewPosition: objectViewPosition,
  27231. objectWorldMatrix: objectWorldMatrix,
  27232. oneMinus: oneMinus,
  27233. or: or,
  27234. orthographicDepthToViewZ: orthographicDepthToViewZ,
  27235. oscSawtooth: oscSawtooth,
  27236. oscSine: oscSine,
  27237. oscSquare: oscSquare,
  27238. oscTriangle: oscTriangle,
  27239. output: output,
  27240. outputStruct: outputStruct,
  27241. overlay: overlay,
  27242. overloadingFn: overloadingFn,
  27243. parabola: parabola,
  27244. parallaxDirection: parallaxDirection,
  27245. parallaxUV: parallaxUV,
  27246. parameter: parameter,
  27247. pass: pass,
  27248. passTexture: passTexture,
  27249. pcurve: pcurve,
  27250. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  27251. pmremTexture: pmremTexture,
  27252. pointUV: pointUV,
  27253. pointWidth: pointWidth,
  27254. positionGeometry: positionGeometry,
  27255. positionLocal: positionLocal,
  27256. positionPrevious: positionPrevious,
  27257. positionView: positionView,
  27258. positionViewDirection: positionViewDirection,
  27259. positionWorld: positionWorld,
  27260. positionWorldDirection: positionWorldDirection,
  27261. posterize: posterize,
  27262. pow: pow,
  27263. pow2: pow2,
  27264. pow3: pow3,
  27265. pow4: pow4,
  27266. property: property,
  27267. radians: radians,
  27268. rand: rand,
  27269. range: range,
  27270. rangeFog: rangeFog,
  27271. rangeFogFactor: rangeFogFactor,
  27272. reciprocal: reciprocal,
  27273. reference: reference,
  27274. referenceBuffer: referenceBuffer,
  27275. reflect: reflect,
  27276. reflectVector: reflectVector,
  27277. reflectView: reflectView,
  27278. reflector: reflector,
  27279. refract: refract,
  27280. refractVector: refractVector,
  27281. refractView: refractView,
  27282. reinhardToneMapping: reinhardToneMapping,
  27283. remainder: remainder,
  27284. remap: remap,
  27285. remapClamp: remapClamp,
  27286. renderGroup: renderGroup,
  27287. renderOutput: renderOutput,
  27288. rendererReference: rendererReference,
  27289. rotate: rotate,
  27290. rotateUV: rotateUV,
  27291. roughness: roughness,
  27292. round: round,
  27293. rtt: rtt,
  27294. sRGBTransferEOTF: sRGBTransferEOTF,
  27295. sRGBTransferOETF: sRGBTransferOETF,
  27296. sampler: sampler,
  27297. saturate: saturate,
  27298. saturation: saturation,
  27299. screen: screen,
  27300. screenCoordinate: screenCoordinate,
  27301. screenSize: screenSize,
  27302. screenUV: screenUV,
  27303. scriptable: scriptable,
  27304. scriptableValue: scriptableValue,
  27305. select: select,
  27306. setCurrentStack: setCurrentStack,
  27307. shaderStages: shaderStages,
  27308. shadow: shadow,
  27309. shadowPositionWorld: shadowPositionWorld,
  27310. sharedUniformGroup: sharedUniformGroup,
  27311. sheen: sheen,
  27312. sheenRoughness: sheenRoughness,
  27313. shiftLeft: shiftLeft,
  27314. shiftRight: shiftRight,
  27315. shininess: shininess,
  27316. sign: sign,
  27317. sin: sin,
  27318. sinc: sinc,
  27319. skinning: skinning,
  27320. skinningReference: skinningReference,
  27321. smoothstep: smoothstep,
  27322. smoothstepElement: smoothstepElement,
  27323. specularColor: specularColor,
  27324. specularF90: specularF90,
  27325. spherizeUV: spherizeUV,
  27326. split: split,
  27327. spritesheetUV: spritesheetUV,
  27328. sqrt: sqrt,
  27329. stack: stack,
  27330. step: step,
  27331. storage: storage,
  27332. storageBarrier: storageBarrier,
  27333. storageObject: storageObject,
  27334. storageTexture: storageTexture,
  27335. string: string,
  27336. sub: sub,
  27337. subgroupIndex: subgroupIndex,
  27338. subgroupSize: subgroupSize,
  27339. tan: tan,
  27340. tangentGeometry: tangentGeometry,
  27341. tangentLocal: tangentLocal,
  27342. tangentView: tangentView,
  27343. tangentWorld: tangentWorld,
  27344. temp: temp,
  27345. texture: texture,
  27346. texture3D: texture3D,
  27347. textureBarrier: textureBarrier,
  27348. textureBicubic: textureBicubic,
  27349. textureCubeUV: textureCubeUV,
  27350. textureLoad: textureLoad,
  27351. textureSize: textureSize,
  27352. textureStore: textureStore,
  27353. thickness: thickness,
  27354. time: time,
  27355. timerDelta: timerDelta,
  27356. timerGlobal: timerGlobal,
  27357. timerLocal: timerLocal,
  27358. toOutputColorSpace: toOutputColorSpace,
  27359. toWorkingColorSpace: toWorkingColorSpace,
  27360. toneMapping: toneMapping,
  27361. toneMappingExposure: toneMappingExposure,
  27362. toonOutlinePass: toonOutlinePass,
  27363. transformDirection: transformDirection,
  27364. transformNormal: transformNormal,
  27365. transformNormalToView: transformNormalToView,
  27366. transformedBentNormalView: transformedBentNormalView,
  27367. transformedBitangentView: transformedBitangentView,
  27368. transformedBitangentWorld: transformedBitangentWorld,
  27369. transformedClearcoatNormalView: transformedClearcoatNormalView,
  27370. transformedNormalView: transformedNormalView,
  27371. transformedNormalWorld: transformedNormalWorld,
  27372. transformedTangentView: transformedTangentView,
  27373. transformedTangentWorld: transformedTangentWorld,
  27374. transmission: transmission,
  27375. transpose: transpose,
  27376. triNoise3D: triNoise3D,
  27377. triplanarTexture: triplanarTexture,
  27378. triplanarTextures: triplanarTextures,
  27379. trunc: trunc,
  27380. tslFn: tslFn,
  27381. uint: uint,
  27382. uniform: uniform,
  27383. uniformArray: uniformArray,
  27384. uniformGroup: uniformGroup,
  27385. uniforms: uniforms,
  27386. userData: userData,
  27387. uv: uv,
  27388. uvec2: uvec2,
  27389. uvec3: uvec3,
  27390. uvec4: uvec4,
  27391. varying: varying,
  27392. varyingProperty: varyingProperty,
  27393. vec2: vec2,
  27394. vec3: vec3,
  27395. vec4: vec4,
  27396. vectorComponents: vectorComponents,
  27397. velocity: velocity,
  27398. vertexColor: vertexColor,
  27399. vertexIndex: vertexIndex,
  27400. vertexStage: vertexStage,
  27401. vibrance: vibrance,
  27402. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  27403. viewZToOrthographicDepth: viewZToOrthographicDepth,
  27404. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  27405. viewport: viewport,
  27406. viewportBottomLeft: viewportBottomLeft,
  27407. viewportCoordinate: viewportCoordinate,
  27408. viewportDepthTexture: viewportDepthTexture,
  27409. viewportLinearDepth: viewportLinearDepth,
  27410. viewportMipTexture: viewportMipTexture,
  27411. viewportResolution: viewportResolution,
  27412. viewportSafeUV: viewportSafeUV,
  27413. viewportSharedTexture: viewportSharedTexture,
  27414. viewportSize: viewportSize,
  27415. viewportTexture: viewportTexture,
  27416. viewportTopLeft: viewportTopLeft,
  27417. viewportUV: viewportUV,
  27418. wgsl: wgsl,
  27419. wgslFn: wgslFn,
  27420. workgroupArray: workgroupArray,
  27421. workgroupBarrier: workgroupBarrier,
  27422. workgroupId: workgroupId,
  27423. workingToColorSpace: workingToColorSpace,
  27424. xor: xor
  27425. });
  27426. const _clearColor$1 = /*@__PURE__*/ new Color4();
  27427. /**
  27428. * This renderer module manages the background.
  27429. *
  27430. * @private
  27431. * @augments DataMap
  27432. */
  27433. class Background extends DataMap {
  27434. /**
  27435. * Constructs a new background management component.
  27436. *
  27437. * @param {Renderer} renderer - The renderer.
  27438. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  27439. */
  27440. constructor( renderer, nodes ) {
  27441. super();
  27442. /**
  27443. * The renderer.
  27444. *
  27445. * @type {Renderer}
  27446. */
  27447. this.renderer = renderer;
  27448. /**
  27449. * Renderer component for managing nodes related logic.
  27450. *
  27451. * @type {Nodes}
  27452. */
  27453. this.nodes = nodes;
  27454. }
  27455. /**
  27456. * Updates the background for the given scene. Depending on how `Scene.background`
  27457. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  27458. * or add a mesh to the render list for rendering the background as a textured plane
  27459. * or skybox.
  27460. *
  27461. * @param {Scene} scene - The scene.
  27462. * @param {RenderList} renderList - The current render list.
  27463. * @param {RenderContext} renderContext - The current render context.
  27464. */
  27465. update( scene, renderList, renderContext ) {
  27466. const renderer = this.renderer;
  27467. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  27468. let forceClear = false;
  27469. if ( background === null ) {
  27470. // no background settings, use clear color configuration from the renderer
  27471. renderer._clearColor.getRGB( _clearColor$1, LinearSRGBColorSpace );
  27472. _clearColor$1.a = renderer._clearColor.a;
  27473. } else if ( background.isColor === true ) {
  27474. // background is an opaque color
  27475. background.getRGB( _clearColor$1, LinearSRGBColorSpace );
  27476. _clearColor$1.a = 1;
  27477. forceClear = true;
  27478. } else if ( background.isNode === true ) {
  27479. const sceneData = this.get( scene );
  27480. const backgroundNode = background;
  27481. _clearColor$1.copy( renderer._clearColor );
  27482. let backgroundMesh = sceneData.backgroundMesh;
  27483. if ( backgroundMesh === undefined ) {
  27484. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  27485. // @TODO: Add Texture2D support using node context
  27486. getUV: () => backgroundRotation.mul( normalWorld ),
  27487. getTextureLevel: () => backgroundBlurriness
  27488. } );
  27489. let viewProj = modelViewProjection;
  27490. viewProj = viewProj.setZ( viewProj.w );
  27491. const nodeMaterial = new NodeMaterial();
  27492. nodeMaterial.name = 'Background.material';
  27493. nodeMaterial.side = BackSide;
  27494. nodeMaterial.depthTest = false;
  27495. nodeMaterial.depthWrite = false;
  27496. nodeMaterial.fog = false;
  27497. nodeMaterial.lights = false;
  27498. nodeMaterial.vertexNode = viewProj;
  27499. nodeMaterial.colorNode = backgroundMeshNode;
  27500. sceneData.backgroundMeshNode = backgroundMeshNode;
  27501. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  27502. backgroundMesh.frustumCulled = false;
  27503. backgroundMesh.name = 'Background.mesh';
  27504. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  27505. this.matrixWorld.copyPosition( camera.matrixWorld );
  27506. };
  27507. }
  27508. const backgroundCacheKey = backgroundNode.getCacheKey();
  27509. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  27510. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  27511. sceneData.backgroundMeshNode.needsUpdate = true;
  27512. backgroundMesh.material.needsUpdate = true;
  27513. sceneData.backgroundCacheKey = backgroundCacheKey;
  27514. }
  27515. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  27516. } else {
  27517. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  27518. }
  27519. //
  27520. if ( renderer.autoClear === true || forceClear === true ) {
  27521. const clearColorValue = renderContext.clearColorValue;
  27522. clearColorValue.r = _clearColor$1.r;
  27523. clearColorValue.g = _clearColor$1.g;
  27524. clearColorValue.b = _clearColor$1.b;
  27525. clearColorValue.a = _clearColor$1.a;
  27526. // premultiply alpha
  27527. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  27528. clearColorValue.r *= clearColorValue.a;
  27529. clearColorValue.g *= clearColorValue.a;
  27530. clearColorValue.b *= clearColorValue.a;
  27531. }
  27532. //
  27533. renderContext.depthClearValue = renderer._clearDepth;
  27534. renderContext.stencilClearValue = renderer._clearStencil;
  27535. renderContext.clearColor = renderer.autoClearColor === true;
  27536. renderContext.clearDepth = renderer.autoClearDepth === true;
  27537. renderContext.clearStencil = renderer.autoClearStencil === true;
  27538. } else {
  27539. renderContext.clearColor = false;
  27540. renderContext.clearDepth = false;
  27541. renderContext.clearStencil = false;
  27542. }
  27543. }
  27544. }
  27545. let _id$6 = 0;
  27546. /**
  27547. * A bind group represents a collection of bindings and thus a collection
  27548. * or resources. Bind groups are assigned to pipelines to provide them
  27549. * with the required resources (like uniform buffers or textures).
  27550. *
  27551. * @private
  27552. */
  27553. class BindGroup {
  27554. /**
  27555. * Constructs a new bind group.
  27556. *
  27557. * @param {String} name - The bind group's name.
  27558. * @param {Array<Binding>} bindings - An array of bindings.
  27559. * @param {Number} index - The group index.
  27560. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  27561. */
  27562. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  27563. /**
  27564. * The bind group's name.
  27565. *
  27566. * @type {String}
  27567. */
  27568. this.name = name;
  27569. /**
  27570. * An array of bindings.
  27571. *
  27572. * @type {Array<Binding>}
  27573. */
  27574. this.bindings = bindings;
  27575. /**
  27576. * The group index.
  27577. *
  27578. * @type {Number}
  27579. */
  27580. this.index = index;
  27581. /**
  27582. * An array of reference bindings.
  27583. *
  27584. * @type {Array<Binding>}
  27585. */
  27586. this.bindingsReference = bindingsReference;
  27587. /**
  27588. * The group's ID.
  27589. *
  27590. * @type {Number}
  27591. */
  27592. this.id = _id$6 ++;
  27593. }
  27594. }
  27595. /**
  27596. * This module represents the state of a node builder after it was
  27597. * used to build the nodes for a render object. The state holds the
  27598. * results of the build for further processing in the renderer.
  27599. *
  27600. * Render objects with identical cache keys share the same node builder state.
  27601. *
  27602. * @private
  27603. */
  27604. class NodeBuilderState {
  27605. /**
  27606. * Constructs a new node builder state.
  27607. *
  27608. * @param {String?} vertexShader - The native vertex shader code.
  27609. * @param {String?} fragmentShader - The native fragment shader code.
  27610. * @param {String?} computeShader - The native compute shader code.
  27611. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  27612. * @param {Array<BindGroup>} bindings - An array of bind groups.
  27613. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  27614. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  27615. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  27616. * @param {NodeMaterialObserver} monitor - A node material observer.
  27617. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  27618. */
  27619. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, monitor, transforms = [] ) {
  27620. /**
  27621. * The native vertex shader code.
  27622. *
  27623. * @type {String}
  27624. */
  27625. this.vertexShader = vertexShader;
  27626. /**
  27627. * The native fragment shader code.
  27628. *
  27629. * @type {String}
  27630. */
  27631. this.fragmentShader = fragmentShader;
  27632. /**
  27633. * The native compute shader code.
  27634. *
  27635. * @type {String}
  27636. */
  27637. this.computeShader = computeShader;
  27638. /**
  27639. * An array with transform attribute objects.
  27640. * Only relevant when using compute shaders with WebGL 2.
  27641. *
  27642. * @type {Array<Object>}
  27643. */
  27644. this.transforms = transforms;
  27645. /**
  27646. * An array of node attributes representing
  27647. * the attributes of the shaders.
  27648. *
  27649. * @type {Array<NodeAttribute>}
  27650. */
  27651. this.nodeAttributes = nodeAttributes;
  27652. /**
  27653. * An array of bind groups representing the uniform or storage
  27654. * buffers, texture or samplers of the shader.
  27655. *
  27656. * @type {Array<BindGroup>}
  27657. */
  27658. this.bindings = bindings;
  27659. /**
  27660. * An array of nodes that implement their `update()` method.
  27661. *
  27662. * @type {Array<Node>}
  27663. */
  27664. this.updateNodes = updateNodes;
  27665. /**
  27666. * An array of nodes that implement their `updateBefore()` method.
  27667. *
  27668. * @type {Array<Node>}
  27669. */
  27670. this.updateBeforeNodes = updateBeforeNodes;
  27671. /**
  27672. * An array of nodes that implement their `updateAfter()` method.
  27673. *
  27674. * @type {Array<Node>}
  27675. */
  27676. this.updateAfterNodes = updateAfterNodes;
  27677. /**
  27678. * A node material observer.
  27679. *
  27680. * @type {NodeMaterialObserver}
  27681. */
  27682. this.monitor = monitor;
  27683. /**
  27684. * How often this state is used by render objects.
  27685. *
  27686. * @type {Number}
  27687. */
  27688. this.usedTimes = 0;
  27689. }
  27690. /**
  27691. * This method is used to create a array of bind groups based
  27692. * on the existing bind groups of this state. Shared groups are
  27693. * not cloned.
  27694. *
  27695. * @return {Array<BindGroup>} A array of bind groups.
  27696. */
  27697. createBindings() {
  27698. const bindings = [];
  27699. for ( const instanceGroup of this.bindings ) {
  27700. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // TODO: Is it safe to always check the first binding in the group?
  27701. if ( shared !== true ) {
  27702. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  27703. bindings.push( bindingsGroup );
  27704. for ( const instanceBinding of instanceGroup.bindings ) {
  27705. bindingsGroup.bindings.push( instanceBinding.clone() );
  27706. }
  27707. } else {
  27708. bindings.push( instanceGroup );
  27709. }
  27710. }
  27711. return bindings;
  27712. }
  27713. }
  27714. /**
  27715. * {@link NodeBuilder} is going to create instances of this class during the build process
  27716. * of nodes. They represent the final shader attributes that are going to be generated
  27717. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  27718. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  27719. */
  27720. class NodeAttribute {
  27721. /**
  27722. * Constructs a new node attribute.
  27723. *
  27724. * @param {String} name - The name of the attribute.
  27725. * @param {String} type - The type of the attribute.
  27726. * @param {Node?} node - An optional reference to the node.
  27727. */
  27728. constructor( name, type, node = null ) {
  27729. /**
  27730. * This flag can be used for type testing.
  27731. *
  27732. * @type {Boolean}
  27733. * @readonly
  27734. * @default true
  27735. */
  27736. this.isNodeAttribute = true;
  27737. /**
  27738. * The name of the attribute.
  27739. *
  27740. * @type {String}
  27741. */
  27742. this.name = name;
  27743. /**
  27744. * The type of the attribute.
  27745. *
  27746. * @type {String}
  27747. */
  27748. this.type = type;
  27749. /**
  27750. * An optional reference to the node.
  27751. *
  27752. * @type {Node?}
  27753. * @default null
  27754. */
  27755. this.node = node;
  27756. }
  27757. }
  27758. /**
  27759. * {@link NodeBuilder} is going to create instances of this class during the build process
  27760. * of nodes. They represent the final shader uniforms that are going to be generated
  27761. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  27762. * for this purpose.
  27763. */
  27764. class NodeUniform {
  27765. /**
  27766. * Constructs a new node uniform.
  27767. *
  27768. * @param {String} name - The name of the uniform.
  27769. * @param {String} type - The type of the uniform.
  27770. * @param {UniformNode} node - An reference to the node.
  27771. */
  27772. constructor( name, type, node ) {
  27773. /**
  27774. * This flag can be used for type testing.
  27775. *
  27776. * @type {Boolean}
  27777. * @readonly
  27778. * @default true
  27779. */
  27780. this.isNodeUniform = true;
  27781. /**
  27782. * The name of the uniform.
  27783. *
  27784. * @type {String}
  27785. */
  27786. this.name = name;
  27787. /**
  27788. * The type of the uniform.
  27789. *
  27790. * @type {String}
  27791. */
  27792. this.type = type;
  27793. /**
  27794. * An reference to the node.
  27795. *
  27796. * @type {UniformNode}
  27797. */
  27798. this.node = node.getSelf();
  27799. }
  27800. /**
  27801. * The value of the uniform node.
  27802. *
  27803. * @type {Any}
  27804. */
  27805. get value() {
  27806. return this.node.value;
  27807. }
  27808. set value( val ) {
  27809. this.node.value = val;
  27810. }
  27811. /**
  27812. * The id of the uniform node.
  27813. *
  27814. * @type {Number}
  27815. */
  27816. get id() {
  27817. return this.node.id;
  27818. }
  27819. /**
  27820. * The uniform node's group.
  27821. *
  27822. * @type {UniformGroupNode}
  27823. */
  27824. get groupNode() {
  27825. return this.node.groupNode;
  27826. }
  27827. }
  27828. /**
  27829. * {@link NodeBuilder} is going to create instances of this class during the build process
  27830. * of nodes. They represent the final shader variables that are going to be generated
  27831. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  27832. * this purpose.
  27833. */
  27834. class NodeVar {
  27835. /**
  27836. * Constructs a new node variable.
  27837. *
  27838. * @param {String} name - The name of the variable.
  27839. * @param {String} type - The type of the variable.
  27840. */
  27841. constructor( name, type ) {
  27842. /**
  27843. * This flag can be used for type testing.
  27844. *
  27845. * @type {Boolean}
  27846. * @readonly
  27847. * @default true
  27848. */
  27849. this.isNodeVar = true;
  27850. /**
  27851. * The name of the variable.
  27852. *
  27853. * @type {String}
  27854. */
  27855. this.name = name;
  27856. /**
  27857. * The type of the variable.
  27858. *
  27859. * @type {String}
  27860. */
  27861. this.type = type;
  27862. }
  27863. }
  27864. /**
  27865. * {@link NodeBuilder} is going to create instances of this class during the build process
  27866. * of nodes. They represent the final shader varyings that are going to be generated
  27867. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  27868. * this purpose.
  27869. *
  27870. * @augments NodeVar
  27871. */
  27872. class NodeVarying extends NodeVar {
  27873. /**
  27874. * Constructs a new node varying.
  27875. *
  27876. * @param {String} name - The name of the varying.
  27877. * @param {String} type - The type of the varying.
  27878. */
  27879. constructor( name, type ) {
  27880. super( name, type );
  27881. /**
  27882. * Whether this varying requires interpolation or not. This property can be used
  27883. * to check if the varying can be optimized for a variable.
  27884. *
  27885. * @type {Boolean}
  27886. * @default false
  27887. */
  27888. this.needsInterpolation = false;
  27889. /**
  27890. * This flag can be used for type testing.
  27891. *
  27892. * @type {Boolean}
  27893. * @readonly
  27894. * @default true
  27895. */
  27896. this.isNodeVarying = true;
  27897. }
  27898. }
  27899. /**
  27900. * {@link NodeBuilder} is going to create instances of this class during the build process
  27901. * of nodes. They represent user-defined, native shader code portions that are going to be
  27902. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  27903. * for this purpose.
  27904. */
  27905. class NodeCode {
  27906. /**
  27907. * Constructs a new code node.
  27908. *
  27909. * @param {String} name - The name of the code.
  27910. * @param {String} type - The node type.
  27911. * @param {String} [code=''] - The native shader code.
  27912. */
  27913. constructor( name, type, code = '' ) {
  27914. /**
  27915. * The name of the code.
  27916. *
  27917. * @type {String}
  27918. */
  27919. this.name = name;
  27920. /**
  27921. * The node type.
  27922. *
  27923. * @type {String}
  27924. */
  27925. this.type = type;
  27926. /**
  27927. * The native shader code.
  27928. *
  27929. * @type {String}
  27930. * @default ''
  27931. */
  27932. this.code = code;
  27933. Object.defineProperty( this, 'isNodeCode', { value: true } );
  27934. }
  27935. }
  27936. let _id$5 = 0;
  27937. /**
  27938. * This utility class is used in {@link NodeBuilder} as an internal
  27939. * cache data structure for node data.
  27940. */
  27941. class NodeCache {
  27942. /**
  27943. * Constructs a new node cache.
  27944. *
  27945. * @param {NodeCache?} parent - A reference to a parent cache.
  27946. */
  27947. constructor( parent = null ) {
  27948. /**
  27949. * The id of the cache.
  27950. *
  27951. * @type {Number}
  27952. * @readonly
  27953. */
  27954. this.id = _id$5 ++;
  27955. /**
  27956. * A weak map for managing node data.
  27957. *
  27958. * @type {WeakMap<Node, Object>}
  27959. */
  27960. this.nodesData = new WeakMap();
  27961. /**
  27962. * Reference to a parent node cache.
  27963. *
  27964. * @type {NodeCache?}
  27965. * @default null
  27966. */
  27967. this.parent = parent;
  27968. }
  27969. /**
  27970. * Returns the data for the given node.
  27971. *
  27972. * @param {Node} node - The node.
  27973. * @return {Object?} The data for the node.
  27974. */
  27975. getData( node ) {
  27976. let data = this.nodesData.get( node );
  27977. if ( data === undefined && this.parent !== null ) {
  27978. data = this.parent.getData( node );
  27979. }
  27980. return data;
  27981. }
  27982. /**
  27983. * Sets the data for a given node.
  27984. *
  27985. * @param {Node} node - The node.
  27986. * @param {Object} data - The data that should be cached.
  27987. */
  27988. setData( node, data ) {
  27989. this.nodesData.set( node, data );
  27990. }
  27991. }
  27992. /**
  27993. * {@link NodeBuilder} is going to create instances of this class during the build process
  27994. * of nodes. They represent the final shader struct data that are going to be generated
  27995. * by the builder. A dictionary of struct types is maintained in {@link NodeBuilder#structs}
  27996. * for this purpose.
  27997. */
  27998. class StructTypeNode extends Node {
  27999. static get type() {
  28000. return 'StructTypeNode';
  28001. }
  28002. /**
  28003. * Constructs a new struct type node.
  28004. *
  28005. * @param {String} name - The name of the struct.
  28006. * @param {Array<String>} types - An array of types.
  28007. */
  28008. constructor( name, types ) {
  28009. super();
  28010. /**
  28011. * The name of the struct.
  28012. *
  28013. * @type {String}
  28014. */
  28015. this.name = name;
  28016. /**
  28017. * An array of types.
  28018. *
  28019. * @type {Array<String>}
  28020. */
  28021. this.types = types;
  28022. /**
  28023. * This flag can be used for type testing.
  28024. *
  28025. * @type {Boolean}
  28026. * @readonly
  28027. * @default true
  28028. */
  28029. this.isStructTypeNode = true;
  28030. }
  28031. /**
  28032. * Returns the member types.
  28033. *
  28034. * @return {Array<String>} The types.
  28035. */
  28036. getMemberTypes() {
  28037. return this.types;
  28038. }
  28039. }
  28040. /**
  28041. * Abstract base class for uniforms.
  28042. *
  28043. * @abstract
  28044. * @private
  28045. */
  28046. class Uniform {
  28047. /**
  28048. * Constructs a new uniform.
  28049. *
  28050. * @param {String} name - The uniform's name.
  28051. * @param {Any} value - The uniform's value.
  28052. */
  28053. constructor( name, value ) {
  28054. /**
  28055. * The uniform's name.
  28056. *
  28057. * @type {String}
  28058. */
  28059. this.name = name;
  28060. /**
  28061. * The uniform's value.
  28062. *
  28063. * @type {Any}
  28064. */
  28065. this.value = value;
  28066. /**
  28067. * Used to build the uniform buffer according to the STD140 layout.
  28068. * Derived uniforms will set this property to a data type specific
  28069. * value.
  28070. *
  28071. * @type {Number}
  28072. */
  28073. this.boundary = 0;
  28074. /**
  28075. * The item size. Derived uniforms will set this property to a data
  28076. * type specific value.
  28077. *
  28078. * @type {Number}
  28079. */
  28080. this.itemSize = 0;
  28081. /**
  28082. * This property is set by {@link UniformsGroup} and marks
  28083. * the start position in the uniform buffer.
  28084. *
  28085. * @type {Number}
  28086. */
  28087. this.offset = 0;
  28088. }
  28089. /**
  28090. * Sets the uniform's value.
  28091. *
  28092. * @param {Any} value - The value to set.
  28093. */
  28094. setValue( value ) {
  28095. this.value = value;
  28096. }
  28097. /**
  28098. * Returns the uniform's value.
  28099. *
  28100. * @return {Any} The value.
  28101. */
  28102. getValue() {
  28103. return this.value;
  28104. }
  28105. }
  28106. /**
  28107. * Represents a Number uniform.
  28108. *
  28109. * @private
  28110. * @augments Uniform
  28111. */
  28112. class NumberUniform extends Uniform {
  28113. /**
  28114. * Constructs a new Number uniform.
  28115. *
  28116. * @param {String} name - The uniform's name.
  28117. * @param {Number} value - The uniform's value.
  28118. */
  28119. constructor( name, value = 0 ) {
  28120. super( name, value );
  28121. /**
  28122. * This flag can be used for type testing.
  28123. *
  28124. * @type {Boolean}
  28125. * @readonly
  28126. * @default true
  28127. */
  28128. this.isNumberUniform = true;
  28129. this.boundary = 4;
  28130. this.itemSize = 1;
  28131. }
  28132. }
  28133. /**
  28134. * Represents a Vector2 uniform.
  28135. *
  28136. * @private
  28137. * @augments Uniform
  28138. */
  28139. class Vector2Uniform extends Uniform {
  28140. /**
  28141. * Constructs a new Number uniform.
  28142. *
  28143. * @param {String} name - The uniform's name.
  28144. * @param {Vector2} value - The uniform's value.
  28145. */
  28146. constructor( name, value = new Vector2() ) {
  28147. super( name, value );
  28148. /**
  28149. * This flag can be used for type testing.
  28150. *
  28151. * @type {Boolean}
  28152. * @readonly
  28153. * @default true
  28154. */
  28155. this.isVector2Uniform = true;
  28156. this.boundary = 8;
  28157. this.itemSize = 2;
  28158. }
  28159. }
  28160. /**
  28161. * Represents a Vector3 uniform.
  28162. *
  28163. * @private
  28164. * @augments Uniform
  28165. */
  28166. class Vector3Uniform extends Uniform {
  28167. /**
  28168. * Constructs a new Number uniform.
  28169. *
  28170. * @param {String} name - The uniform's name.
  28171. * @param {Vector3} value - The uniform's value.
  28172. */
  28173. constructor( name, value = new Vector3() ) {
  28174. super( name, value );
  28175. /**
  28176. * This flag can be used for type testing.
  28177. *
  28178. * @type {Boolean}
  28179. * @readonly
  28180. * @default true
  28181. */
  28182. this.isVector3Uniform = true;
  28183. this.boundary = 16;
  28184. this.itemSize = 3;
  28185. }
  28186. }
  28187. /**
  28188. * Represents a Vector4 uniform.
  28189. *
  28190. * @private
  28191. * @augments Uniform
  28192. */
  28193. class Vector4Uniform extends Uniform {
  28194. /**
  28195. * Constructs a new Number uniform.
  28196. *
  28197. * @param {String} name - The uniform's name.
  28198. * @param {Vector4} value - The uniform's value.
  28199. */
  28200. constructor( name, value = new Vector4() ) {
  28201. super( name, value );
  28202. /**
  28203. * This flag can be used for type testing.
  28204. *
  28205. * @type {Boolean}
  28206. * @readonly
  28207. * @default true
  28208. */
  28209. this.isVector4Uniform = true;
  28210. this.boundary = 16;
  28211. this.itemSize = 4;
  28212. }
  28213. }
  28214. /**
  28215. * Represents a Color uniform.
  28216. *
  28217. * @private
  28218. * @augments Uniform
  28219. */
  28220. class ColorUniform extends Uniform {
  28221. /**
  28222. * Constructs a new Number uniform.
  28223. *
  28224. * @param {String} name - The uniform's name.
  28225. * @param {Color} value - The uniform's value.
  28226. */
  28227. constructor( name, value = new Color() ) {
  28228. super( name, value );
  28229. /**
  28230. * This flag can be used for type testing.
  28231. *
  28232. * @type {Boolean}
  28233. * @readonly
  28234. * @default true
  28235. */
  28236. this.isColorUniform = true;
  28237. this.boundary = 16;
  28238. this.itemSize = 3;
  28239. }
  28240. }
  28241. /**
  28242. * Represents a Matrix3 uniform.
  28243. *
  28244. * @private
  28245. * @augments Uniform
  28246. */
  28247. class Matrix3Uniform extends Uniform {
  28248. /**
  28249. * Constructs a new Number uniform.
  28250. *
  28251. * @param {String} name - The uniform's name.
  28252. * @param {Matrix3} value - The uniform's value.
  28253. */
  28254. constructor( name, value = new Matrix3() ) {
  28255. super( name, value );
  28256. /**
  28257. * This flag can be used for type testing.
  28258. *
  28259. * @type {Boolean}
  28260. * @readonly
  28261. * @default true
  28262. */
  28263. this.isMatrix3Uniform = true;
  28264. this.boundary = 48;
  28265. this.itemSize = 12;
  28266. }
  28267. }
  28268. /**
  28269. * Represents a Matrix4 uniform.
  28270. *
  28271. * @private
  28272. * @augments Uniform
  28273. */
  28274. class Matrix4Uniform extends Uniform {
  28275. /**
  28276. * Constructs a new Number uniform.
  28277. *
  28278. * @param {String} name - The uniform's name.
  28279. * @param {Matrix4} value - The uniform's value.
  28280. */
  28281. constructor( name, value = new Matrix4() ) {
  28282. super( name, value );
  28283. /**
  28284. * This flag can be used for type testing.
  28285. *
  28286. * @type {Boolean}
  28287. * @readonly
  28288. * @default true
  28289. */
  28290. this.isMatrix4Uniform = true;
  28291. this.boundary = 64;
  28292. this.itemSize = 16;
  28293. }
  28294. }
  28295. /**
  28296. * A special form of Number uniform binding type.
  28297. * It's value is managed by a node object.
  28298. *
  28299. * @private
  28300. * @augments NumberUniform
  28301. */
  28302. class NumberNodeUniform extends NumberUniform {
  28303. /**
  28304. * Constructs a new node-based Number uniform.
  28305. *
  28306. * @param {NodeUniform} nodeUniform - The node uniform.
  28307. */
  28308. constructor( nodeUniform ) {
  28309. super( nodeUniform.name, nodeUniform.value );
  28310. /**
  28311. * The node uniform.
  28312. *
  28313. * @type {NodeUniform}
  28314. */
  28315. this.nodeUniform = nodeUniform;
  28316. }
  28317. /**
  28318. * Overwritten to return the value of the node uniform.
  28319. *
  28320. * @return {Number} The value.
  28321. */
  28322. getValue() {
  28323. return this.nodeUniform.value;
  28324. }
  28325. /**
  28326. * Returns the node uniform data type.
  28327. *
  28328. * @return {String} The data type.
  28329. */
  28330. getType() {
  28331. return this.nodeUniform.type;
  28332. }
  28333. }
  28334. /**
  28335. * A special form of Vector2 uniform binding type.
  28336. * It's value is managed by a node object.
  28337. *
  28338. * @private
  28339. * @augments Vector2Uniform
  28340. */
  28341. class Vector2NodeUniform extends Vector2Uniform {
  28342. /**
  28343. * Constructs a new node-based Vector2 uniform.
  28344. *
  28345. * @param {NodeUniform} nodeUniform - The node uniform.
  28346. */
  28347. constructor( nodeUniform ) {
  28348. super( nodeUniform.name, nodeUniform.value );
  28349. /**
  28350. * The node uniform.
  28351. *
  28352. * @type {NodeUniform}
  28353. */
  28354. this.nodeUniform = nodeUniform;
  28355. }
  28356. /**
  28357. * Overwritten to return the value of the node uniform.
  28358. *
  28359. * @return {Vector2} The value.
  28360. */
  28361. getValue() {
  28362. return this.nodeUniform.value;
  28363. }
  28364. /**
  28365. * Returns the node uniform data type.
  28366. *
  28367. * @return {String} The data type.
  28368. */
  28369. getType() {
  28370. return this.nodeUniform.type;
  28371. }
  28372. }
  28373. /**
  28374. * A special form of Vector3 uniform binding type.
  28375. * It's value is managed by a node object.
  28376. *
  28377. * @private
  28378. * @augments Vector3Uniform
  28379. */
  28380. class Vector3NodeUniform extends Vector3Uniform {
  28381. /**
  28382. * Constructs a new node-based Vector3 uniform.
  28383. *
  28384. * @param {NodeUniform} nodeUniform - The node uniform.
  28385. */
  28386. constructor( nodeUniform ) {
  28387. super( nodeUniform.name, nodeUniform.value );
  28388. /**
  28389. * The node uniform.
  28390. *
  28391. * @type {NodeUniform}
  28392. */
  28393. this.nodeUniform = nodeUniform;
  28394. }
  28395. /**
  28396. * Overwritten to return the value of the node uniform.
  28397. *
  28398. * @return {Vector3} The value.
  28399. */
  28400. getValue() {
  28401. return this.nodeUniform.value;
  28402. }
  28403. /**
  28404. * Returns the node uniform data type.
  28405. *
  28406. * @return {String} The data type.
  28407. */
  28408. getType() {
  28409. return this.nodeUniform.type;
  28410. }
  28411. }
  28412. /**
  28413. * A special form of Vector4 uniform binding type.
  28414. * It's value is managed by a node object.
  28415. *
  28416. * @private
  28417. * @augments Vector4Uniform
  28418. */
  28419. class Vector4NodeUniform extends Vector4Uniform {
  28420. /**
  28421. * Constructs a new node-based Vector4 uniform.
  28422. *
  28423. * @param {NodeUniform} nodeUniform - The node uniform.
  28424. */
  28425. constructor( nodeUniform ) {
  28426. super( nodeUniform.name, nodeUniform.value );
  28427. /**
  28428. * The node uniform.
  28429. *
  28430. * @type {NodeUniform}
  28431. */
  28432. this.nodeUniform = nodeUniform;
  28433. }
  28434. /**
  28435. * Overwritten to return the value of the node uniform.
  28436. *
  28437. * @return {Vector4} The value.
  28438. */
  28439. getValue() {
  28440. return this.nodeUniform.value;
  28441. }
  28442. /**
  28443. * Returns the node uniform data type.
  28444. *
  28445. * @return {String} The data type.
  28446. */
  28447. getType() {
  28448. return this.nodeUniform.type;
  28449. }
  28450. }
  28451. /**
  28452. * A special form of Color uniform binding type.
  28453. * It's value is managed by a node object.
  28454. *
  28455. * @private
  28456. * @augments ColorUniform
  28457. */
  28458. class ColorNodeUniform extends ColorUniform {
  28459. /**
  28460. * Constructs a new node-based Color uniform.
  28461. *
  28462. * @param {NodeUniform} nodeUniform - The node uniform.
  28463. */
  28464. constructor( nodeUniform ) {
  28465. super( nodeUniform.name, nodeUniform.value );
  28466. /**
  28467. * The node uniform.
  28468. *
  28469. * @type {NodeUniform}
  28470. */
  28471. this.nodeUniform = nodeUniform;
  28472. }
  28473. /**
  28474. * Overwritten to return the value of the node uniform.
  28475. *
  28476. * @return {Color} The value.
  28477. */
  28478. getValue() {
  28479. return this.nodeUniform.value;
  28480. }
  28481. /**
  28482. * Returns the node uniform data type.
  28483. *
  28484. * @return {String} The data type.
  28485. */
  28486. getType() {
  28487. return this.nodeUniform.type;
  28488. }
  28489. }
  28490. /**
  28491. * A special form of Matrix3 uniform binding type.
  28492. * It's value is managed by a node object.
  28493. *
  28494. * @private
  28495. * @augments Matrix3Uniform
  28496. */
  28497. class Matrix3NodeUniform extends Matrix3Uniform {
  28498. /**
  28499. * Constructs a new node-based Matrix3 uniform.
  28500. *
  28501. * @param {NodeUniform} nodeUniform - The node uniform.
  28502. */
  28503. constructor( nodeUniform ) {
  28504. super( nodeUniform.name, nodeUniform.value );
  28505. /**
  28506. * The node uniform.
  28507. *
  28508. * @type {NodeUniform}
  28509. */
  28510. this.nodeUniform = nodeUniform;
  28511. }
  28512. /**
  28513. * Overwritten to return the value of the node uniform.
  28514. *
  28515. * @return {Matrix3} The value.
  28516. */
  28517. getValue() {
  28518. return this.nodeUniform.value;
  28519. }
  28520. /**
  28521. * Returns the node uniform data type.
  28522. *
  28523. * @return {String} The data type.
  28524. */
  28525. getType() {
  28526. return this.nodeUniform.type;
  28527. }
  28528. }
  28529. /**
  28530. * A special form of Matrix4 uniform binding type.
  28531. * It's value is managed by a node object.
  28532. *
  28533. * @private
  28534. * @augments Matrix4Uniform
  28535. */
  28536. class Matrix4NodeUniform extends Matrix4Uniform {
  28537. /**
  28538. * Constructs a new node-based Matrix4 uniform.
  28539. *
  28540. * @param {NodeUniform} nodeUniform - The node uniform.
  28541. */
  28542. constructor( nodeUniform ) {
  28543. super( nodeUniform.name, nodeUniform.value );
  28544. /**
  28545. * The node uniform.
  28546. *
  28547. * @type {NodeUniform}
  28548. */
  28549. this.nodeUniform = nodeUniform;
  28550. }
  28551. /**
  28552. * Overwritten to return the value of the node uniform.
  28553. *
  28554. * @return {Matrix4} The value.
  28555. */
  28556. getValue() {
  28557. return this.nodeUniform.value;
  28558. }
  28559. /**
  28560. * Returns the node uniform data type.
  28561. *
  28562. * @return {String} The data type.
  28563. */
  28564. getType() {
  28565. return this.nodeUniform.type;
  28566. }
  28567. }
  28568. const LOD_MIN = 4;
  28569. // The standard deviations (radians) associated with the extra mips. These are
  28570. // chosen to approximate a Trowbridge-Reitz distribution function times the
  28571. // geometric shadowing function. These sigma values squared must match the
  28572. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  28573. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  28574. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  28575. // samples and exit early, but not recompile the shader.
  28576. const MAX_SAMPLES = 20;
  28577. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  28578. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  28579. const _clearColor = /*@__PURE__*/ new Color();
  28580. let _oldTarget = null;
  28581. let _oldActiveCubeFace = 0;
  28582. let _oldActiveMipmapLevel = 0;
  28583. // Golden Ratio
  28584. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  28585. const INV_PHI = 1 / PHI;
  28586. // Vertices of a dodecahedron (except the opposites, which represent the
  28587. // same axis), used as axis directions evenly spread on a sphere.
  28588. const _axisDirections = [
  28589. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  28590. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  28591. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  28592. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  28593. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  28594. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  28595. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  28596. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  28597. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  28598. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  28599. ];
  28600. //
  28601. // WebGPU Face indices
  28602. const _faceLib = [
  28603. 3, 1, 5,
  28604. 0, 4, 2
  28605. ];
  28606. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  28607. const outputDirection = vec3( direction.x, direction.y, direction.z );
  28608. /**
  28609. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  28610. * (PMREM) from a cubeMap environment texture. This allows different levels of
  28611. * blur to be quickly accessed based on material roughness. It is packed into a
  28612. * special CubeUV format that allows us to perform custom interpolation so that
  28613. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  28614. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  28615. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  28616. * higher roughness levels. In this way we maintain resolution to smoothly
  28617. * interpolate diffuse lighting while limiting sampling computation.
  28618. *
  28619. * Paper: Fast, Accurate Image-Based Lighting
  28620. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  28621. */
  28622. class PMREMGenerator {
  28623. constructor( renderer ) {
  28624. this._renderer = renderer;
  28625. this._pingPongRenderTarget = null;
  28626. this._lodMax = 0;
  28627. this._cubeSize = 0;
  28628. this._lodPlanes = [];
  28629. this._sizeLods = [];
  28630. this._sigmas = [];
  28631. this._lodMeshes = [];
  28632. this._blurMaterial = null;
  28633. this._cubemapMaterial = null;
  28634. this._equirectMaterial = null;
  28635. this._backgroundBox = null;
  28636. }
  28637. get _hasInitialized() {
  28638. return this._renderer.hasInitialized();
  28639. }
  28640. /**
  28641. * Generates a PMREM from a supplied Scene, which can be faster than using an
  28642. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  28643. * in radians to be applied to the scene before PMREM generation. Optional near
  28644. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  28645. * is placed at the origin).
  28646. *
  28647. * @param {Scene} scene - The scene to be captured.
  28648. * @param {Number} [sigma=0] - The blur radius in radians.
  28649. * @param {Number} [near=0.1] - The near plane distance.
  28650. * @param {Number} [far=100] - The far plane distance.
  28651. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  28652. * @return {RenderTarget} The resulting PMREM.
  28653. */
  28654. fromScene( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  28655. this._setSize( 256 );
  28656. if ( this._hasInitialized === false ) {
  28657. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  28658. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  28659. this.fromSceneAsync( scene, sigma, near, far, cubeUVRenderTarget );
  28660. return cubeUVRenderTarget;
  28661. }
  28662. _oldTarget = this._renderer.getRenderTarget();
  28663. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  28664. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  28665. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  28666. cubeUVRenderTarget.depthBuffer = true;
  28667. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  28668. if ( sigma > 0 ) {
  28669. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  28670. }
  28671. this._applyPMREM( cubeUVRenderTarget );
  28672. this._cleanup( cubeUVRenderTarget );
  28673. return cubeUVRenderTarget;
  28674. }
  28675. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  28676. if ( this._hasInitialized === false ) await this._renderer.init();
  28677. return this.fromScene( scene, sigma, near, far, renderTarget );
  28678. }
  28679. /**
  28680. * Generates a PMREM from an equirectangular texture, which can be either LDR
  28681. * or HDR. The ideal input image size is 1k (1024 x 512),
  28682. * as this matches best with the 256 x 256 cubemap output.
  28683. *
  28684. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  28685. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  28686. * @return {RenderTarget} The resulting PMREM.
  28687. */
  28688. fromEquirectangular( equirectangular, renderTarget = null ) {
  28689. if ( this._hasInitialized === false ) {
  28690. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  28691. this._setSizeFromTexture( equirectangular );
  28692. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  28693. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  28694. return cubeUVRenderTarget;
  28695. }
  28696. return this._fromTexture( equirectangular, renderTarget );
  28697. }
  28698. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  28699. if ( this._hasInitialized === false ) await this._renderer.init();
  28700. return this._fromTexture( equirectangular, renderTarget );
  28701. }
  28702. /**
  28703. * Generates a PMREM from an cubemap texture, which can be either LDR
  28704. * or HDR. The ideal input cube size is 256 x 256,
  28705. * as this matches best with the 256 x 256 cubemap output.
  28706. *
  28707. * @param {Texture} cubemap - The cubemap texture to be converted.
  28708. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  28709. * @return {RenderTarget} The resulting PMREM.
  28710. */
  28711. fromCubemap( cubemap, renderTarget = null ) {
  28712. if ( this._hasInitialized === false ) {
  28713. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  28714. this._setSizeFromTexture( cubemap );
  28715. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  28716. this.fromCubemapAsync( cubemap, renderTarget );
  28717. return cubeUVRenderTarget;
  28718. }
  28719. return this._fromTexture( cubemap, renderTarget );
  28720. }
  28721. async fromCubemapAsync( cubemap, renderTarget = null ) {
  28722. if ( this._hasInitialized === false ) await this._renderer.init();
  28723. return this._fromTexture( cubemap, renderTarget );
  28724. }
  28725. /**
  28726. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  28727. * your texture's network fetch for increased concurrency.
  28728. */
  28729. async compileCubemapShader() {
  28730. if ( this._cubemapMaterial === null ) {
  28731. this._cubemapMaterial = _getCubemapMaterial();
  28732. await this._compileMaterial( this._cubemapMaterial );
  28733. }
  28734. }
  28735. /**
  28736. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  28737. * your texture's network fetch for increased concurrency.
  28738. */
  28739. async compileEquirectangularShader() {
  28740. if ( this._equirectMaterial === null ) {
  28741. this._equirectMaterial = _getEquirectMaterial();
  28742. await this._compileMaterial( this._equirectMaterial );
  28743. }
  28744. }
  28745. /**
  28746. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  28747. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  28748. * one of them will cause any others to also become unusable.
  28749. */
  28750. dispose() {
  28751. this._dispose();
  28752. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  28753. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  28754. if ( this._backgroundBox !== null ) {
  28755. this._backgroundBox.geometry.dispose();
  28756. this._backgroundBox.material.dispose();
  28757. }
  28758. }
  28759. // private interface
  28760. _setSizeFromTexture( texture ) {
  28761. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  28762. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  28763. } else { // Equirectangular
  28764. this._setSize( texture.image.width / 4 );
  28765. }
  28766. }
  28767. _setSize( cubeSize ) {
  28768. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  28769. this._cubeSize = Math.pow( 2, this._lodMax );
  28770. }
  28771. _dispose() {
  28772. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  28773. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  28774. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  28775. this._lodPlanes[ i ].dispose();
  28776. }
  28777. }
  28778. _cleanup( outputTarget ) {
  28779. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  28780. outputTarget.scissorTest = false;
  28781. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  28782. }
  28783. _fromTexture( texture, renderTarget ) {
  28784. this._setSizeFromTexture( texture );
  28785. _oldTarget = this._renderer.getRenderTarget();
  28786. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  28787. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  28788. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  28789. this._textureToCubeUV( texture, cubeUVRenderTarget );
  28790. this._applyPMREM( cubeUVRenderTarget );
  28791. this._cleanup( cubeUVRenderTarget );
  28792. return cubeUVRenderTarget;
  28793. }
  28794. _allocateTargets() {
  28795. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  28796. const height = 4 * this._cubeSize;
  28797. const params = {
  28798. magFilter: LinearFilter,
  28799. minFilter: LinearFilter,
  28800. generateMipmaps: false,
  28801. type: HalfFloatType,
  28802. format: RGBAFormat,
  28803. colorSpace: LinearSRGBColorSpace,
  28804. //depthBuffer: false
  28805. };
  28806. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  28807. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  28808. if ( this._pingPongRenderTarget !== null ) {
  28809. this._dispose();
  28810. }
  28811. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  28812. const { _lodMax } = this;
  28813. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  28814. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  28815. }
  28816. return cubeUVRenderTarget;
  28817. }
  28818. async _compileMaterial( material ) {
  28819. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  28820. await this._renderer.compile( tmpMesh, _flatCamera );
  28821. }
  28822. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  28823. const cubeCamera = _cubeCamera;
  28824. cubeCamera.near = near;
  28825. cubeCamera.far = far;
  28826. // px, py, pz, nx, ny, nz
  28827. const upSign = [ 1, 1, 1, 1, - 1, 1 ];
  28828. const forwardSign = [ 1, - 1, 1, - 1, 1, - 1 ];
  28829. const renderer = this._renderer;
  28830. const originalAutoClear = renderer.autoClear;
  28831. renderer.getClearColor( _clearColor );
  28832. renderer.autoClear = false;
  28833. let backgroundBox = this._backgroundBox;
  28834. if ( backgroundBox === null ) {
  28835. const backgroundMaterial = new MeshBasicMaterial( {
  28836. name: 'PMREM.Background',
  28837. side: BackSide,
  28838. depthWrite: false,
  28839. depthTest: false
  28840. } );
  28841. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  28842. }
  28843. let useSolidColor = false;
  28844. const background = scene.background;
  28845. if ( background ) {
  28846. if ( background.isColor ) {
  28847. backgroundBox.material.color.copy( background );
  28848. scene.background = null;
  28849. useSolidColor = true;
  28850. }
  28851. } else {
  28852. backgroundBox.material.color.copy( _clearColor );
  28853. useSolidColor = true;
  28854. }
  28855. renderer.setRenderTarget( cubeUVRenderTarget );
  28856. renderer.clear();
  28857. if ( useSolidColor ) {
  28858. renderer.render( backgroundBox, cubeCamera );
  28859. }
  28860. for ( let i = 0; i < 6; i ++ ) {
  28861. const col = i % 3;
  28862. if ( col === 0 ) {
  28863. cubeCamera.up.set( 0, upSign[ i ], 0 );
  28864. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  28865. } else if ( col === 1 ) {
  28866. cubeCamera.up.set( 0, 0, upSign[ i ] );
  28867. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  28868. } else {
  28869. cubeCamera.up.set( 0, upSign[ i ], 0 );
  28870. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  28871. }
  28872. const size = this._cubeSize;
  28873. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  28874. renderer.render( scene, cubeCamera );
  28875. }
  28876. renderer.autoClear = originalAutoClear;
  28877. scene.background = background;
  28878. }
  28879. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  28880. const renderer = this._renderer;
  28881. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  28882. if ( isCubeTexture ) {
  28883. if ( this._cubemapMaterial === null ) {
  28884. this._cubemapMaterial = _getCubemapMaterial( texture );
  28885. }
  28886. } else {
  28887. if ( this._equirectMaterial === null ) {
  28888. this._equirectMaterial = _getEquirectMaterial( texture );
  28889. }
  28890. }
  28891. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  28892. material.fragmentNode.value = texture;
  28893. const mesh = this._lodMeshes[ 0 ];
  28894. mesh.material = material;
  28895. const size = this._cubeSize;
  28896. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  28897. renderer.setRenderTarget( cubeUVRenderTarget );
  28898. renderer.render( mesh, _flatCamera );
  28899. }
  28900. _applyPMREM( cubeUVRenderTarget ) {
  28901. const renderer = this._renderer;
  28902. const autoClear = renderer.autoClear;
  28903. renderer.autoClear = false;
  28904. const n = this._lodPlanes.length;
  28905. for ( let i = 1; i < n; i ++ ) {
  28906. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  28907. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  28908. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  28909. }
  28910. renderer.autoClear = autoClear;
  28911. }
  28912. /**
  28913. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  28914. * vertically and horizontally, but this breaks down on a cube. Here we apply
  28915. * the blur latitudinally (around the poles), and then longitudinally (towards
  28916. * the poles) to approximate the orthogonally-separable blur. It is least
  28917. * accurate at the poles, but still does a decent job.
  28918. *
  28919. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  28920. * @param {Number} lodIn - The input level-of-detail.
  28921. * @param {Number} lodOut - The output level-of-detail.
  28922. * @param {Number} sigma - The blur radius in radians.
  28923. * @param {Vector3} [poleAxis] - The pole axis.
  28924. */
  28925. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  28926. const pingPongRenderTarget = this._pingPongRenderTarget;
  28927. this._halfBlur(
  28928. cubeUVRenderTarget,
  28929. pingPongRenderTarget,
  28930. lodIn,
  28931. lodOut,
  28932. sigma,
  28933. 'latitudinal',
  28934. poleAxis );
  28935. this._halfBlur(
  28936. pingPongRenderTarget,
  28937. cubeUVRenderTarget,
  28938. lodOut,
  28939. lodOut,
  28940. sigma,
  28941. 'longitudinal',
  28942. poleAxis );
  28943. }
  28944. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  28945. const renderer = this._renderer;
  28946. const blurMaterial = this._blurMaterial;
  28947. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  28948. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  28949. }
  28950. // Number of standard deviations at which to cut off the discrete approximation.
  28951. const STANDARD_DEVIATIONS = 3;
  28952. const blurMesh = this._lodMeshes[ lodOut ];
  28953. blurMesh.material = blurMaterial;
  28954. const blurUniforms = blurMaterial.uniforms;
  28955. const pixels = this._sizeLods[ lodIn ] - 1;
  28956. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  28957. const sigmaPixels = sigmaRadians / radiansPerPixel;
  28958. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  28959. if ( samples > MAX_SAMPLES ) {
  28960. console.warn( `sigmaRadians, ${
  28961. sigmaRadians}, is too large and will clip, as it requested ${
  28962. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  28963. }
  28964. const weights = [];
  28965. let sum = 0;
  28966. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  28967. const x = i / sigmaPixels;
  28968. const weight = Math.exp( - x * x / 2 );
  28969. weights.push( weight );
  28970. if ( i === 0 ) {
  28971. sum += weight;
  28972. } else if ( i < samples ) {
  28973. sum += 2 * weight;
  28974. }
  28975. }
  28976. for ( let i = 0; i < weights.length; i ++ ) {
  28977. weights[ i ] = weights[ i ] / sum;
  28978. }
  28979. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  28980. blurUniforms.envMap.value = targetIn.texture;
  28981. blurUniforms.samples.value = samples;
  28982. blurUniforms.weights.array = weights;
  28983. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  28984. if ( poleAxis ) {
  28985. blurUniforms.poleAxis.value = poleAxis;
  28986. }
  28987. const { _lodMax } = this;
  28988. blurUniforms.dTheta.value = radiansPerPixel;
  28989. blurUniforms.mipInt.value = _lodMax - lodIn;
  28990. const outputSize = this._sizeLods[ lodOut ];
  28991. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  28992. const y = 4 * ( this._cubeSize - outputSize );
  28993. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  28994. renderer.setRenderTarget( targetOut );
  28995. renderer.render( blurMesh, _flatCamera );
  28996. }
  28997. }
  28998. function _createPlanes( lodMax ) {
  28999. const lodPlanes = [];
  29000. const sizeLods = [];
  29001. const sigmas = [];
  29002. const lodMeshes = [];
  29003. let lod = lodMax;
  29004. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  29005. for ( let i = 0; i < totalLods; i ++ ) {
  29006. const sizeLod = Math.pow( 2, lod );
  29007. sizeLods.push( sizeLod );
  29008. let sigma = 1.0 / sizeLod;
  29009. if ( i > lodMax - LOD_MIN ) {
  29010. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  29011. } else if ( i === 0 ) {
  29012. sigma = 0;
  29013. }
  29014. sigmas.push( sigma );
  29015. const texelSize = 1.0 / ( sizeLod - 2 );
  29016. const min = - texelSize;
  29017. const max = 1 + texelSize;
  29018. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  29019. const cubeFaces = 6;
  29020. const vertices = 6;
  29021. const positionSize = 3;
  29022. const uvSize = 2;
  29023. const faceIndexSize = 1;
  29024. const position = new Float32Array( positionSize * vertices * cubeFaces );
  29025. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  29026. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  29027. for ( let face = 0; face < cubeFaces; face ++ ) {
  29028. const x = ( face % 3 ) * 2 / 3 - 1;
  29029. const y = face > 2 ? 0 : - 1;
  29030. const coordinates = [
  29031. x, y, 0,
  29032. x + 2 / 3, y, 0,
  29033. x + 2 / 3, y + 1, 0,
  29034. x, y, 0,
  29035. x + 2 / 3, y + 1, 0,
  29036. x, y + 1, 0
  29037. ];
  29038. const faceIdx = _faceLib[ face ];
  29039. position.set( coordinates, positionSize * vertices * faceIdx );
  29040. uv.set( uv1, uvSize * vertices * faceIdx );
  29041. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  29042. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  29043. }
  29044. const planes = new BufferGeometry();
  29045. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  29046. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  29047. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  29048. lodPlanes.push( planes );
  29049. lodMeshes.push( new Mesh( planes, null ) );
  29050. if ( lod > LOD_MIN ) {
  29051. lod --;
  29052. }
  29053. }
  29054. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  29055. }
  29056. function _createRenderTarget( width, height, params ) {
  29057. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  29058. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  29059. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  29060. cubeUVRenderTarget.texture.isPMREMTexture = true;
  29061. cubeUVRenderTarget.scissorTest = true;
  29062. return cubeUVRenderTarget;
  29063. }
  29064. function _setViewport( target, x, y, width, height ) {
  29065. target.viewport.set( x, y, width, height );
  29066. target.scissor.set( x, y, width, height );
  29067. }
  29068. function _getMaterial( type ) {
  29069. const material = new NodeMaterial();
  29070. material.depthTest = false;
  29071. material.depthWrite = false;
  29072. material.blending = NoBlending;
  29073. material.name = `PMREM_${ type }`;
  29074. return material;
  29075. }
  29076. function _getBlurShader( lodMax, width, height ) {
  29077. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  29078. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  29079. const dTheta = uniform( 0 );
  29080. const n = float( MAX_SAMPLES );
  29081. const latitudinal = uniform( 0 ); // false, bool
  29082. const samples = uniform( 1 ); // int
  29083. const envMap = texture( null );
  29084. const mipInt = uniform( 0 ); // int
  29085. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  29086. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  29087. const CUBEUV_MAX_MIP = float( lodMax );
  29088. const materialUniforms = {
  29089. n,
  29090. latitudinal,
  29091. weights,
  29092. poleAxis,
  29093. outputDirection,
  29094. dTheta,
  29095. samples,
  29096. envMap,
  29097. mipInt,
  29098. CUBEUV_TEXEL_WIDTH,
  29099. CUBEUV_TEXEL_HEIGHT,
  29100. CUBEUV_MAX_MIP
  29101. };
  29102. const material = _getMaterial( 'blur' );
  29103. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  29104. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  29105. return material;
  29106. }
  29107. function _getCubemapMaterial( envTexture ) {
  29108. const material = _getMaterial( 'cubemap' );
  29109. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  29110. return material;
  29111. }
  29112. function _getEquirectMaterial( envTexture ) {
  29113. const material = _getMaterial( 'equirect' );
  29114. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  29115. return material;
  29116. }
  29117. const rendererCache = new WeakMap();
  29118. const typeFromArray = new Map( [
  29119. [ Int8Array, 'int' ],
  29120. [ Int16Array, 'int' ],
  29121. [ Int32Array, 'int' ],
  29122. [ Uint8Array, 'uint' ],
  29123. [ Uint16Array, 'uint' ],
  29124. [ Uint32Array, 'uint' ],
  29125. [ Float32Array, 'float' ]
  29126. ] );
  29127. const toFloat = ( value ) => {
  29128. if ( /e/g.test( value ) ) {
  29129. return String( value ).replace( /\+/g, '' );
  29130. } else {
  29131. value = Number( value );
  29132. return value + ( value % 1 ? '' : '.0' );
  29133. }
  29134. };
  29135. /**
  29136. * Base class for builders which generate a shader program based
  29137. * on a 3D object and its node material definition.
  29138. */
  29139. class NodeBuilder {
  29140. /**
  29141. * Constructs a new node builder.
  29142. *
  29143. * @param {Object3D} object - The 3D object.
  29144. * @param {Renderer} renderer - The current renderer.
  29145. * @param {NodeParser} parser - A reference to a node parser.
  29146. */
  29147. constructor( object, renderer, parser ) {
  29148. /**
  29149. * The 3D object.
  29150. *
  29151. * @type {Object3D}
  29152. */
  29153. this.object = object;
  29154. /**
  29155. * The material of the 3D object.
  29156. *
  29157. * @type {Material?}
  29158. */
  29159. this.material = ( object && object.material ) || null;
  29160. /**
  29161. * The geometry of the 3D object.
  29162. *
  29163. * @type {BufferGeometry?}
  29164. */
  29165. this.geometry = ( object && object.geometry ) || null;
  29166. /**
  29167. * The current renderer.
  29168. *
  29169. * @type {Renderer}
  29170. */
  29171. this.renderer = renderer;
  29172. /**
  29173. * A reference to a node parser.
  29174. *
  29175. * @type {NodeParser}
  29176. */
  29177. this.parser = parser;
  29178. /**
  29179. * The scene the 3D object belongs to.
  29180. *
  29181. * @type {Scene?}
  29182. * @default null
  29183. */
  29184. this.scene = null;
  29185. /**
  29186. * The camera the 3D object is rendered with.
  29187. *
  29188. * @type {Camera?}
  29189. * @default null
  29190. */
  29191. this.camera = null;
  29192. /**
  29193. * A list of all nodes the builder is processing
  29194. * for this 3D object.
  29195. *
  29196. * @type {Array<Node>}
  29197. */
  29198. this.nodes = [];
  29199. /**
  29200. * A list of all sequential nodes.
  29201. *
  29202. * @type {Array<Node>}
  29203. */
  29204. this.sequentialNodes = [];
  29205. /**
  29206. * A list of all nodes which {@link Node#update} method should be executed.
  29207. *
  29208. * @type {Array<Node>}
  29209. */
  29210. this.updateNodes = [];
  29211. /**
  29212. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  29213. *
  29214. * @type {Array<Node>}
  29215. */
  29216. this.updateBeforeNodes = [];
  29217. /**
  29218. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  29219. *
  29220. * @type {Array<Node>}
  29221. */
  29222. this.updateAfterNodes = [];
  29223. /**
  29224. * A dictionary that assigns each node to a unique hash.
  29225. *
  29226. * @type {Object<Number,Node>}
  29227. */
  29228. this.hashNodes = {};
  29229. /**
  29230. * A reference to a node material observer.
  29231. *
  29232. * @type {NodeMaterialObserver?}
  29233. * @default null
  29234. */
  29235. this.monitor = null;
  29236. /**
  29237. * A reference to the current lights node.
  29238. *
  29239. * @type {LightsNode?}
  29240. * @default null
  29241. */
  29242. this.lightsNode = null;
  29243. /**
  29244. * A reference to the current environment node.
  29245. *
  29246. * @type {Node?}
  29247. * @default null
  29248. */
  29249. this.environmentNode = null;
  29250. /**
  29251. * A reference to the current fog node.
  29252. *
  29253. * @type {FogNode?}
  29254. * @default null
  29255. */
  29256. this.fogNode = null;
  29257. /**
  29258. * The current clipping context.
  29259. *
  29260. * @type {ClippingContext?}
  29261. */
  29262. this.clippingContext = null;
  29263. /**
  29264. * The generated vertex shader.
  29265. *
  29266. * @type {String?}
  29267. */
  29268. this.vertexShader = null;
  29269. /**
  29270. * The generated fragment shader.
  29271. *
  29272. * @type {String?}
  29273. */
  29274. this.fragmentShader = null;
  29275. /**
  29276. * The generated compute shader.
  29277. *
  29278. * @type {String?}
  29279. */
  29280. this.computeShader = null;
  29281. /**
  29282. * Nodes used in the primary flow of code generation.
  29283. *
  29284. * @type {Object<String,Array<Node>>}
  29285. */
  29286. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  29287. /**
  29288. * Nodes code from `.flowNodes`.
  29289. *
  29290. * @type {Object<String,String>}
  29291. */
  29292. this.flowCode = { vertex: '', fragment: '', compute: '' };
  29293. /**
  29294. * This dictionary holds the node uniforms of the builder.
  29295. * The uniforms are maintained in an array for each shader stage.
  29296. *
  29297. * @type {Object}
  29298. */
  29299. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  29300. /**
  29301. * This dictionary holds the output structs of the builder.
  29302. * The structs are maintained in an array for each shader stage.
  29303. *
  29304. * @type {Object}
  29305. */
  29306. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  29307. /**
  29308. * This dictionary holds the bindings for each shader stage.
  29309. *
  29310. * @type {Object}
  29311. */
  29312. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  29313. /**
  29314. * This dictionary maintains the binding indices per bind group.
  29315. *
  29316. * @type {Object}
  29317. */
  29318. this.bindingsIndexes = {};
  29319. /**
  29320. * Reference to the array of bind groups.
  29321. *
  29322. * @type {Array<BindGroup>?}
  29323. */
  29324. this.bindGroups = null;
  29325. /**
  29326. * This array holds the node attributes of this builder
  29327. * created via {@link AttributeNode}.
  29328. *
  29329. * @type {Array<NodeAttribute>}
  29330. */
  29331. this.attributes = [];
  29332. /**
  29333. * This array holds the node attributes of this builder
  29334. * created via {@link BufferAttributeNode}.
  29335. *
  29336. * @type {Array<NodeAttribute>}
  29337. */
  29338. this.bufferAttributes = [];
  29339. /**
  29340. * This array holds the node varyings of this builder.
  29341. *
  29342. * @type {Array<NodeVarying>}
  29343. */
  29344. this.varyings = [];
  29345. /**
  29346. * This dictionary holds the (native) node codes of this builder.
  29347. * The codes are maintained in an array for each shader stage.
  29348. *
  29349. * @type {Object<String,Array<NodeCode>>}
  29350. */
  29351. this.codes = {};
  29352. /**
  29353. * This dictionary holds the node variables of this builder.
  29354. * The variables are maintained in an array for each shader stage.
  29355. *
  29356. * @type {Object<String,Array<NodeVar>>}
  29357. */
  29358. this.vars = {};
  29359. /**
  29360. * Current code flow.
  29361. * All code generated in this stack will be stored in `.flow`.
  29362. *
  29363. * @type {{code: String}}
  29364. */
  29365. this.flow = { code: '' };
  29366. /**
  29367. * A chain of nodes.
  29368. * Used to check recursive calls in node-graph.
  29369. *
  29370. * @type {Array<Node>}
  29371. */
  29372. this.chaining = [];
  29373. /**
  29374. * The current stack.
  29375. * This reflects the current process in the code block hierarchy,
  29376. * it is useful to know if the current process is inside a conditional for example.
  29377. *
  29378. * @type {StackNode}
  29379. */
  29380. this.stack = stack();
  29381. /**
  29382. * List of stack nodes.
  29383. * The current stack hierarchy is stored in an array.
  29384. *
  29385. * @type {Array<StackNode>}
  29386. */
  29387. this.stacks = [];
  29388. /**
  29389. * A tab value. Used for shader string generation.
  29390. *
  29391. * @type {String}
  29392. * @default '\t'
  29393. */
  29394. this.tab = '\t';
  29395. /**
  29396. * Reference to the current function node.
  29397. *
  29398. * @type {FunctionNode?}
  29399. * @default null
  29400. */
  29401. this.currentFunctionNode = null;
  29402. /**
  29403. * The builder's context.
  29404. *
  29405. * @type {Object}
  29406. */
  29407. this.context = {
  29408. material: this.material
  29409. };
  29410. /**
  29411. * The builder's cache.
  29412. *
  29413. * @type {NodeCache}
  29414. */
  29415. this.cache = new NodeCache();
  29416. /**
  29417. * Since the {@link NodeBuilder#cache} might be temporarily
  29418. * overwritten by other caches, this member retains the reference
  29419. * to the builder's own cache.
  29420. *
  29421. * @type {NodeCache}
  29422. * @default this.cache
  29423. */
  29424. this.globalCache = this.cache;
  29425. this.flowsData = new WeakMap();
  29426. /**
  29427. * The current shader stage.
  29428. *
  29429. * @type {('vertex'|'fragment'|'compute'|'any')?}
  29430. */
  29431. this.shaderStage = null;
  29432. /**
  29433. * The current build stage.
  29434. *
  29435. * @type {('setup'|'analyze'|'generate')?}
  29436. */
  29437. this.buildStage = null;
  29438. /**
  29439. * Whether comparison in shader code are generated with methods or not.
  29440. *
  29441. * @type {Boolean}
  29442. * @default false
  29443. */
  29444. this.useComparisonMethod = false;
  29445. }
  29446. /**
  29447. * Returns the bind groups of the current renderer.
  29448. *
  29449. * @return {ChainMap} The cache.
  29450. */
  29451. getBindGroupsCache() {
  29452. let bindGroupsCache = rendererCache.get( this.renderer );
  29453. if ( bindGroupsCache === undefined ) {
  29454. bindGroupsCache = new ChainMap();
  29455. rendererCache.set( this.renderer, bindGroupsCache );
  29456. }
  29457. return bindGroupsCache;
  29458. }
  29459. /**
  29460. * Factory method for creating an instance of {@link RenderTarget} with the given
  29461. * dimensions and options.
  29462. *
  29463. * @param {Number} width - The width of the render target.
  29464. * @param {Number} height - The height of the render target.
  29465. * @param {Object} options - The options of the render target.
  29466. * @return {RenderTarget} The render target.
  29467. */
  29468. createRenderTarget( width, height, options ) {
  29469. return new RenderTarget( width, height, options );
  29470. }
  29471. /**
  29472. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  29473. * dimensions and options.
  29474. *
  29475. * @param {Number} size - The size of the cube render target.
  29476. * @param {Object} options - The options of the cube render target.
  29477. * @return {CubeRenderTarget} The cube render target.
  29478. */
  29479. createCubeRenderTarget( size, options ) {
  29480. return new CubeRenderTarget( size, options );
  29481. }
  29482. /**
  29483. * Factory method for creating an instance of {@link PMREMGenerator}.
  29484. *
  29485. * @return {PMREMGenerator} The PMREM generator.
  29486. */
  29487. createPMREMGenerator() {
  29488. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  29489. return new PMREMGenerator( this.renderer );
  29490. }
  29491. /**
  29492. * Whether the given node is included in the internal array of nodes or not.
  29493. *
  29494. * @param {Node} node - The node to test.
  29495. * @return {Boolean} Whether the given node is included in the internal array of nodes or not.
  29496. */
  29497. includes( node ) {
  29498. return this.nodes.includes( node );
  29499. }
  29500. /**
  29501. * Returns a bind group for the given group name and binding.
  29502. *
  29503. * @private
  29504. * @param {String} groupName - The group name.
  29505. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  29506. * @return {BindGroup} The bind group
  29507. */
  29508. _getBindGroup( groupName, bindings ) {
  29509. const bindGroupsCache = this.getBindGroupsCache();
  29510. //
  29511. const bindingsArray = [];
  29512. let sharedGroup = true;
  29513. for ( const binding of bindings ) {
  29514. bindingsArray.push( binding );
  29515. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  29516. }
  29517. //
  29518. let bindGroup;
  29519. if ( sharedGroup ) {
  29520. bindGroup = bindGroupsCache.get( bindingsArray );
  29521. if ( bindGroup === undefined ) {
  29522. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  29523. bindGroupsCache.set( bindingsArray, bindGroup );
  29524. }
  29525. } else {
  29526. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  29527. }
  29528. return bindGroup;
  29529. }
  29530. /**
  29531. * Returns an array of node uniform groups for the given group name and shader stage.
  29532. *
  29533. * @param {String} groupName - The group name.
  29534. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  29535. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  29536. */
  29537. getBindGroupArray( groupName, shaderStage ) {
  29538. const bindings = this.bindings[ shaderStage ];
  29539. let bindGroup = bindings[ groupName ];
  29540. if ( bindGroup === undefined ) {
  29541. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  29542. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  29543. }
  29544. bindings[ groupName ] = bindGroup = [];
  29545. }
  29546. return bindGroup;
  29547. }
  29548. /**
  29549. * Returns a list bindings of all shader stages separated by groups.
  29550. *
  29551. * @return {Array<BindGroup>} The list of bindings.
  29552. */
  29553. getBindings() {
  29554. let bindingsGroups = this.bindGroups;
  29555. if ( bindingsGroups === null ) {
  29556. const groups = {};
  29557. const bindings = this.bindings;
  29558. for ( const shaderStage of shaderStages ) {
  29559. for ( const groupName in bindings[ shaderStage ] ) {
  29560. const uniforms = bindings[ shaderStage ][ groupName ];
  29561. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  29562. groupUniforms.push( ...uniforms );
  29563. }
  29564. }
  29565. bindingsGroups = [];
  29566. for ( const groupName in groups ) {
  29567. const group = groups[ groupName ];
  29568. const bindingsGroup = this._getBindGroup( groupName, group );
  29569. bindingsGroups.push( bindingsGroup );
  29570. }
  29571. this.bindGroups = bindingsGroups;
  29572. }
  29573. return bindingsGroups;
  29574. }
  29575. /**
  29576. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  29577. */
  29578. sortBindingGroups() {
  29579. const bindingsGroups = this.getBindings();
  29580. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  29581. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  29582. const bindingGroup = bindingsGroups[ i ];
  29583. this.bindingsIndexes[ bindingGroup.name ].group = i;
  29584. bindingGroup.index = i;
  29585. }
  29586. }
  29587. /**
  29588. * The builder maintains each node in a hash-based dictionary.
  29589. * This method sets the given node (value) with the given hash (key) into this dictionary.
  29590. *
  29591. * @param {Node} node - The node to add.
  29592. * @param {Number} hash - The hash of the node.
  29593. */
  29594. setHashNode( node, hash ) {
  29595. this.hashNodes[ hash ] = node;
  29596. }
  29597. /**
  29598. * Adds a node to this builder.
  29599. *
  29600. * @param {Node} node - The node to add.
  29601. */
  29602. addNode( node ) {
  29603. if ( this.nodes.includes( node ) === false ) {
  29604. this.nodes.push( node );
  29605. this.setHashNode( node, node.getHash( this ) );
  29606. }
  29607. }
  29608. /**
  29609. * It is used to add Nodes that will be used as FRAME and RENDER events,
  29610. * and need to follow a certain sequence in the calls to work correctly.
  29611. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  29612. *
  29613. * @param {Node} node - The node to add.
  29614. */
  29615. addSequentialNode( node ) {
  29616. if ( this.sequentialNodes.includes( node ) === false ) {
  29617. this.sequentialNodes.push( node );
  29618. }
  29619. }
  29620. /**
  29621. * Checks the update types of nodes
  29622. */
  29623. buildUpdateNodes() {
  29624. for ( const node of this.nodes ) {
  29625. const updateType = node.getUpdateType();
  29626. if ( updateType !== NodeUpdateType.NONE ) {
  29627. this.updateNodes.push( node.getSelf() );
  29628. }
  29629. }
  29630. for ( const node of this.sequentialNodes ) {
  29631. const updateBeforeType = node.getUpdateBeforeType();
  29632. const updateAfterType = node.getUpdateAfterType();
  29633. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  29634. this.updateBeforeNodes.push( node.getSelf() );
  29635. }
  29636. if ( updateAfterType !== NodeUpdateType.NONE ) {
  29637. this.updateAfterNodes.push( node.getSelf() );
  29638. }
  29639. }
  29640. }
  29641. /**
  29642. * A reference the current node which is the
  29643. * last node in the chain of nodes.
  29644. *
  29645. * @type {Node}
  29646. */
  29647. get currentNode() {
  29648. return this.chaining[ this.chaining.length - 1 ];
  29649. }
  29650. /**
  29651. * Whether the given texture is filtered or not.
  29652. *
  29653. * @param {Texture} texture - The texture to check.
  29654. * @return {Boolean} Whether the given texture is filtered or not.
  29655. */
  29656. isFilteredTexture( texture ) {
  29657. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  29658. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  29659. }
  29660. /**
  29661. * Adds the given node to the internal node chain.
  29662. * This is used to check recursive calls in node-graph.
  29663. *
  29664. * @param {Node} node - The node to add.
  29665. */
  29666. addChain( node ) {
  29667. /*
  29668. if ( this.chaining.indexOf( node ) !== - 1 ) {
  29669. console.warn( 'Recursive node: ', node );
  29670. }
  29671. */
  29672. this.chaining.push( node );
  29673. }
  29674. /**
  29675. * Removes the given node from the internal node chain.
  29676. *
  29677. * @param {Node} node - The node to remove.
  29678. */
  29679. removeChain( node ) {
  29680. const lastChain = this.chaining.pop();
  29681. if ( lastChain !== node ) {
  29682. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  29683. }
  29684. }
  29685. /**
  29686. * Returns the native shader method name for a given generic name. E.g.
  29687. * the method name `textureDimensions` matches the WGSL name but must be
  29688. * resolved to `textureSize` in GLSL.
  29689. *
  29690. * @abstract
  29691. * @param {String} method - The method name to resolve.
  29692. * @return {String} The resolved method name.
  29693. */
  29694. getMethod( method ) {
  29695. return method;
  29696. }
  29697. /**
  29698. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  29699. *
  29700. * @param {Number} hash - The hash of the node.
  29701. * @return {Node} The found node.
  29702. */
  29703. getNodeFromHash( hash ) {
  29704. return this.hashNodes[ hash ];
  29705. }
  29706. /**
  29707. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  29708. *
  29709. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  29710. * @param {Node} node - The node to add.
  29711. * @return {Node} The node.
  29712. */
  29713. addFlow( shaderStage, node ) {
  29714. this.flowNodes[ shaderStage ].push( node );
  29715. return node;
  29716. }
  29717. /**
  29718. * Sets builder's context.
  29719. *
  29720. * @param {Object} context - The context to set.
  29721. */
  29722. setContext( context ) {
  29723. this.context = context;
  29724. }
  29725. /**
  29726. * Returns the builder's current context.
  29727. *
  29728. * @return {Object} The builder's current context.
  29729. */
  29730. getContext() {
  29731. return this.context;
  29732. }
  29733. /**
  29734. * Gets a context used in shader construction that can be shared across different materials.
  29735. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  29736. *
  29737. * @return {Object} The builder's current context without material.
  29738. */
  29739. getSharedContext() {
  29740. ({ ...this.context });
  29741. return this.context;
  29742. }
  29743. /**
  29744. * Sets builder's cache.
  29745. *
  29746. * @param {NodeCache} cache - The cache to set.
  29747. */
  29748. setCache( cache ) {
  29749. this.cache = cache;
  29750. }
  29751. /**
  29752. * Returns the builder's current cache.
  29753. *
  29754. * @return {NodeCache} The builder's current cache.
  29755. */
  29756. getCache() {
  29757. return this.cache;
  29758. }
  29759. /**
  29760. * Returns a cache for the given node.
  29761. *
  29762. * @param {Node} node - The node.
  29763. * @param {Boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  29764. * @return {NodeCache} The cache.
  29765. */
  29766. getCacheFromNode( node, parent = true ) {
  29767. const data = this.getDataFromNode( node );
  29768. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  29769. return data.cache;
  29770. }
  29771. /**
  29772. * Whether the requested feature is available or not.
  29773. *
  29774. * @abstract
  29775. * @param {String} name - The requested feature.
  29776. * @return {Boolean} Whether the requested feature is supported or not.
  29777. */
  29778. isAvailable( /*name*/ ) {
  29779. return false;
  29780. }
  29781. /**
  29782. * Returns the vertexIndex input variable as a native shader string.
  29783. *
  29784. * @abstract
  29785. * @return {String} The instanceIndex shader string.
  29786. */
  29787. getVertexIndex() {
  29788. console.warn( 'Abstract function.' );
  29789. }
  29790. /**
  29791. * Returns the instanceIndex input variable as a native shader string.
  29792. *
  29793. * @abstract
  29794. * @return {String} The instanceIndex shader string.
  29795. */
  29796. getInstanceIndex() {
  29797. console.warn( 'Abstract function.' );
  29798. }
  29799. /**
  29800. * Returns the drawIndex input variable as a native shader string.
  29801. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  29802. *
  29803. * @abstract
  29804. * @return {String} The drawIndex shader string.
  29805. */
  29806. getDrawIndex() {
  29807. console.warn( 'Abstract function.' );
  29808. }
  29809. /**
  29810. * Returns the frontFacing input variable as a native shader string.
  29811. *
  29812. * @abstract
  29813. * @return {String} The frontFacing shader string.
  29814. */
  29815. getFrontFacing() {
  29816. console.warn( 'Abstract function.' );
  29817. }
  29818. /**
  29819. * Returns the fragCoord input variable as a native shader string.
  29820. *
  29821. * @abstract
  29822. * @return {String} The fragCoord shader string.
  29823. */
  29824. getFragCoord() {
  29825. console.warn( 'Abstract function.' );
  29826. }
  29827. /**
  29828. * Whether to flip texture data along its vertical axis or not. WebGL needs
  29829. * this method evaluate to `true`, WebGPU to `false`.
  29830. *
  29831. * @abstract
  29832. * @return {Boolean} Whether to flip texture data along its vertical axis or not.
  29833. */
  29834. isFlipY() {
  29835. return false;
  29836. }
  29837. /**
  29838. * Calling this method increases the usage count for the given node by one.
  29839. *
  29840. * @param {Node} node - The node to increase the usage count for.
  29841. * @return {Number} The updated usage count.
  29842. */
  29843. increaseUsage( node ) {
  29844. const nodeData = this.getDataFromNode( node );
  29845. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  29846. return nodeData.usageCount;
  29847. }
  29848. /**
  29849. * Generates a texture sample shader string for the given texture data.
  29850. *
  29851. * @abstract
  29852. * @param {Texture} texture - The texture.
  29853. * @param {String} textureProperty - The texture property name.
  29854. * @param {String} uvSnippet - Snippet defining the texture coordinates.
  29855. * @return {String} The generated shader string.
  29856. */
  29857. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  29858. console.warn( 'Abstract function.' );
  29859. }
  29860. /**
  29861. * Generates a texture LOD shader string for the given texture data.
  29862. *
  29863. * @abstract
  29864. * @param {Texture} texture - The texture.
  29865. * @param {String} textureProperty - The texture property name.
  29866. * @param {String} uvSnippet - Snippet defining the texture coordinates.
  29867. * @param {String} levelSnippet - Snippet defining the mip level.
  29868. * @return {String} The generated shader string.
  29869. */
  29870. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  29871. console.warn( 'Abstract function.' );
  29872. }
  29873. /**
  29874. * Generates the shader string for the given type and value.
  29875. *
  29876. * @param {String} type - The type.
  29877. * @param {Any?} [value=null] - The value.
  29878. * @return {String} The generated value as a shader string.
  29879. */
  29880. generateConst( type, value = null ) {
  29881. if ( value === null ) {
  29882. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  29883. else if ( type === 'bool' ) value = false;
  29884. else if ( type === 'color' ) value = new Color();
  29885. else if ( type === 'vec2' ) value = new Vector2();
  29886. else if ( type === 'vec3' ) value = new Vector3();
  29887. else if ( type === 'vec4' ) value = new Vector4();
  29888. }
  29889. if ( type === 'float' ) return toFloat( value );
  29890. if ( type === 'int' ) return `${ Math.round( value ) }`;
  29891. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  29892. if ( type === 'bool' ) return value ? 'true' : 'false';
  29893. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  29894. const typeLength = this.getTypeLength( type );
  29895. const componentType = this.getComponentType( type );
  29896. const generateConst = value => this.generateConst( componentType, value );
  29897. if ( typeLength === 2 ) {
  29898. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  29899. } else if ( typeLength === 3 ) {
  29900. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  29901. } else if ( typeLength === 4 ) {
  29902. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  29903. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  29904. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  29905. } else if ( typeLength > 4 ) {
  29906. return `${ this.getType( type ) }()`;
  29907. }
  29908. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  29909. }
  29910. /**
  29911. * It might be necessary to convert certain data types to different ones
  29912. * so this method can be used to hide the conversion.
  29913. *
  29914. * @param {String} type - The type.
  29915. * @return {String} The updated type.
  29916. */
  29917. getType( type ) {
  29918. if ( type === 'color' ) return 'vec3';
  29919. return type;
  29920. }
  29921. /**
  29922. * Whether the given attribute name is defined in the geometry or not.
  29923. *
  29924. * @param {String} name - The attribute name.
  29925. * @return {Boolean} Whether the given attribute name is defined in the geometry.
  29926. */
  29927. hasGeometryAttribute( name ) {
  29928. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  29929. }
  29930. /**
  29931. * Returns a node attribute for the given name and type.
  29932. *
  29933. * @param {String} name - The attribute's name.
  29934. * @param {String} type - The attribute's type.
  29935. * @return {NodeAttribute} The node attribute.
  29936. */
  29937. getAttribute( name, type ) {
  29938. const attributes = this.attributes;
  29939. // find attribute
  29940. for ( const attribute of attributes ) {
  29941. if ( attribute.name === name ) {
  29942. return attribute;
  29943. }
  29944. }
  29945. // create a new if no exist
  29946. const attribute = new NodeAttribute( name, type );
  29947. attributes.push( attribute );
  29948. return attribute;
  29949. }
  29950. /**
  29951. * Returns for the given node and shader stage the property name for the shader.
  29952. *
  29953. * @param {Node} node - The node.
  29954. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  29955. * @return {String} The property name.
  29956. */
  29957. getPropertyName( node/*, shaderStage*/ ) {
  29958. return node.name;
  29959. }
  29960. /**
  29961. * Whether the given type is a vector type or not.
  29962. *
  29963. * @param {String} type - The type to check.
  29964. * @return {Boolean} Whether the given type is a vector type or not.
  29965. */
  29966. isVector( type ) {
  29967. return /vec\d/.test( type );
  29968. }
  29969. /**
  29970. * Whether the given type is a matrix type or not.
  29971. *
  29972. * @param {String} type - The type to check.
  29973. * @return {Boolean} Whether the given type is a matrix type or not.
  29974. */
  29975. isMatrix( type ) {
  29976. return /mat\d/.test( type );
  29977. }
  29978. /**
  29979. * Whether the given type is a reference type or not.
  29980. *
  29981. * @param {String} type - The type to check.
  29982. * @return {Boolean} Whether the given type is a reference type or not.
  29983. */
  29984. isReference( type ) {
  29985. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  29986. }
  29987. /**
  29988. * Whether the given texture needs a conversion to working color space.
  29989. *
  29990. * @abstract
  29991. * @param {Texture} texture - The texture to check.
  29992. * @return {Boolean} Whether a color space conversion is required or not.
  29993. */
  29994. needsToWorkingColorSpace( /*texture*/ ) {
  29995. return false;
  29996. }
  29997. /**
  29998. * Returns the component type of a given texture.
  29999. *
  30000. * @param {Texture} texture - The texture.
  30001. * @return {String} The component type.
  30002. */
  30003. getComponentTypeFromTexture( texture ) {
  30004. const type = texture.type;
  30005. if ( texture.isDataTexture ) {
  30006. if ( type === IntType ) return 'int';
  30007. if ( type === UnsignedIntType ) return 'uint';
  30008. }
  30009. return 'float';
  30010. }
  30011. /**
  30012. * Returns the element type for a given type.
  30013. *
  30014. * @param {String} type - The type.
  30015. * @return {String} The element type.
  30016. */
  30017. getElementType( type ) {
  30018. if ( type === 'mat2' ) return 'vec2';
  30019. if ( type === 'mat3' ) return 'vec3';
  30020. if ( type === 'mat4' ) return 'vec4';
  30021. return this.getComponentType( type );
  30022. }
  30023. /**
  30024. * Returns the component type for a given type.
  30025. *
  30026. * @param {String} type - The type.
  30027. * @return {String} The component type.
  30028. */
  30029. getComponentType( type ) {
  30030. type = this.getVectorType( type );
  30031. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  30032. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  30033. if ( componentType === null ) return null;
  30034. if ( componentType[ 1 ] === 'b' ) return 'bool';
  30035. if ( componentType[ 1 ] === 'i' ) return 'int';
  30036. if ( componentType[ 1 ] === 'u' ) return 'uint';
  30037. return 'float';
  30038. }
  30039. /**
  30040. * Returns the vector type for a given type.
  30041. *
  30042. * @param {String} type - The type.
  30043. * @return {String} The vector type.
  30044. */
  30045. getVectorType( type ) {
  30046. if ( type === 'color' ) return 'vec3';
  30047. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  30048. return type;
  30049. }
  30050. /**
  30051. * Returns the data type for the given the length and component type.
  30052. *
  30053. * @param {Number} length - The length.
  30054. * @param {String} [componentType='float'] - The component type.
  30055. * @return {String} The type.
  30056. */
  30057. getTypeFromLength( length, componentType = 'float' ) {
  30058. if ( length === 1 ) return componentType;
  30059. const baseType = getTypeFromLength( length );
  30060. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  30061. return prefix + baseType;
  30062. }
  30063. /**
  30064. * Returns the type for a given typed array.
  30065. *
  30066. * @param {TypedArray} array - The typed array.
  30067. * @return {String} The type.
  30068. */
  30069. getTypeFromArray( array ) {
  30070. return typeFromArray.get( array.constructor );
  30071. }
  30072. /**
  30073. * Returns the type for a given buffer attribute.
  30074. *
  30075. * @param {BufferAttribute} attribute - The buffer attribute.
  30076. * @return {String} The type.
  30077. */
  30078. getTypeFromAttribute( attribute ) {
  30079. let dataAttribute = attribute;
  30080. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  30081. const array = dataAttribute.array;
  30082. const itemSize = attribute.itemSize;
  30083. const normalized = attribute.normalized;
  30084. let arrayType;
  30085. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  30086. arrayType = this.getTypeFromArray( array );
  30087. }
  30088. return this.getTypeFromLength( itemSize, arrayType );
  30089. }
  30090. /**
  30091. * Returns the length for the given data type.
  30092. *
  30093. * @param {String} type - The data type.
  30094. * @return {Number} The length.
  30095. */
  30096. getTypeLength( type ) {
  30097. const vecType = this.getVectorType( type );
  30098. const vecNum = /vec([2-4])/.exec( vecType );
  30099. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  30100. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  30101. if ( /mat2/.test( type ) === true ) return 4;
  30102. if ( /mat3/.test( type ) === true ) return 9;
  30103. if ( /mat4/.test( type ) === true ) return 16;
  30104. return 0;
  30105. }
  30106. /**
  30107. * Returns the vector type for a given matrix type.
  30108. *
  30109. * @param {String} type - The matrix type.
  30110. * @return {String} The vector type.
  30111. */
  30112. getVectorFromMatrix( type ) {
  30113. return type.replace( 'mat', 'vec' );
  30114. }
  30115. /**
  30116. * For a given type this method changes the component type to the
  30117. * given value. E.g. `vec4` should be changed to the new component type
  30118. * `uint` which results in `uvec4`.
  30119. *
  30120. * @param {String} type - The type.
  30121. * @param {String} newComponentType - The new component type.
  30122. * @return {String} The new type.
  30123. */
  30124. changeComponentType( type, newComponentType ) {
  30125. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  30126. }
  30127. /**
  30128. * Returns the integer type pendant for the given type.
  30129. *
  30130. * @param {String} type - The type.
  30131. * @return {String} The integer type.
  30132. */
  30133. getIntegerType( type ) {
  30134. const componentType = this.getComponentType( type );
  30135. if ( componentType === 'int' || componentType === 'uint' ) return type;
  30136. return this.changeComponentType( type, 'int' );
  30137. }
  30138. /**
  30139. * Adds a stack node to the internal stack.
  30140. *
  30141. * @return {StackNode} The added stack node.
  30142. */
  30143. addStack() {
  30144. this.stack = stack( this.stack );
  30145. this.stacks.push( getCurrentStack() || this.stack );
  30146. setCurrentStack( this.stack );
  30147. return this.stack;
  30148. }
  30149. /**
  30150. * Removes the last stack node from the internal stack.
  30151. *
  30152. * @return {StackNode} The removed stack node.
  30153. */
  30154. removeStack() {
  30155. const lastStack = this.stack;
  30156. this.stack = lastStack.parent;
  30157. setCurrentStack( this.stacks.pop() );
  30158. return lastStack;
  30159. }
  30160. /**
  30161. * The builder maintains (cached) data for each node during the building process. This method
  30162. * can be used to get these data for a specific shader stage and cache.
  30163. *
  30164. * @param {Node} node - The node to get the data for.
  30165. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30166. * @param {NodeCache?} cache - An optional cache.
  30167. * @return {Object} The node data.
  30168. */
  30169. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  30170. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  30171. let nodeData = cache.getData( node );
  30172. if ( nodeData === undefined ) {
  30173. nodeData = {};
  30174. cache.setData( node, nodeData );
  30175. }
  30176. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  30177. return nodeData[ shaderStage ];
  30178. }
  30179. /**
  30180. * Returns the properties for the given node and shader stage.
  30181. *
  30182. * @param {Node} node - The node to get the properties for.
  30183. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  30184. * @return {Object} The node properties.
  30185. */
  30186. getNodeProperties( node, shaderStage = 'any' ) {
  30187. const nodeData = this.getDataFromNode( node, shaderStage );
  30188. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  30189. }
  30190. /**
  30191. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  30192. *
  30193. * @param {BufferAttributeNode} node - The buffer attribute node.
  30194. * @param {String} type - The node type.
  30195. * @return {NodeAttribute} The node attribute.
  30196. */
  30197. getBufferAttributeFromNode( node, type ) {
  30198. const nodeData = this.getDataFromNode( node );
  30199. let bufferAttribute = nodeData.bufferAttribute;
  30200. if ( bufferAttribute === undefined ) {
  30201. const index = this.uniforms.index ++;
  30202. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  30203. this.bufferAttributes.push( bufferAttribute );
  30204. nodeData.bufferAttribute = bufferAttribute;
  30205. }
  30206. return bufferAttribute;
  30207. }
  30208. /**
  30209. * Returns an instance of {@link StructTypeNode} for the given output struct node.
  30210. *
  30211. * @param {OutputStructNode} node - The output struct node.
  30212. * @param {Array<String>} types - The output struct types.
  30213. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30214. * @return {StructTypeNode} The struct type attribute.
  30215. */
  30216. getStructTypeFromNode( node, types, shaderStage = this.shaderStage ) {
  30217. const nodeData = this.getDataFromNode( node, shaderStage );
  30218. let structType = nodeData.structType;
  30219. if ( structType === undefined ) {
  30220. const index = this.structs.index ++;
  30221. structType = new StructTypeNode( 'StructType' + index, types );
  30222. this.structs[ shaderStage ].push( structType );
  30223. nodeData.structType = structType;
  30224. }
  30225. return structType;
  30226. }
  30227. /**
  30228. * Returns an instance of {@link NodeUniform} for the given uniform node.
  30229. *
  30230. * @param {UniformNode} node - The uniform node.
  30231. * @param {String} type - The uniform type.
  30232. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30233. * @param {String?} name - The name of the uniform.
  30234. * @return {NodeUniform} The node uniform.
  30235. */
  30236. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  30237. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  30238. let nodeUniform = nodeData.uniform;
  30239. if ( nodeUniform === undefined ) {
  30240. const index = this.uniforms.index ++;
  30241. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  30242. this.uniforms[ shaderStage ].push( nodeUniform );
  30243. nodeData.uniform = nodeUniform;
  30244. }
  30245. return nodeUniform;
  30246. }
  30247. /**
  30248. * Returns an instance of {@link NodeVar} for the given variable node.
  30249. *
  30250. * @param {VarNode} node - The variable node.
  30251. * @param {String?} name - The variable's name.
  30252. * @param {String} [type=node.getNodeType( this )] - The variable's type.
  30253. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30254. * @return {NodeVar} The node variable.
  30255. */
  30256. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  30257. const nodeData = this.getDataFromNode( node, shaderStage );
  30258. let nodeVar = nodeData.variable;
  30259. if ( nodeVar === undefined ) {
  30260. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  30261. if ( name === null ) name = 'nodeVar' + vars.length;
  30262. nodeVar = new NodeVar( name, type );
  30263. vars.push( nodeVar );
  30264. nodeData.variable = nodeVar;
  30265. }
  30266. return nodeVar;
  30267. }
  30268. /**
  30269. * Returns an instance of {@link NodeVarying} for the given varying node.
  30270. *
  30271. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  30272. * @param {String?} name - The varying's name.
  30273. * @param {String} [type=node.getNodeType( this )] - The varying's type.
  30274. * @return {NodeVar} The node varying.
  30275. */
  30276. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  30277. const nodeData = this.getDataFromNode( node, 'any' );
  30278. let nodeVarying = nodeData.varying;
  30279. if ( nodeVarying === undefined ) {
  30280. const varyings = this.varyings;
  30281. const index = varyings.length;
  30282. if ( name === null ) name = 'nodeVarying' + index;
  30283. nodeVarying = new NodeVarying( name, type );
  30284. varyings.push( nodeVarying );
  30285. nodeData.varying = nodeVarying;
  30286. }
  30287. return nodeVarying;
  30288. }
  30289. /**
  30290. * Returns an instance of {@link NodeCode} for the given code node.
  30291. *
  30292. * @param {CodeNode} node - The code node.
  30293. * @param {String} type - The node type.
  30294. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30295. * @return {NodeCode} The node code.
  30296. */
  30297. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  30298. const nodeData = this.getDataFromNode( node );
  30299. let nodeCode = nodeData.code;
  30300. if ( nodeCode === undefined ) {
  30301. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  30302. const index = codes.length;
  30303. nodeCode = new NodeCode( 'nodeCode' + index, type );
  30304. codes.push( nodeCode );
  30305. nodeData.code = nodeCode;
  30306. }
  30307. return nodeCode;
  30308. }
  30309. /**
  30310. * Adds a code flow based on the code-block hierarchy.
  30311. * This is used so that code-blocks like If,Else create their variables locally if the Node
  30312. * is only used inside one of these conditionals in the current shader stage.
  30313. *
  30314. * @param {Node} node - The node to add.
  30315. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  30316. */
  30317. addFlowCodeHierarchy( node, nodeBlock ) {
  30318. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  30319. let needsFlowCode = true;
  30320. let nodeBlockHierarchy = nodeBlock;
  30321. while ( nodeBlockHierarchy ) {
  30322. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  30323. needsFlowCode = false;
  30324. break;
  30325. }
  30326. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  30327. }
  30328. if ( needsFlowCode ) {
  30329. for ( const flowCode of flowCodes ) {
  30330. this.addLineFlowCode( flowCode );
  30331. }
  30332. }
  30333. }
  30334. /**
  30335. * Add a inline-code to the current flow code-block.
  30336. *
  30337. * @param {Node} node - The node to add.
  30338. * @param {String} code - The code to add.
  30339. * @param {Node} nodeBlock - Current ConditionalNode
  30340. */
  30341. addLineFlowCodeBlock( node, code, nodeBlock ) {
  30342. const nodeData = this.getDataFromNode( node );
  30343. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  30344. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  30345. flowCodes.push( code );
  30346. codeBlock.set( nodeBlock, true );
  30347. }
  30348. /**
  30349. * Add a inline-code to the current flow.
  30350. *
  30351. * @param {String} code - The code to add.
  30352. * @param {Node?} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  30353. * @return {NodeBuilder} A reference to this node builder.
  30354. */
  30355. addLineFlowCode( code, node = null ) {
  30356. if ( code === '' ) return this;
  30357. if ( node !== null && this.context.nodeBlock ) {
  30358. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  30359. }
  30360. code = this.tab + code;
  30361. if ( ! /;\s*$/.test( code ) ) {
  30362. code = code + ';\n';
  30363. }
  30364. this.flow.code += code;
  30365. return this;
  30366. }
  30367. /**
  30368. * Adds a code to the current code flow.
  30369. *
  30370. * @param {String} code - Shader code.
  30371. * @return {NodeBuilder} A reference to this node builder.
  30372. */
  30373. addFlowCode( code ) {
  30374. this.flow.code += code;
  30375. return this;
  30376. }
  30377. /**
  30378. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  30379. * Typically used in codes with If,Else.
  30380. *
  30381. * @return {NodeBuilder} A reference to this node builder.
  30382. */
  30383. addFlowTab() {
  30384. this.tab += '\t';
  30385. return this;
  30386. }
  30387. /**
  30388. * Removes a tab.
  30389. *
  30390. * @return {NodeBuilder} A reference to this node builder.
  30391. */
  30392. removeFlowTab() {
  30393. this.tab = this.tab.slice( 0, - 1 );
  30394. return this;
  30395. }
  30396. /**
  30397. * Gets the current flow data based on a Node.
  30398. *
  30399. * @param {Node} node - Node that the flow was started.
  30400. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30401. * @return {Object} The flow data.
  30402. */
  30403. getFlowData( node/*, shaderStage*/ ) {
  30404. return this.flowsData.get( node );
  30405. }
  30406. /**
  30407. * Executes the node flow based on a root node to generate the final shader code.
  30408. *
  30409. * @param {Node} node - The node to execute.
  30410. * @return {Object} The code flow.
  30411. */
  30412. flowNode( node ) {
  30413. const output = node.getNodeType( this );
  30414. const flowData = this.flowChildNode( node, output );
  30415. this.flowsData.set( node, flowData );
  30416. return flowData;
  30417. }
  30418. /**
  30419. * Returns the native shader operator name for a given generic name.
  30420. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  30421. *
  30422. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  30423. * @return {FunctionNode} The build function node.
  30424. */
  30425. buildFunctionNode( shaderNode ) {
  30426. const fn = new FunctionNode();
  30427. const previous = this.currentFunctionNode;
  30428. this.currentFunctionNode = fn;
  30429. fn.code = this.buildFunctionCode( shaderNode );
  30430. this.currentFunctionNode = previous;
  30431. return fn;
  30432. }
  30433. /**
  30434. * Generates a code flow based on a TSL function: Fn().
  30435. *
  30436. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  30437. * @return {Object}
  30438. */
  30439. flowShaderNode( shaderNode ) {
  30440. const layout = shaderNode.layout;
  30441. const inputs = {
  30442. [ Symbol.iterator ]() {
  30443. let index = 0;
  30444. const values = Object.values( this );
  30445. return {
  30446. next: () => ( {
  30447. value: values[ index ],
  30448. done: index ++ >= values.length
  30449. } )
  30450. };
  30451. }
  30452. };
  30453. for ( const input of layout.inputs ) {
  30454. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  30455. }
  30456. //
  30457. shaderNode.layout = null;
  30458. const callNode = shaderNode.call( inputs );
  30459. const flowData = this.flowStagesNode( callNode, layout.type );
  30460. shaderNode.layout = layout;
  30461. return flowData;
  30462. }
  30463. /**
  30464. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  30465. *
  30466. * @param {Node} node - The node to execute.
  30467. * @param {String?} output - Expected output type. For example 'vec3'.
  30468. * @return {Object}
  30469. */
  30470. flowStagesNode( node, output = null ) {
  30471. const previousFlow = this.flow;
  30472. const previousVars = this.vars;
  30473. const previousCache = this.cache;
  30474. const previousBuildStage = this.buildStage;
  30475. const previousStack = this.stack;
  30476. const flow = {
  30477. code: ''
  30478. };
  30479. this.flow = flow;
  30480. this.vars = {};
  30481. this.cache = new NodeCache();
  30482. this.stack = stack();
  30483. for ( const buildStage of defaultBuildStages ) {
  30484. this.setBuildStage( buildStage );
  30485. flow.result = node.build( this, output );
  30486. }
  30487. flow.vars = this.getVars( this.shaderStage );
  30488. this.flow = previousFlow;
  30489. this.vars = previousVars;
  30490. this.cache = previousCache;
  30491. this.stack = previousStack;
  30492. this.setBuildStage( previousBuildStage );
  30493. return flow;
  30494. }
  30495. /**
  30496. * Returns the native shader operator name for a given generic name.
  30497. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  30498. *
  30499. * @abstract
  30500. * @param {String} op - The operator name to resolve.
  30501. * @return {String} The resolved operator name.
  30502. */
  30503. getFunctionOperator( /* op */ ) {
  30504. return null;
  30505. }
  30506. /**
  30507. * Generates a code flow based on a child Node.
  30508. *
  30509. * @param {Node} node - The node to execute.
  30510. * @param {String?} output - Expected output type. For example 'vec3'.
  30511. * @return {Object} The code flow.
  30512. */
  30513. flowChildNode( node, output = null ) {
  30514. const previousFlow = this.flow;
  30515. const flow = {
  30516. code: ''
  30517. };
  30518. this.flow = flow;
  30519. flow.result = node.build( this, output );
  30520. this.flow = previousFlow;
  30521. return flow;
  30522. }
  30523. /**
  30524. * Executes a flow of code in a different stage.
  30525. *
  30526. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  30527. * return the value in fragment-stage even if it is being executed in an input fragment.
  30528. *
  30529. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30530. * @param {Node} node - The node to execute.
  30531. * @param {String?} output - Expected output type. For example 'vec3'.
  30532. * @param {String?} propertyName - The property name to assign the result.
  30533. * @return {Object}
  30534. */
  30535. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  30536. const previousShaderStage = this.shaderStage;
  30537. this.setShaderStage( shaderStage );
  30538. const flowData = this.flowChildNode( node, output );
  30539. if ( propertyName !== null ) {
  30540. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  30541. }
  30542. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  30543. this.setShaderStage( previousShaderStage );
  30544. return flowData;
  30545. }
  30546. /**
  30547. * Returns an array holding all node attributes of this node builder.
  30548. *
  30549. * @return {Array<NodeAttribute>} The node attributes of this builder.
  30550. */
  30551. getAttributesArray() {
  30552. return this.attributes.concat( this.bufferAttributes );
  30553. }
  30554. /**
  30555. * Returns the attribute definitions as a shader string for the given shader stage.
  30556. *
  30557. * @abstract
  30558. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30559. * @return {String} The attribute code section.
  30560. */
  30561. getAttributes( /*shaderStage*/ ) {
  30562. console.warn( 'Abstract function.' );
  30563. }
  30564. /**
  30565. * Returns the varying definitions as a shader string for the given shader stage.
  30566. *
  30567. * @abstract
  30568. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30569. * @return {String} The varying code section.
  30570. */
  30571. getVaryings( /*shaderStage*/ ) {
  30572. console.warn( 'Abstract function.' );
  30573. }
  30574. /**
  30575. * Returns a single variable definition as a shader string for the given variable type and name.
  30576. *
  30577. * @param {String} type - The variable's type.
  30578. * @param {String} name - The variable's name.
  30579. * @return {String} The shader string.
  30580. */
  30581. getVar( type, name ) {
  30582. return `${ this.getType( type ) } ${ name }`;
  30583. }
  30584. /**
  30585. * Returns the variable definitions as a shader string for the given shader stage.
  30586. *
  30587. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30588. * @return {String} The variable code section.
  30589. */
  30590. getVars( shaderStage ) {
  30591. let snippet = '';
  30592. const vars = this.vars[ shaderStage ];
  30593. if ( vars !== undefined ) {
  30594. for ( const variable of vars ) {
  30595. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  30596. }
  30597. }
  30598. return snippet;
  30599. }
  30600. /**
  30601. * Returns the uniform definitions as a shader string for the given shader stage.
  30602. *
  30603. * @abstract
  30604. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30605. * @return {String} The uniform code section.
  30606. */
  30607. getUniforms( /*shaderStage*/ ) {
  30608. console.warn( 'Abstract function.' );
  30609. }
  30610. /**
  30611. * Returns the native code definitions as a shader string for the given shader stage.
  30612. *
  30613. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30614. * @return {String} The native code section.
  30615. */
  30616. getCodes( shaderStage ) {
  30617. const codes = this.codes[ shaderStage ];
  30618. let code = '';
  30619. if ( codes !== undefined ) {
  30620. for ( const nodeCode of codes ) {
  30621. code += nodeCode.code + '\n';
  30622. }
  30623. }
  30624. return code;
  30625. }
  30626. /**
  30627. * Returns the hash of this node builder.
  30628. *
  30629. * @return {String} The hash.
  30630. */
  30631. getHash() {
  30632. return this.vertexShader + this.fragmentShader + this.computeShader;
  30633. }
  30634. /**
  30635. * Sets the current shader stage.
  30636. *
  30637. * @param {('vertex'|'fragment'|'compute'|'any')?} shaderStage - The shader stage to set.
  30638. */
  30639. setShaderStage( shaderStage ) {
  30640. this.shaderStage = shaderStage;
  30641. }
  30642. /**
  30643. * Returns the current shader stage.
  30644. *
  30645. * @return {('vertex'|'fragment'|'compute'|'any')?} The current shader stage.
  30646. */
  30647. getShaderStage() {
  30648. return this.shaderStage;
  30649. }
  30650. /**
  30651. * Sets the current build stage.
  30652. *
  30653. * @param {('setup'|'analyze'|'generate')?} buildStage - The build stage to set.
  30654. */
  30655. setBuildStage( buildStage ) {
  30656. this.buildStage = buildStage;
  30657. }
  30658. /**
  30659. * Returns the current build stage.
  30660. *
  30661. * @return {('setup'|'analyze'|'generate')?} The current build stage.
  30662. */
  30663. getBuildStage() {
  30664. return this.buildStage;
  30665. }
  30666. /**
  30667. * Controls the code build of the shader stages.
  30668. *
  30669. * @abstract
  30670. */
  30671. buildCode() {
  30672. console.warn( 'Abstract function.' );
  30673. }
  30674. /**
  30675. * Central build method which controls the build for the given object.
  30676. *
  30677. * @return {NodeBuilder} A reference to this node builder.
  30678. */
  30679. build() {
  30680. const { object, material, renderer } = this;
  30681. if ( material !== null ) {
  30682. let nodeMaterial = renderer.library.fromMaterial( material );
  30683. if ( nodeMaterial === null ) {
  30684. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  30685. nodeMaterial = new NodeMaterial();
  30686. }
  30687. nodeMaterial.build( this );
  30688. } else {
  30689. this.addFlow( 'compute', object );
  30690. }
  30691. // setup() -> stage 1: create possible new nodes and returns an output reference node
  30692. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  30693. // generate() -> stage 3: generate shader
  30694. for ( const buildStage of defaultBuildStages ) {
  30695. this.setBuildStage( buildStage );
  30696. if ( this.context.vertex && this.context.vertex.isNode ) {
  30697. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  30698. }
  30699. for ( const shaderStage of shaderStages ) {
  30700. this.setShaderStage( shaderStage );
  30701. const flowNodes = this.flowNodes[ shaderStage ];
  30702. for ( const node of flowNodes ) {
  30703. if ( buildStage === 'generate' ) {
  30704. this.flowNode( node );
  30705. } else {
  30706. node.build( this );
  30707. }
  30708. }
  30709. }
  30710. }
  30711. this.setBuildStage( null );
  30712. this.setShaderStage( null );
  30713. // stage 4: build code for a specific output
  30714. this.buildCode();
  30715. this.buildUpdateNodes();
  30716. return this;
  30717. }
  30718. /**
  30719. * Returns a uniform representation which is later used for UBO generation and rendering.
  30720. *
  30721. * @param {NodeUniform} uniformNode - The uniform node.
  30722. * @param {String} type - The requested type.
  30723. * @return {Uniform} The uniform.
  30724. */
  30725. getNodeUniform( uniformNode, type ) {
  30726. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  30727. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  30728. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  30729. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  30730. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  30731. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  30732. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  30733. throw new Error( `Uniform "${type}" not declared.` );
  30734. }
  30735. /**
  30736. * Formats the given shader snippet from a given type into another one. E.g.
  30737. * this method might be used to convert a simple float string `"1.0"` into a
  30738. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  30739. *
  30740. * @param {String} snippet - The shader snippet.
  30741. * @param {String} fromType - The source type.
  30742. * @param {String} toType - The target type.
  30743. * @return {String} The updated shader string.
  30744. */
  30745. format( snippet, fromType, toType ) {
  30746. fromType = this.getVectorType( fromType );
  30747. toType = this.getVectorType( toType );
  30748. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  30749. return snippet;
  30750. }
  30751. const fromTypeLength = this.getTypeLength( fromType );
  30752. const toTypeLength = this.getTypeLength( toType );
  30753. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  30754. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  30755. }
  30756. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  30757. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  30758. }
  30759. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  30760. // @TODO: ignore for now
  30761. return snippet;
  30762. }
  30763. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  30764. // @TODO: ignore for now
  30765. return snippet;
  30766. }
  30767. if ( fromTypeLength === toTypeLength ) {
  30768. return `${ this.getType( toType ) }( ${ snippet } )`;
  30769. }
  30770. if ( fromTypeLength > toTypeLength ) {
  30771. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  30772. }
  30773. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  30774. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  30775. }
  30776. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  30777. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  30778. }
  30779. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  30780. // convert a number value to vector type, e.g:
  30781. // vec3( 1u ) -> vec3( float( 1u ) )
  30782. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  30783. }
  30784. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  30785. }
  30786. /**
  30787. * Returns a signature with the engine's current revision.
  30788. *
  30789. * @return {String} The signature.
  30790. */
  30791. getSignature() {
  30792. return `// Three.js r${ REVISION } - Node System\n`;
  30793. }
  30794. // deprecated
  30795. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  30796. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  30797. }
  30798. }
  30799. /**
  30800. * Management class for updating nodes. The module tracks metrics like
  30801. * the elapsed time, delta time, the render and frame ID to correctly
  30802. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  30803. * and {@link Node#updateAfter} depending on the node's configuration.
  30804. */
  30805. class NodeFrame {
  30806. /**
  30807. * Constructs a new node fame.
  30808. */
  30809. constructor() {
  30810. /**
  30811. * The elapsed time in seconds.
  30812. *
  30813. * @type {Number}
  30814. * @default 0
  30815. */
  30816. this.time = 0;
  30817. /**
  30818. * The delta time in seconds.
  30819. *
  30820. * @type {Number}
  30821. * @default 0
  30822. */
  30823. this.deltaTime = 0;
  30824. /**
  30825. * The frame ID.
  30826. *
  30827. * @type {Number}
  30828. * @default 0
  30829. */
  30830. this.frameId = 0;
  30831. /**
  30832. * The render ID.
  30833. *
  30834. * @type {Number}
  30835. * @default 0
  30836. */
  30837. this.renderId = 0;
  30838. /**
  30839. * Used to control the {@link Node#update} call.
  30840. *
  30841. * @type {WeakMap<Node, Object>}
  30842. */
  30843. this.updateMap = new WeakMap();
  30844. /**
  30845. * Used to control the {@link Node#updateBefore} call.
  30846. *
  30847. * @type {WeakMap<Node, Object>}
  30848. */
  30849. this.updateBeforeMap = new WeakMap();
  30850. /**
  30851. * Used to control the {@link Node#updateAfter} call.
  30852. *
  30853. * @type {WeakMap<Node, Object>}
  30854. */
  30855. this.updateAfterMap = new WeakMap();
  30856. /**
  30857. * A reference to the current renderer.
  30858. *
  30859. * @type {Renderer?}
  30860. * @default null
  30861. */
  30862. this.renderer = null;
  30863. /**
  30864. * A reference to the current material.
  30865. *
  30866. * @type {Material?}
  30867. * @default null
  30868. */
  30869. this.material = null;
  30870. /**
  30871. * A reference to the current camera.
  30872. *
  30873. * @type {Camera?}
  30874. * @default null
  30875. */
  30876. this.camera = null;
  30877. /**
  30878. * A reference to the current 3D object.
  30879. *
  30880. * @type {Object3D?}
  30881. * @default null
  30882. */
  30883. this.object = null;
  30884. /**
  30885. * A reference to the current scene.
  30886. *
  30887. * @type {Scene?}
  30888. * @default null
  30889. */
  30890. this.scene = null;
  30891. }
  30892. /**
  30893. * Returns a dictionary for a given node and update map which
  30894. * is used to correctly call node update methods per frame or render.
  30895. *
  30896. * @private
  30897. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  30898. * @param {Node} nodeRef - The reference to the current node.
  30899. * @return {Object<String,WeakMap>} The dictionary.
  30900. */
  30901. _getMaps( referenceMap, nodeRef ) {
  30902. let maps = referenceMap.get( nodeRef );
  30903. if ( maps === undefined ) {
  30904. maps = {
  30905. renderMap: new WeakMap(),
  30906. frameMap: new WeakMap()
  30907. };
  30908. referenceMap.set( nodeRef, maps );
  30909. }
  30910. return maps;
  30911. }
  30912. /**
  30913. * This method executes the {@link Node#updateBefore} for the given node.
  30914. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  30915. * is only executed once per frame, render or object depending on the update
  30916. * type.
  30917. *
  30918. * @param {Node} node - The node that should be updated.
  30919. */
  30920. updateBeforeNode( node ) {
  30921. const updateType = node.getUpdateBeforeType();
  30922. const reference = node.updateReference( this );
  30923. if ( updateType === NodeUpdateType.FRAME ) {
  30924. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  30925. if ( frameMap.get( reference ) !== this.frameId ) {
  30926. if ( node.updateBefore( this ) !== false ) {
  30927. frameMap.set( reference, this.frameId );
  30928. }
  30929. }
  30930. } else if ( updateType === NodeUpdateType.RENDER ) {
  30931. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  30932. if ( renderMap.get( reference ) !== this.renderId ) {
  30933. if ( node.updateBefore( this ) !== false ) {
  30934. renderMap.set( reference, this.renderId );
  30935. }
  30936. }
  30937. } else if ( updateType === NodeUpdateType.OBJECT ) {
  30938. node.updateBefore( this );
  30939. }
  30940. }
  30941. /**
  30942. * This method executes the {@link Node#updateAfter} for the given node.
  30943. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  30944. * is only executed once per frame, render or object depending on the update
  30945. * type.
  30946. *
  30947. * @param {Node} node - The node that should be updated.
  30948. */
  30949. updateAfterNode( node ) {
  30950. const updateType = node.getUpdateAfterType();
  30951. const reference = node.updateReference( this );
  30952. if ( updateType === NodeUpdateType.FRAME ) {
  30953. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  30954. if ( frameMap.get( reference ) !== this.frameId ) {
  30955. if ( node.updateAfter( this ) !== false ) {
  30956. frameMap.set( reference, this.frameId );
  30957. }
  30958. }
  30959. } else if ( updateType === NodeUpdateType.RENDER ) {
  30960. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  30961. if ( renderMap.get( reference ) !== this.renderId ) {
  30962. if ( node.updateAfter( this ) !== false ) {
  30963. renderMap.set( reference, this.renderId );
  30964. }
  30965. }
  30966. } else if ( updateType === NodeUpdateType.OBJECT ) {
  30967. node.updateAfter( this );
  30968. }
  30969. }
  30970. /**
  30971. * This method executes the {@link Node#update} for the given node.
  30972. * It makes sure {@link Node#updateType} is honored meaning the update
  30973. * is only executed once per frame, render or object depending on the update
  30974. * type.
  30975. *
  30976. * @param {Node} node - The node that should be updated.
  30977. */
  30978. updateNode( node ) {
  30979. const updateType = node.getUpdateType();
  30980. const reference = node.updateReference( this );
  30981. if ( updateType === NodeUpdateType.FRAME ) {
  30982. const { frameMap } = this._getMaps( this.updateMap, reference );
  30983. if ( frameMap.get( reference ) !== this.frameId ) {
  30984. if ( node.update( this ) !== false ) {
  30985. frameMap.set( reference, this.frameId );
  30986. }
  30987. }
  30988. } else if ( updateType === NodeUpdateType.RENDER ) {
  30989. const { renderMap } = this._getMaps( this.updateMap, reference );
  30990. if ( renderMap.get( reference ) !== this.renderId ) {
  30991. if ( node.update( this ) !== false ) {
  30992. renderMap.set( reference, this.renderId );
  30993. }
  30994. }
  30995. } else if ( updateType === NodeUpdateType.OBJECT ) {
  30996. node.update( this );
  30997. }
  30998. }
  30999. /**
  31000. * Updates the internal state of the node frame. This method is
  31001. * called by the renderer in its internal animation loop.
  31002. */
  31003. update() {
  31004. this.frameId ++;
  31005. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  31006. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  31007. this.lastTime = performance.now();
  31008. this.time += this.deltaTime;
  31009. }
  31010. }
  31011. /**
  31012. * Describes the input of a {@link NodeFunction}.
  31013. */
  31014. class NodeFunctionInput {
  31015. /**
  31016. * Constructs a new node function input.
  31017. *
  31018. * @param {String} type - The input type.
  31019. * @param {String} name - The input name.
  31020. * @param {Number?} [count=null] - If the input is an Array, count will be the length.
  31021. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  31022. * @param {Boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  31023. */
  31024. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  31025. /**
  31026. * The input type.
  31027. *
  31028. * @type {String}
  31029. */
  31030. this.type = type;
  31031. /**
  31032. * The input name.
  31033. *
  31034. * @type {String}
  31035. */
  31036. this.name = name;
  31037. /**
  31038. * If the input is an Array, count will be the length.
  31039. *
  31040. * @type {Number?}
  31041. * @default null
  31042. */
  31043. this.count = count;
  31044. /**
  31045. *The parameter qualifier (only relevant for GLSL).
  31046. *
  31047. * @type {('in'|'out'|'inout')}
  31048. * @default ''
  31049. */
  31050. this.qualifier = qualifier;
  31051. /**
  31052. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  31053. *
  31054. * @type {Boolean}
  31055. * @default false
  31056. */
  31057. this.isConst = isConst;
  31058. }
  31059. }
  31060. NodeFunctionInput.isNodeFunctionInput = true;
  31061. /**
  31062. * Module for representing directional lights as nodes.
  31063. *
  31064. * @augments AnalyticLightNode
  31065. */
  31066. class DirectionalLightNode extends AnalyticLightNode {
  31067. static get type() {
  31068. return 'DirectionalLightNode';
  31069. }
  31070. /**
  31071. * Constructs a new directional light node.
  31072. *
  31073. * @param {DirectionalLight?} [light=null] - The directional light source.
  31074. */
  31075. constructor( light = null ) {
  31076. super( light );
  31077. }
  31078. setup( builder ) {
  31079. super.setup( builder );
  31080. const lightingModel = builder.context.lightingModel;
  31081. const lightColor = this.colorNode;
  31082. const lightDirection = lightTargetDirection( this.light );
  31083. const reflectedLight = builder.context.reflectedLight;
  31084. lightingModel.direct( {
  31085. lightDirection,
  31086. lightColor,
  31087. reflectedLight
  31088. }, builder.stack, builder );
  31089. }
  31090. }
  31091. const _matrix41 = /*@__PURE__*/ new Matrix4();
  31092. const _matrix42 = /*@__PURE__*/ new Matrix4();
  31093. let _ltcLib = null;
  31094. /**
  31095. * Module for representing rect area lights as nodes.
  31096. *
  31097. * @augments AnalyticLightNode
  31098. */
  31099. class RectAreaLightNode extends AnalyticLightNode {
  31100. static get type() {
  31101. return 'RectAreaLightNode';
  31102. }
  31103. /**
  31104. * Constructs a new rect area light node.
  31105. *
  31106. * @param {RectAreaLight?} [light=null] - The rect area light source.
  31107. */
  31108. constructor( light = null ) {
  31109. super( light );
  31110. /**
  31111. * Uniform node representing the half height of the are light.
  31112. *
  31113. * @type {UniformNode<vec3>}
  31114. */
  31115. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  31116. /**
  31117. * Uniform node representing the half width of the are light.
  31118. *
  31119. * @type {UniformNode<vec3>}
  31120. */
  31121. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  31122. /**
  31123. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  31124. * relies on `viewMatrix` which might vary per render call.
  31125. *
  31126. * @type {String}
  31127. * @default 'render'
  31128. */
  31129. this.updateType = NodeUpdateType.RENDER;
  31130. }
  31131. /**
  31132. * Overwritten to updated rect area light specific uniforms.
  31133. *
  31134. * @param {NodeFrame} frame - A reference to the current node frame.
  31135. */
  31136. update( frame ) {
  31137. super.update( frame );
  31138. const { light } = this;
  31139. const viewMatrix = frame.camera.matrixWorldInverse;
  31140. _matrix42.identity();
  31141. _matrix41.copy( light.matrixWorld );
  31142. _matrix41.premultiply( viewMatrix );
  31143. _matrix42.extractRotation( _matrix41 );
  31144. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  31145. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  31146. this.halfWidth.value.applyMatrix4( _matrix42 );
  31147. this.halfHeight.value.applyMatrix4( _matrix42 );
  31148. }
  31149. setup( builder ) {
  31150. super.setup( builder );
  31151. let ltc_1, ltc_2;
  31152. if ( builder.isAvailable( 'float32Filterable' ) ) {
  31153. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  31154. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  31155. } else {
  31156. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  31157. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  31158. }
  31159. const { colorNode, light } = this;
  31160. const lightingModel = builder.context.lightingModel;
  31161. const lightPosition = lightViewPosition( light );
  31162. const reflectedLight = builder.context.reflectedLight;
  31163. lightingModel.directRectArea( {
  31164. lightColor: colorNode,
  31165. lightPosition,
  31166. halfWidth: this.halfWidth,
  31167. halfHeight: this.halfHeight,
  31168. reflectedLight,
  31169. ltc_1,
  31170. ltc_2
  31171. }, builder.stack, builder );
  31172. }
  31173. /**
  31174. * Used to configure the internal BRDF approximation texture data.
  31175. *
  31176. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  31177. */
  31178. static setLTC( ltc ) {
  31179. _ltcLib = ltc;
  31180. }
  31181. }
  31182. /**
  31183. * Module for representing spot lights as nodes.
  31184. *
  31185. * @augments AnalyticLightNode
  31186. */
  31187. class SpotLightNode extends AnalyticLightNode {
  31188. static get type() {
  31189. return 'SpotLightNode';
  31190. }
  31191. /**
  31192. * Constructs a new spot light node.
  31193. *
  31194. * @param {SpotLight?} [light=null] - The spot light source.
  31195. */
  31196. constructor( light = null ) {
  31197. super( light );
  31198. /**
  31199. * Uniform node representing the cone cosine.
  31200. *
  31201. * @type {UniformNode<float>}
  31202. */
  31203. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  31204. /**
  31205. * Uniform node representing the penumbra cosine.
  31206. *
  31207. * @type {UniformNode<float>}
  31208. */
  31209. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  31210. /**
  31211. * Uniform node representing the cutoff distance.
  31212. *
  31213. * @type {UniformNode<float>}
  31214. */
  31215. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  31216. /**
  31217. * Uniform node representing the decay exponent.
  31218. *
  31219. * @type {UniformNode<float>}
  31220. */
  31221. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  31222. }
  31223. /**
  31224. * Overwritten to updated spot light specific uniforms.
  31225. *
  31226. * @param {NodeFrame} frame - A reference to the current node frame.
  31227. */
  31228. update( frame ) {
  31229. super.update( frame );
  31230. const { light } = this;
  31231. this.coneCosNode.value = Math.cos( light.angle );
  31232. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  31233. this.cutoffDistanceNode.value = light.distance;
  31234. this.decayExponentNode.value = light.decay;
  31235. }
  31236. /**
  31237. * Computes the spot attenuation for the given angle.
  31238. *
  31239. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  31240. * @return {Node<float>} The spot attenuation.
  31241. */
  31242. getSpotAttenuation( angleCosine ) {
  31243. const { coneCosNode, penumbraCosNode } = this;
  31244. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  31245. }
  31246. setup( builder ) {
  31247. super.setup( builder );
  31248. const lightingModel = builder.context.lightingModel;
  31249. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  31250. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  31251. const lightDirection = lVector.normalize();
  31252. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  31253. const spotAttenuation = this.getSpotAttenuation( angleCos );
  31254. const lightDistance = lVector.length();
  31255. const lightAttenuation = getDistanceAttenuation( {
  31256. lightDistance,
  31257. cutoffDistance: cutoffDistanceNode,
  31258. decayExponent: decayExponentNode
  31259. } );
  31260. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  31261. if ( light.map ) {
  31262. const spotLightCoord = lightProjectionUV( light );
  31263. const projectedTexture = texture( light.map, spotLightCoord.xy ).onRenderUpdate( () => light.map );
  31264. const inSpotLightMap = spotLightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  31265. lightColor = inSpotLightMap.select( lightColor.mul( projectedTexture ), lightColor );
  31266. }
  31267. const reflectedLight = builder.context.reflectedLight;
  31268. lightingModel.direct( {
  31269. lightDirection,
  31270. lightColor,
  31271. reflectedLight
  31272. }, builder.stack, builder );
  31273. }
  31274. }
  31275. /**
  31276. * An IES version of the default spot light node.
  31277. *
  31278. * @augments SpotLightNode
  31279. */
  31280. class IESSpotLightNode extends SpotLightNode {
  31281. static get type() {
  31282. return 'IESSpotLightNode';
  31283. }
  31284. /**
  31285. * Overwrites the default implementation to compute an IES conform spot attenuation.
  31286. *
  31287. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  31288. * @return {Node<float>} The spot attenuation.
  31289. */
  31290. getSpotAttenuation( angleCosine ) {
  31291. const iesMap = this.light.iesMap;
  31292. let spotAttenuation = null;
  31293. if ( iesMap && iesMap.isTexture === true ) {
  31294. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  31295. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  31296. } else {
  31297. spotAttenuation = super.getSpotAttenuation( angleCosine );
  31298. }
  31299. return spotAttenuation;
  31300. }
  31301. }
  31302. /**
  31303. * Module for representing ambient lights as nodes.
  31304. *
  31305. * @augments AnalyticLightNode
  31306. */
  31307. class AmbientLightNode extends AnalyticLightNode {
  31308. static get type() {
  31309. return 'AmbientLightNode';
  31310. }
  31311. /**
  31312. * Constructs a new ambient light node.
  31313. *
  31314. * @param {AmbientLight?} [light=null] - The ambient light source.
  31315. */
  31316. constructor( light = null ) {
  31317. super( light );
  31318. }
  31319. setup( { context } ) {
  31320. context.irradiance.addAssign( this.colorNode );
  31321. }
  31322. }
  31323. /**
  31324. * Module for representing hemisphere lights as nodes.
  31325. *
  31326. * @augments AnalyticLightNode
  31327. */
  31328. class HemisphereLightNode extends AnalyticLightNode {
  31329. static get type() {
  31330. return 'HemisphereLightNode';
  31331. }
  31332. /**
  31333. * Constructs a new hemisphere light node.
  31334. *
  31335. * @param {HemisphereLight?} [light=null] - The hemisphere light source.
  31336. */
  31337. constructor( light = null ) {
  31338. super( light );
  31339. /**
  31340. * Uniform node representing the light's position.
  31341. *
  31342. * @type {UniformNode<vec3>}
  31343. */
  31344. this.lightPositionNode = lightPosition( light );
  31345. /**
  31346. * A node representing the light's direction.
  31347. *
  31348. * @type {Node<vec3>}
  31349. */
  31350. this.lightDirectionNode = this.lightPositionNode.normalize();
  31351. /**
  31352. * Uniform node representing the light's ground color.
  31353. *
  31354. * @type {UniformNode<vec3>}
  31355. */
  31356. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  31357. }
  31358. /**
  31359. * Overwritten to updated hemisphere light specific uniforms.
  31360. *
  31361. * @param {NodeFrame} frame - A reference to the current node frame.
  31362. */
  31363. update( frame ) {
  31364. const { light } = this;
  31365. super.update( frame );
  31366. this.lightPositionNode.object3d = light;
  31367. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  31368. }
  31369. setup( builder ) {
  31370. const { colorNode, groundColorNode, lightDirectionNode } = this;
  31371. const dotNL = normalView.dot( lightDirectionNode );
  31372. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  31373. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  31374. builder.context.irradiance.addAssign( irradiance );
  31375. }
  31376. }
  31377. /**
  31378. * Module for representing light probes as nodes.
  31379. *
  31380. * @augments AnalyticLightNode
  31381. */
  31382. class LightProbeNode extends AnalyticLightNode {
  31383. static get type() {
  31384. return 'LightProbeNode';
  31385. }
  31386. /**
  31387. * Constructs a new light probe node.
  31388. *
  31389. * @param {LightProbe?} [light=null] - The light probe.
  31390. */
  31391. constructor( light = null ) {
  31392. super( light );
  31393. const array = [];
  31394. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  31395. /**
  31396. * Light probe represented as a uniform of spherical harmonics.
  31397. *
  31398. * @type {UniformArrayNode}
  31399. */
  31400. this.lightProbe = uniformArray( array );
  31401. }
  31402. /**
  31403. * Overwritten to updated light probe specific uniforms.
  31404. *
  31405. * @param {NodeFrame} frame - A reference to the current node frame.
  31406. */
  31407. update( frame ) {
  31408. const { light } = this;
  31409. super.update( frame );
  31410. //
  31411. for ( let i = 0; i < 9; i ++ ) {
  31412. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  31413. }
  31414. }
  31415. setup( builder ) {
  31416. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  31417. builder.context.irradiance.addAssign( irradiance );
  31418. }
  31419. }
  31420. /**
  31421. * Base class for node parsers. A derived parser must be implemented
  31422. * for each supported native shader language.
  31423. */
  31424. class NodeParser {
  31425. /**
  31426. * The method parses the given native code an returns a node function.
  31427. *
  31428. * @abstract
  31429. * @param {String} source - The native shader code.
  31430. * @return {NodeFunction} A node function.
  31431. */
  31432. parseFunction( /*source*/ ) {
  31433. console.warn( 'Abstract function.' );
  31434. }
  31435. }
  31436. /**
  31437. * Base class for node functions. A derived module must be implemented
  31438. * for each supported native shader language. Similar to other `Node*` modules,
  31439. * this class is only relevant during the building process and not used
  31440. * in user-level code.
  31441. */
  31442. class NodeFunction {
  31443. /**
  31444. * Constructs a new node function.
  31445. *
  31446. * @param {String} type - The node type. This type is the return type of the node function.
  31447. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  31448. * @param {String} [name=''] - The function's name.
  31449. * @param {String} [precision=''] - The precision qualifier.
  31450. */
  31451. constructor( type, inputs, name = '', precision = '' ) {
  31452. /**
  31453. * The node type. This type is the return type of the node function.
  31454. *
  31455. * @type {String}
  31456. */
  31457. this.type = type;
  31458. /**
  31459. * The function's inputs.
  31460. *
  31461. * @type {Array<NodeFunctionInput>}
  31462. */
  31463. this.inputs = inputs;
  31464. /**
  31465. * The name of the uniform.
  31466. *
  31467. * @type {String}
  31468. * @default ''
  31469. */
  31470. this.name = name;
  31471. /**
  31472. * The precision qualifier.
  31473. *
  31474. * @type {String}
  31475. * @default ''
  31476. */
  31477. this.precision = precision;
  31478. }
  31479. /**
  31480. * This method returns the native code of the node function.
  31481. *
  31482. * @abstract
  31483. * @param {String} name - The function's name.
  31484. * @return {String} A shader code.
  31485. */
  31486. getCode( /*name = this.name*/ ) {
  31487. console.warn( 'Abstract function.' );
  31488. }
  31489. }
  31490. NodeFunction.isNodeFunction = true;
  31491. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  31492. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  31493. const pragmaMain = '#pragma main';
  31494. const parse$1 = ( source ) => {
  31495. source = source.trim();
  31496. const pragmaMainIndex = source.indexOf( pragmaMain );
  31497. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  31498. const declaration = mainCode.match( declarationRegexp$1 );
  31499. if ( declaration !== null && declaration.length === 5 ) {
  31500. // tokenizer
  31501. const inputsCode = declaration[ 4 ];
  31502. const propsMatches = [];
  31503. let nameMatch = null;
  31504. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  31505. propsMatches.push( nameMatch );
  31506. }
  31507. // parser
  31508. const inputs = [];
  31509. let i = 0;
  31510. while ( i < propsMatches.length ) {
  31511. const isConst = propsMatches[ i ][ 0 ] === 'const';
  31512. if ( isConst === true ) {
  31513. i ++;
  31514. }
  31515. let qualifier = propsMatches[ i ][ 0 ];
  31516. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  31517. i ++;
  31518. } else {
  31519. qualifier = '';
  31520. }
  31521. const type = propsMatches[ i ++ ][ 0 ];
  31522. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  31523. if ( Number.isNaN( count ) === false ) i ++;
  31524. else count = null;
  31525. const name = propsMatches[ i ++ ][ 0 ];
  31526. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  31527. }
  31528. //
  31529. const blockCode = mainCode.substring( declaration[ 0 ].length );
  31530. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  31531. const type = declaration[ 2 ];
  31532. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  31533. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  31534. return {
  31535. type,
  31536. inputs,
  31537. name,
  31538. precision,
  31539. inputsCode,
  31540. blockCode,
  31541. headerCode
  31542. };
  31543. } else {
  31544. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  31545. }
  31546. };
  31547. /**
  31548. * This class represents a GLSL node function.
  31549. *
  31550. * @augments NodeFunction
  31551. */
  31552. class GLSLNodeFunction extends NodeFunction {
  31553. /**
  31554. * Constructs a new GLSL node function.
  31555. *
  31556. * @param {String} source - The GLSL source.
  31557. */
  31558. constructor( source ) {
  31559. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  31560. super( type, inputs, name, precision );
  31561. this.inputsCode = inputsCode;
  31562. this.blockCode = blockCode;
  31563. this.headerCode = headerCode;
  31564. }
  31565. /**
  31566. * This method returns the GLSL code of the node function.
  31567. *
  31568. * @param {String} [name=this.name] - The function's name.
  31569. * @return {String} The shader code.
  31570. */
  31571. getCode( name = this.name ) {
  31572. let code;
  31573. const blockCode = this.blockCode;
  31574. if ( blockCode !== '' ) {
  31575. const { type, inputsCode, headerCode, precision } = this;
  31576. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  31577. if ( precision !== '' ) {
  31578. declarationCode = `${ precision } ${ declarationCode }`;
  31579. }
  31580. code = headerCode + declarationCode + blockCode;
  31581. } else {
  31582. // interface function
  31583. code = '';
  31584. }
  31585. return code;
  31586. }
  31587. }
  31588. /**
  31589. * A GLSL node parser.
  31590. *
  31591. * @augments NodeParser
  31592. */
  31593. class GLSLNodeParser extends NodeParser {
  31594. /**
  31595. * The method parses the given GLSL code an returns a node function.
  31596. *
  31597. * @param {String} source - The GLSL code.
  31598. * @return {GLSLNodeFunction} A node function.
  31599. */
  31600. parseFunction( source ) {
  31601. return new GLSLNodeFunction( source );
  31602. }
  31603. }
  31604. const _outputNodeMap = new WeakMap();
  31605. /**
  31606. * This renderer module manages node-related objects and is the
  31607. * primary interface between the renderer and the node system.
  31608. *
  31609. * @private
  31610. * @augments DataMap
  31611. */
  31612. class Nodes extends DataMap {
  31613. /**
  31614. * Constructs a new nodes management component.
  31615. *
  31616. * @param {Renderer} renderer - The renderer.
  31617. * @param {Backend} backend - The renderer's backend.
  31618. */
  31619. constructor( renderer, backend ) {
  31620. super();
  31621. /**
  31622. * The renderer.
  31623. *
  31624. * @type {Renderer}
  31625. */
  31626. this.renderer = renderer;
  31627. /**
  31628. * The renderer's backend.
  31629. *
  31630. * @type {Backend}
  31631. */
  31632. this.backend = backend;
  31633. /**
  31634. * The node frame.
  31635. *
  31636. * @type {Renderer}
  31637. */
  31638. this.nodeFrame = new NodeFrame();
  31639. /**
  31640. * A cache for managing node builder states.
  31641. *
  31642. * @type {Map<Number,NodeBuilderState>}
  31643. */
  31644. this.nodeBuilderCache = new Map();
  31645. /**
  31646. * A cache for managing data cache key data.
  31647. *
  31648. * @type {ChainMap}
  31649. */
  31650. this.callHashCache = new ChainMap();
  31651. /**
  31652. * A cache for managing node uniforms group data.
  31653. *
  31654. * @type {ChainMap}
  31655. */
  31656. this.groupsData = new ChainMap();
  31657. /**
  31658. * A cache for managing node objects of
  31659. * scene properties like fog or environments.
  31660. *
  31661. * @type {Object<String,WeakMap>}
  31662. */
  31663. this.cacheLib = {};
  31664. }
  31665. /**
  31666. * Returns `true` if the given node uniforms group must be updated or not.
  31667. *
  31668. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  31669. * @return {Boolean} Whether the node uniforms group requires an update or not.
  31670. */
  31671. updateGroup( nodeUniformsGroup ) {
  31672. const groupNode = nodeUniformsGroup.groupNode;
  31673. const name = groupNode.name;
  31674. // objectGroup is always updated
  31675. if ( name === objectGroup.name ) return true;
  31676. // renderGroup is updated once per render/compute call
  31677. if ( name === renderGroup.name ) {
  31678. const uniformsGroupData = this.get( nodeUniformsGroup );
  31679. const renderId = this.nodeFrame.renderId;
  31680. if ( uniformsGroupData.renderId !== renderId ) {
  31681. uniformsGroupData.renderId = renderId;
  31682. return true;
  31683. }
  31684. return false;
  31685. }
  31686. // frameGroup is updated once per frame
  31687. if ( name === frameGroup.name ) {
  31688. const uniformsGroupData = this.get( nodeUniformsGroup );
  31689. const frameId = this.nodeFrame.frameId;
  31690. if ( uniformsGroupData.frameId !== frameId ) {
  31691. uniformsGroupData.frameId = frameId;
  31692. return true;
  31693. }
  31694. return false;
  31695. }
  31696. // other groups are updated just when groupNode.needsUpdate is true
  31697. const groupChain = [ groupNode, nodeUniformsGroup ];
  31698. let groupData = this.groupsData.get( groupChain );
  31699. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  31700. if ( groupData.version !== groupNode.version ) {
  31701. groupData.version = groupNode.version;
  31702. return true;
  31703. }
  31704. return false;
  31705. }
  31706. /**
  31707. * Returns the cache key for the given render object.
  31708. *
  31709. * @param {RenderObject} renderObject - The render object.
  31710. * @return {Number} The cache key.
  31711. */
  31712. getForRenderCacheKey( renderObject ) {
  31713. return renderObject.initialCacheKey;
  31714. }
  31715. /**
  31716. * Returns a node builder state for the given render object.
  31717. *
  31718. * @param {RenderObject} renderObject - The render object.
  31719. * @return {NodeBuilderState} The node builder state.
  31720. */
  31721. getForRender( renderObject ) {
  31722. const renderObjectData = this.get( renderObject );
  31723. let nodeBuilderState = renderObjectData.nodeBuilderState;
  31724. if ( nodeBuilderState === undefined ) {
  31725. const { nodeBuilderCache } = this;
  31726. const cacheKey = this.getForRenderCacheKey( renderObject );
  31727. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  31728. if ( nodeBuilderState === undefined ) {
  31729. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  31730. nodeBuilder.scene = renderObject.scene;
  31731. nodeBuilder.material = renderObject.material;
  31732. nodeBuilder.camera = renderObject.camera;
  31733. nodeBuilder.context.material = renderObject.material;
  31734. nodeBuilder.lightsNode = renderObject.lightsNode;
  31735. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  31736. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  31737. nodeBuilder.clippingContext = renderObject.clippingContext;
  31738. nodeBuilder.build();
  31739. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  31740. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  31741. }
  31742. nodeBuilderState.usedTimes ++;
  31743. renderObjectData.nodeBuilderState = nodeBuilderState;
  31744. }
  31745. return nodeBuilderState;
  31746. }
  31747. /**
  31748. * Deletes the given object from the internal data map
  31749. *
  31750. * @param {Any} object - The object to delete.
  31751. * @return {Object?} The deleted dictionary.
  31752. */
  31753. delete( object ) {
  31754. if ( object.isRenderObject ) {
  31755. const nodeBuilderState = this.get( object ).nodeBuilderState;
  31756. nodeBuilderState.usedTimes --;
  31757. if ( nodeBuilderState.usedTimes === 0 ) {
  31758. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  31759. }
  31760. }
  31761. return super.delete( object );
  31762. }
  31763. /**
  31764. * Returns a node builder state for the given compute node.
  31765. *
  31766. * @param {Node} computeNode - The compute node.
  31767. * @return {NodeBuilderState} The node builder state.
  31768. */
  31769. getForCompute( computeNode ) {
  31770. const computeData = this.get( computeNode );
  31771. let nodeBuilderState = computeData.nodeBuilderState;
  31772. if ( nodeBuilderState === undefined ) {
  31773. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  31774. nodeBuilder.build();
  31775. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  31776. computeData.nodeBuilderState = nodeBuilderState;
  31777. }
  31778. return nodeBuilderState;
  31779. }
  31780. /**
  31781. * Creates a node builder state for the given node builder.
  31782. *
  31783. * @private
  31784. * @param {NodeBuilder} nodeBuilder - The node builder.
  31785. * @return {NodeBuilderState} The node builder state.
  31786. */
  31787. _createNodeBuilderState( nodeBuilder ) {
  31788. return new NodeBuilderState(
  31789. nodeBuilder.vertexShader,
  31790. nodeBuilder.fragmentShader,
  31791. nodeBuilder.computeShader,
  31792. nodeBuilder.getAttributesArray(),
  31793. nodeBuilder.getBindings(),
  31794. nodeBuilder.updateNodes,
  31795. nodeBuilder.updateBeforeNodes,
  31796. nodeBuilder.updateAfterNodes,
  31797. nodeBuilder.monitor,
  31798. nodeBuilder.transforms
  31799. );
  31800. }
  31801. /**
  31802. * Returns an environment node for the current configured
  31803. * scene environment.
  31804. *
  31805. * @param {Scene} scene - The scene.
  31806. * @return {Node} A node representing the current scene environment.
  31807. */
  31808. getEnvironmentNode( scene ) {
  31809. this.updateEnvironment( scene );
  31810. let environmentNode = null;
  31811. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  31812. environmentNode = scene.environmentNode;
  31813. } else {
  31814. const sceneData = this.get( scene );
  31815. if ( sceneData.environmentNode ) {
  31816. environmentNode = sceneData.environmentNode;
  31817. }
  31818. }
  31819. return environmentNode;
  31820. }
  31821. /**
  31822. * Returns a background node for the current configured
  31823. * scene background.
  31824. *
  31825. * @param {Scene} scene - The scene.
  31826. * @return {Node} A node representing the current scene background.
  31827. */
  31828. getBackgroundNode( scene ) {
  31829. this.updateBackground( scene );
  31830. let backgroundNode = null;
  31831. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  31832. backgroundNode = scene.backgroundNode;
  31833. } else {
  31834. const sceneData = this.get( scene );
  31835. if ( sceneData.backgroundNode ) {
  31836. backgroundNode = sceneData.backgroundNode;
  31837. }
  31838. }
  31839. return backgroundNode;
  31840. }
  31841. /**
  31842. * Returns a fog node for the current configured scene fog.
  31843. *
  31844. * @param {Scene} scene - The scene.
  31845. * @return {Node} A node representing the current scene fog.
  31846. */
  31847. getFogNode( scene ) {
  31848. this.updateFog( scene );
  31849. return scene.fogNode || this.get( scene ).fogNode || null;
  31850. }
  31851. /**
  31852. * Returns a cache key for the given scene and lights node.
  31853. * This key is used by `RenderObject` as a part of the dynamic
  31854. * cache key (a key that must be checked every time the render
  31855. * objects is drawn).
  31856. *
  31857. * @param {Scene} scene - The scene.
  31858. * @param {LightsNode} lightsNode - The lights node.
  31859. * @return {Number} The cache key.
  31860. */
  31861. getCacheKey( scene, lightsNode ) {
  31862. const chain = [ scene, lightsNode ];
  31863. const callId = this.renderer.info.calls;
  31864. let cacheKeyData = this.callHashCache.get( chain );
  31865. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  31866. const environmentNode = this.getEnvironmentNode( scene );
  31867. const fogNode = this.getFogNode( scene );
  31868. const values = [];
  31869. if ( lightsNode ) values.push( lightsNode.getCacheKey( true ) );
  31870. if ( environmentNode ) values.push( environmentNode.getCacheKey() );
  31871. if ( fogNode ) values.push( fogNode.getCacheKey() );
  31872. values.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  31873. cacheKeyData = {
  31874. callId,
  31875. cacheKey: hashArray( values )
  31876. };
  31877. this.callHashCache.set( chain, cacheKeyData );
  31878. }
  31879. return cacheKeyData.cacheKey;
  31880. }
  31881. /**
  31882. * A boolean that indicates whether tone mapping should be enabled
  31883. * or not.
  31884. *
  31885. * @type {Boolean}
  31886. */
  31887. get isToneMappingState() {
  31888. return this.renderer.getRenderTarget() ? false : true;
  31889. }
  31890. /**
  31891. * If a scene background is configured, this method makes sure to
  31892. * represent the background with a corresponding node-based implementation.
  31893. *
  31894. * @param {Scene} scene - The scene.
  31895. */
  31896. updateBackground( scene ) {
  31897. const sceneData = this.get( scene );
  31898. const background = scene.background;
  31899. if ( background ) {
  31900. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  31901. if ( sceneData.background !== background || forceUpdate ) {
  31902. const backgroundNode = this.getCacheNode( 'background', background, () => {
  31903. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  31904. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  31905. return pmremTexture( background );
  31906. } else {
  31907. let envMap;
  31908. if ( background.isCubeTexture === true ) {
  31909. envMap = cubeTexture( background );
  31910. } else {
  31911. envMap = texture( background );
  31912. }
  31913. return cubeMapNode( envMap );
  31914. }
  31915. } else if ( background.isTexture === true ) {
  31916. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  31917. } else if ( background.isColor !== true ) {
  31918. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  31919. }
  31920. }, forceUpdate );
  31921. sceneData.backgroundNode = backgroundNode;
  31922. sceneData.background = background;
  31923. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  31924. }
  31925. } else if ( sceneData.backgroundNode ) {
  31926. delete sceneData.backgroundNode;
  31927. delete sceneData.background;
  31928. }
  31929. }
  31930. /**
  31931. * This method is part of the caching of nodes which are used to represents the
  31932. * scene's background, fog or environment.
  31933. *
  31934. * @param {String} type - The type of object to cache.
  31935. * @param {Object} object - The object.
  31936. * @param {Function} callback - A callback that produces a node representation for the given object.
  31937. * @param {Boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  31938. * @return {Node} The node representation.
  31939. */
  31940. getCacheNode( type, object, callback, forceUpdate = false ) {
  31941. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  31942. let node = nodeCache.get( object );
  31943. if ( node === undefined || forceUpdate ) {
  31944. node = callback();
  31945. nodeCache.set( object, node );
  31946. }
  31947. return node;
  31948. }
  31949. /**
  31950. * If a scene fog is configured, this method makes sure to
  31951. * represent the fog with a corresponding node-based implementation.
  31952. *
  31953. * @param {Scene} scene - The scene.
  31954. */
  31955. updateFog( scene ) {
  31956. const sceneData = this.get( scene );
  31957. const sceneFog = scene.fog;
  31958. if ( sceneFog ) {
  31959. if ( sceneData.fog !== sceneFog ) {
  31960. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  31961. if ( sceneFog.isFogExp2 ) {
  31962. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  31963. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  31964. return fog( color, densityFogFactor( density ) );
  31965. } else if ( sceneFog.isFog ) {
  31966. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  31967. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  31968. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  31969. return fog( color, rangeFogFactor( near, far ) );
  31970. } else {
  31971. console.error( 'THREE.Renderer: Unsupported fog configuration.', sceneFog );
  31972. }
  31973. } );
  31974. sceneData.fogNode = fogNode;
  31975. sceneData.fog = sceneFog;
  31976. }
  31977. } else {
  31978. delete sceneData.fogNode;
  31979. delete sceneData.fog;
  31980. }
  31981. }
  31982. /**
  31983. * If a scene environment is configured, this method makes sure to
  31984. * represent the environment with a corresponding node-based implementation.
  31985. *
  31986. * @param {Scene} scene - The scene.
  31987. */
  31988. updateEnvironment( scene ) {
  31989. const sceneData = this.get( scene );
  31990. const environment = scene.environment;
  31991. if ( environment ) {
  31992. if ( sceneData.environment !== environment ) {
  31993. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  31994. if ( environment.isCubeTexture === true ) {
  31995. return cubeTexture( environment );
  31996. } else if ( environment.isTexture === true ) {
  31997. return texture( environment );
  31998. } else {
  31999. console.error( 'Nodes: Unsupported environment configuration.', environment );
  32000. }
  32001. } );
  32002. sceneData.environmentNode = environmentNode;
  32003. sceneData.environment = environment;
  32004. }
  32005. } else if ( sceneData.environmentNode ) {
  32006. delete sceneData.environmentNode;
  32007. delete sceneData.environment;
  32008. }
  32009. }
  32010. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  32011. const nodeFrame = this.nodeFrame;
  32012. nodeFrame.renderer = renderer;
  32013. nodeFrame.scene = scene;
  32014. nodeFrame.object = object;
  32015. nodeFrame.camera = camera;
  32016. nodeFrame.material = material;
  32017. return nodeFrame;
  32018. }
  32019. getNodeFrameForRender( renderObject ) {
  32020. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  32021. }
  32022. /**
  32023. * Returns the current output cache key.
  32024. *
  32025. * @return {String} The output cache key.
  32026. */
  32027. getOutputCacheKey() {
  32028. const renderer = this.renderer;
  32029. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  32030. }
  32031. /**
  32032. * Checks if the output configuration (tone mapping and color space) for
  32033. * the given target has changed.
  32034. *
  32035. * @param {Texture} outputTarget - The output target.
  32036. * @return {Boolean} Whether the output configuration has changed or not.
  32037. */
  32038. hasOutputChange( outputTarget ) {
  32039. const cacheKey = _outputNodeMap.get( outputTarget );
  32040. return cacheKey !== this.getOutputCacheKey();
  32041. }
  32042. /**
  32043. * Returns a node that represents the output configuration (tone mapping and
  32044. * color space) for the current target.
  32045. *
  32046. * @param {Texture} outputTarget - The output target.
  32047. * @return {Node} The output node.
  32048. */
  32049. getOutputNode( outputTarget ) {
  32050. const renderer = this.renderer;
  32051. const cacheKey = this.getOutputCacheKey();
  32052. const output = texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  32053. _outputNodeMap.set( outputTarget, cacheKey );
  32054. return output;
  32055. }
  32056. /**
  32057. * Triggers the call of `updateBefore()` methods
  32058. * for all nodes of the given render object.
  32059. *
  32060. * @param {RenderObject} renderObject - The render object.
  32061. */
  32062. updateBefore( renderObject ) {
  32063. const nodeBuilder = renderObject.getNodeBuilderState();
  32064. for ( const node of nodeBuilder.updateBeforeNodes ) {
  32065. // update frame state for each node
  32066. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  32067. }
  32068. }
  32069. /**
  32070. * Triggers the call of `updateAfter()` methods
  32071. * for all nodes of the given render object.
  32072. *
  32073. * @param {RenderObject} renderObject - The render object.
  32074. */
  32075. updateAfter( renderObject ) {
  32076. const nodeBuilder = renderObject.getNodeBuilderState();
  32077. for ( const node of nodeBuilder.updateAfterNodes ) {
  32078. // update frame state for each node
  32079. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  32080. }
  32081. }
  32082. /**
  32083. * Triggers the call of `update()` methods
  32084. * for all nodes of the given compute node.
  32085. *
  32086. * @param {Node} computeNode - The compute node.
  32087. */
  32088. updateForCompute( computeNode ) {
  32089. const nodeFrame = this.getNodeFrame();
  32090. const nodeBuilder = this.getForCompute( computeNode );
  32091. for ( const node of nodeBuilder.updateNodes ) {
  32092. nodeFrame.updateNode( node );
  32093. }
  32094. }
  32095. /**
  32096. * Triggers the call of `update()` methods
  32097. * for all nodes of the given compute node.
  32098. *
  32099. * @param {RenderObject} renderObject - The render object.
  32100. */
  32101. updateForRender( renderObject ) {
  32102. const nodeFrame = this.getNodeFrameForRender( renderObject );
  32103. const nodeBuilder = renderObject.getNodeBuilderState();
  32104. for ( const node of nodeBuilder.updateNodes ) {
  32105. nodeFrame.updateNode( node );
  32106. }
  32107. }
  32108. /**
  32109. * Returns `true` if the given render object requires a refresh.
  32110. *
  32111. * @param {RenderObject} renderObject - The render object.
  32112. * @return {Boolean} Whether the given render object requires a refresh or not.
  32113. */
  32114. needsRefresh( renderObject ) {
  32115. const nodeFrame = this.getNodeFrameForRender( renderObject );
  32116. const monitor = renderObject.getMonitor();
  32117. return monitor.needsRefresh( renderObject, nodeFrame );
  32118. }
  32119. /**
  32120. * Frees the intenral resources.
  32121. */
  32122. dispose() {
  32123. super.dispose();
  32124. this.nodeFrame = new NodeFrame();
  32125. this.nodeBuilderCache = new Map();
  32126. this.cacheLib = {};
  32127. }
  32128. }
  32129. const _plane = /*@__PURE__*/ new Plane();
  32130. /**
  32131. * Represents the state that is used to perform clipping via clipping planes.
  32132. * There is a default clipping context for each render context. When the
  32133. * scene holds instances of `ClippingGroup`, there will be a context for each
  32134. * group.
  32135. *
  32136. * @private
  32137. */
  32138. class ClippingContext {
  32139. /**
  32140. * Constructs a new clipping context.
  32141. *
  32142. * @param {ClippingContext?} [parentContext=null] - A reference to the parent clipping context.
  32143. */
  32144. constructor( parentContext = null ) {
  32145. /**
  32146. * The clipping context's version.
  32147. *
  32148. * @type {Number}
  32149. * @readonly
  32150. */
  32151. this.version = 0;
  32152. /**
  32153. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  32154. *
  32155. * @type {Boolean?}
  32156. * @default null
  32157. */
  32158. this.clipIntersection = null;
  32159. /**
  32160. * The clipping context's cache key.
  32161. *
  32162. * @type {String}
  32163. */
  32164. this.cacheKey = '';
  32165. /**
  32166. * Whether the shadow pass is active or not.
  32167. *
  32168. * @type {Boolean}
  32169. * @default false
  32170. */
  32171. this.shadowPass = false;
  32172. /**
  32173. * The view normal matrix.
  32174. *
  32175. * @type {Matrix3}
  32176. */
  32177. this.viewNormalMatrix = new Matrix3();
  32178. /**
  32179. * Internal cache for maintaining clipping contexts.
  32180. *
  32181. * @type {WeakMap<ClippingGroup,ClippingContext>}
  32182. */
  32183. this.clippingGroupContexts = new WeakMap();
  32184. /**
  32185. * The intersection planes.
  32186. *
  32187. * @type {Array<Vector4>}
  32188. */
  32189. this.intersectionPlanes = [];
  32190. /**
  32191. * The intersection planes.
  32192. *
  32193. * @type {Array<Vector4>}
  32194. */
  32195. this.unionPlanes = [];
  32196. /**
  32197. * The version of the clipping context's parent context.
  32198. *
  32199. * @type {Number?}
  32200. * @readonly
  32201. */
  32202. this.parentVersion = null;
  32203. if ( parentContext !== null ) {
  32204. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  32205. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  32206. this.shadowPass = parentContext.shadowPass;
  32207. this.viewMatrix = parentContext.viewMatrix;
  32208. }
  32209. }
  32210. /**
  32211. * Projects the given source clipping planes and writes the result into the
  32212. * destination array.
  32213. *
  32214. * @param {Array<Plane>} source - The source clipping planes.
  32215. * @param {Array<Vector4>} destination - The destination.
  32216. * @param {Number} offset - The offset.
  32217. */
  32218. projectPlanes( source, destination, offset ) {
  32219. const l = source.length;
  32220. for ( let i = 0; i < l; i ++ ) {
  32221. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  32222. const v = destination[ offset + i ];
  32223. const normal = _plane.normal;
  32224. v.x = - normal.x;
  32225. v.y = - normal.y;
  32226. v.z = - normal.z;
  32227. v.w = _plane.constant;
  32228. }
  32229. }
  32230. /**
  32231. * Updates the root clipping context of a scene.
  32232. *
  32233. * @param {Scene} scene - The scene.
  32234. * @param {Camera} camera - The camera that is used to render the scene.
  32235. */
  32236. updateGlobal( scene, camera ) {
  32237. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowNodeMaterial );
  32238. this.viewMatrix = camera.matrixWorldInverse;
  32239. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  32240. }
  32241. /**
  32242. * Updates the clipping context.
  32243. *
  32244. * @param {ClippingContext} parentContext - The parent context.
  32245. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  32246. */
  32247. update( parentContext, clippingGroup ) {
  32248. let update = false;
  32249. if ( parentContext.version !== this.parentVersion ) {
  32250. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  32251. this.unionPlanes = Array.from( parentContext.unionPlanes );
  32252. this.parentVersion = parentContext.version;
  32253. }
  32254. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  32255. this.clipIntersection = clippingGroup.clipIntersection;
  32256. if ( this.clipIntersection ) {
  32257. this.unionPlanes.length = parentContext.unionPlanes.length;
  32258. } else {
  32259. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  32260. }
  32261. }
  32262. const srcClippingPlanes = clippingGroup.clippingPlanes;
  32263. const l = srcClippingPlanes.length;
  32264. let dstClippingPlanes;
  32265. let offset;
  32266. if ( this.clipIntersection ) {
  32267. dstClippingPlanes = this.intersectionPlanes;
  32268. offset = parentContext.intersectionPlanes.length;
  32269. } else {
  32270. dstClippingPlanes = this.unionPlanes;
  32271. offset = parentContext.unionPlanes.length;
  32272. }
  32273. if ( dstClippingPlanes.length !== offset + l ) {
  32274. dstClippingPlanes.length = offset + l;
  32275. for ( let i = 0; i < l; i ++ ) {
  32276. dstClippingPlanes[ offset + i ] = new Vector4();
  32277. }
  32278. update = true;
  32279. }
  32280. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  32281. if ( update ) {
  32282. this.version ++;
  32283. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  32284. }
  32285. }
  32286. /**
  32287. * Returns a clipping context for the given clipping group.
  32288. *
  32289. * @param {ClippingGroup} clippingGroup - The clipping group.
  32290. * @return {ClippingContext} The clipping context.
  32291. */
  32292. getGroupContext( clippingGroup ) {
  32293. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  32294. let context = this.clippingGroupContexts.get( clippingGroup );
  32295. if ( context === undefined ) {
  32296. context = new ClippingContext( this );
  32297. this.clippingGroupContexts.set( clippingGroup, context );
  32298. }
  32299. context.update( this, clippingGroup );
  32300. return context;
  32301. }
  32302. /**
  32303. * The count of union clipping planes.
  32304. *
  32305. * @type {Number}
  32306. * @readonly
  32307. */
  32308. get unionClippingCount() {
  32309. return this.unionPlanes.length;
  32310. }
  32311. }
  32312. /**
  32313. * This module is used to represent render bundles inside the renderer
  32314. * for further processing.
  32315. *
  32316. * @private
  32317. */
  32318. class RenderBundle {
  32319. /**
  32320. * Constructs a new bundle group.
  32321. *
  32322. * @param {BundleGroup} bundleGroup - The bundle group.
  32323. * @param {Camera} camera - The camera the bundle group is rendered with.
  32324. */
  32325. constructor( bundleGroup, camera ) {
  32326. this.bundleGroup = bundleGroup;
  32327. this.camera = camera;
  32328. }
  32329. }
  32330. /**
  32331. * This renderer module manages render bundles.
  32332. *
  32333. * @private
  32334. */
  32335. class RenderBundles {
  32336. /**
  32337. * Constructs a new render bundle management component.
  32338. */
  32339. constructor() {
  32340. /**
  32341. * A chain map for maintaining the render bundles.
  32342. *
  32343. * @type {ChainMap}
  32344. */
  32345. this.bundles = new ChainMap();
  32346. }
  32347. /**
  32348. * Returns a render bundle for the given bundle group and camera.
  32349. *
  32350. * @param {BundleGroup} bundleGroup - The bundle group.
  32351. * @param {Camera} camera - The camera the bundle group is rendered with.
  32352. * @return {RenderBundle} The render bundle.
  32353. */
  32354. get( bundleGroup, camera ) {
  32355. const bundles = this.bundles;
  32356. const keys = [ bundleGroup, camera ];
  32357. let bundle = bundles.get( keys );
  32358. if ( bundle === undefined ) {
  32359. bundle = new RenderBundle( bundleGroup, camera );
  32360. bundles.set( keys, bundle );
  32361. }
  32362. return bundle;
  32363. }
  32364. /**
  32365. * Frees all internal resources.
  32366. */
  32367. dispose() {
  32368. this.bundles = new ChainMap();
  32369. }
  32370. }
  32371. /**
  32372. * The purpose of a node library is to assign node implementations
  32373. * to existing library features. In `WebGPURenderer` lights, materials
  32374. * which are not based on `NodeMaterial` as well as tone mapping techniques
  32375. * are implemented with node-based modules.
  32376. *
  32377. * @private
  32378. */
  32379. class NodeLibrary {
  32380. /**
  32381. * Constructs a new node library.
  32382. */
  32383. constructor() {
  32384. /**
  32385. * A weak map that maps lights to light nodes.
  32386. *
  32387. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  32388. */
  32389. this.lightNodes = new WeakMap();
  32390. /**
  32391. * A map that maps materials to node materials.
  32392. *
  32393. * @type {WeakMap<String,NodeMaterial.constructor>}
  32394. */
  32395. this.materialNodes = new Map();
  32396. /**
  32397. * A map that maps tone mapping techniques (constants)
  32398. * to tone mapping node functions.
  32399. *
  32400. * @type {WeakMap<Number,Function>}
  32401. */
  32402. this.toneMappingNodes = new Map();
  32403. }
  32404. /**
  32405. * Returns a matching node material instance for the given material object.
  32406. *
  32407. * This method also assigns/copies the properties of the given material object
  32408. * to the node material. This is done to make sure the current material
  32409. * configuration carries over to the node version.
  32410. *
  32411. * @param {Material} material - A material.
  32412. * @return {NodeMaterial} The corresponding node material.
  32413. */
  32414. fromMaterial( material ) {
  32415. if ( material.isNodeMaterial ) return material;
  32416. let nodeMaterial = null;
  32417. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  32418. if ( nodeMaterialClass !== null ) {
  32419. nodeMaterial = new nodeMaterialClass();
  32420. for ( const key in material ) {
  32421. nodeMaterial[ key ] = material[ key ];
  32422. }
  32423. }
  32424. return nodeMaterial;
  32425. }
  32426. /**
  32427. * Adds a tone mapping node function for a tone mapping technique (constant).
  32428. *
  32429. * @param {Function} toneMappingNode - The tone mapping node function.
  32430. * @param {Number} toneMapping - The tone mapping.
  32431. */
  32432. addToneMapping( toneMappingNode, toneMapping ) {
  32433. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  32434. }
  32435. /**
  32436. * Returns a tone mapping node function for a tone mapping technique (constant).
  32437. *
  32438. * @param {Number} toneMapping - The tone mapping.
  32439. * @return {Function?} The tone mapping node function. Returns `null` if no node function is found.
  32440. */
  32441. getToneMappingFunction( toneMapping ) {
  32442. return this.toneMappingNodes.get( toneMapping ) || null;
  32443. }
  32444. /**
  32445. * Returns a node material class definition for a material type.
  32446. *
  32447. * @param {Sring} materialType - The material type.
  32448. * @return {NodeMaterial.constructor?} The node material class definition. Returns `null` if no node material is found.
  32449. */
  32450. getMaterialNodeClass( materialType ) {
  32451. return this.materialNodes.get( materialType ) || null;
  32452. }
  32453. /**
  32454. * Adds a node material class definition for a given material type.
  32455. *
  32456. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  32457. * @param {Sring} materialClassType - The material type.
  32458. */
  32459. addMaterial( materialNodeClass, materialClassType ) {
  32460. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  32461. }
  32462. /**
  32463. * Returns a light node class definition for a light class definition.
  32464. *
  32465. * @param {Light.constructor} light - The light class definition.
  32466. * @return {AnalyticLightNode.constructor?} The light node class definition. Returns `null` if no light node is found.
  32467. */
  32468. getLightNodeClass( light ) {
  32469. return this.lightNodes.get( light ) || null;
  32470. }
  32471. /**
  32472. * Adds a light node class definition for a given light class definition.
  32473. *
  32474. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  32475. * @param {Light.constructor} lightClass - The light class definition.
  32476. */
  32477. addLight( lightNodeClass, lightClass ) {
  32478. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  32479. }
  32480. /**
  32481. * Adds a node class definition for the given type to the provided type library.
  32482. *
  32483. * @param {Any} nodeClass - The node class definition.
  32484. * @param {String} type - The object type.
  32485. * @param {Map} library - The type library.
  32486. */
  32487. addType( nodeClass, type, library ) {
  32488. if ( library.has( type ) ) {
  32489. console.warn( `Redefinition of node ${ type }` );
  32490. return;
  32491. }
  32492. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  32493. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  32494. library.set( type, nodeClass );
  32495. }
  32496. /**
  32497. * Adds a node class definition for the given class definition to the provided type library.
  32498. *
  32499. * @param {Any} nodeClass - The node class definition.
  32500. * @param {Any} baseClass - The class definition.
  32501. * @param {WeakMap} library - The type library.
  32502. */
  32503. addClass( nodeClass, baseClass, library ) {
  32504. if ( library.has( baseClass ) ) {
  32505. console.warn( `Redefinition of node ${ baseClass.name }` );
  32506. return;
  32507. }
  32508. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  32509. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  32510. library.set( baseClass, nodeClass );
  32511. }
  32512. }
  32513. const _defaultLights = /*@__PURE__*/ new LightsNode();
  32514. /**
  32515. * This renderer module manages the lights nodes which are unique
  32516. * per scene and camera combination.
  32517. *
  32518. * The lights node itself is later configured in the render list
  32519. * with the actual lights from the scene.
  32520. *
  32521. * @private
  32522. * @augments ChainMap
  32523. */
  32524. class Lighting extends ChainMap {
  32525. /**
  32526. * Constructs a lighting management component.
  32527. */
  32528. constructor() {
  32529. super();
  32530. }
  32531. /**
  32532. * Creates a new lights node for the given array of lights.
  32533. *
  32534. * @param {Array<Light>} lights - The render object.
  32535. * @return {Boolean} Whether if the given render object has an initialized geometry or not.
  32536. */
  32537. createNode( lights = [] ) {
  32538. return new LightsNode().setLights( lights );
  32539. }
  32540. /**
  32541. * Returns a lights node for the given scene and camera.
  32542. *
  32543. * @param {Scene} scene - The scene.
  32544. * @param {Camera} camera - The camera.
  32545. * @return {LightsNode} The lights node.
  32546. */
  32547. getNode( scene, camera ) {
  32548. // ignore post-processing
  32549. if ( scene.isQuadMesh ) return _defaultLights;
  32550. // tiled lighting
  32551. const keys = [ scene, camera ];
  32552. let node = this.get( keys );
  32553. if ( node === undefined ) {
  32554. node = this.createNode();
  32555. this.set( keys, node );
  32556. }
  32557. return node;
  32558. }
  32559. }
  32560. /** @module Renderer **/
  32561. const _scene = /*@__PURE__*/ new Scene();
  32562. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  32563. const _screen = /*@__PURE__*/ new Vector4();
  32564. const _frustum = /*@__PURE__*/ new Frustum();
  32565. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  32566. const _vector4 = /*@__PURE__*/ new Vector4();
  32567. /**
  32568. * Base class for renderers.
  32569. */
  32570. class Renderer {
  32571. /**
  32572. * Constructs a new renderer.
  32573. *
  32574. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  32575. * @param {Object} parameters - The configuration parameter.
  32576. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  32577. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  32578. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  32579. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  32580. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  32581. * @param {Number} [parameters.samples=0] - When `antialias` is `true`, `4` samples are used by default. This parameter can set to any other integer value than 0
  32582. * to overwrite the default.
  32583. * @param {Function?} [parameters.getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  32584. */
  32585. constructor( backend, parameters = {} ) {
  32586. /**
  32587. * This flag can be used for type testing.
  32588. *
  32589. * @type {Boolean}
  32590. * @readonly
  32591. * @default true
  32592. */
  32593. this.isRenderer = true;
  32594. //
  32595. const {
  32596. logarithmicDepthBuffer = false,
  32597. alpha = true,
  32598. depth = true,
  32599. stencil = false,
  32600. antialias = false,
  32601. samples = 0,
  32602. getFallback = null
  32603. } = parameters;
  32604. /**
  32605. * A reference to the canvas element the renderer is drawing to.
  32606. * This value of this property will automatically be created by
  32607. * the renderer.
  32608. *
  32609. * @type {HTMLCanvasElement|OffscreenCanvas}
  32610. */
  32611. this.domElement = backend.getDomElement();
  32612. /**
  32613. * A reference to the current backend.
  32614. *
  32615. * @type {Backend}
  32616. */
  32617. this.backend = backend;
  32618. /**
  32619. * The number of MSAA samples.
  32620. *
  32621. * @type {Number}
  32622. * @default 0
  32623. */
  32624. this.samples = samples || ( antialias === true ) ? 4 : 0;
  32625. /**
  32626. * Whether the renderer should automatically clear the current rendering target
  32627. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  32628. * or the current bound render target (custom framebuffer).
  32629. *
  32630. * @type {Boolean}
  32631. * @default true
  32632. */
  32633. this.autoClear = true;
  32634. /**
  32635. * When `autoClear` is set to `true`, this property defines whether the renderer
  32636. * should clear the color buffer.
  32637. *
  32638. * @type {Boolean}
  32639. * @default true
  32640. */
  32641. this.autoClearColor = true;
  32642. /**
  32643. * When `autoClear` is set to `true`, this property defines whether the renderer
  32644. * should clear the depth buffer.
  32645. *
  32646. * @type {Boolean}
  32647. * @default true
  32648. */
  32649. this.autoClearDepth = true;
  32650. /**
  32651. * When `autoClear` is set to `true`, this property defines whether the renderer
  32652. * should clear the stencil buffer.
  32653. *
  32654. * @type {Boolean}
  32655. * @default true
  32656. */
  32657. this.autoClearStencil = true;
  32658. /**
  32659. * Whether the default framebuffer should be transparent or opaque.
  32660. *
  32661. * @type {Boolean}
  32662. * @default true
  32663. */
  32664. this.alpha = alpha;
  32665. /**
  32666. * Whether logarithmic depth buffer is enabled or not.
  32667. *
  32668. * @type {Boolean}
  32669. * @default false
  32670. */
  32671. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  32672. /**
  32673. * Defines the output color space of the renderer.
  32674. *
  32675. * @type {String}
  32676. * @default SRGBColorSpace
  32677. */
  32678. this.outputColorSpace = SRGBColorSpace;
  32679. /**
  32680. * Defines the tone mapping of the renderer.
  32681. *
  32682. * @type {Number}
  32683. * @default NoToneMapping
  32684. */
  32685. this.toneMapping = NoToneMapping;
  32686. /**
  32687. * Defines the tone mapping exposure.
  32688. *
  32689. * @type {Number}
  32690. * @default 1
  32691. */
  32692. this.toneMappingExposure = 1.0;
  32693. /**
  32694. * Whether the renderer should sort its render lists or not.
  32695. *
  32696. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  32697. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  32698. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  32699. * e.g. manually determining each object's rendering order.
  32700. *
  32701. * @type {Boolean}
  32702. * @default true
  32703. */
  32704. this.sortObjects = true;
  32705. /**
  32706. * Whether the default framebuffer should have a depth buffer or not.
  32707. *
  32708. * @type {Boolean}
  32709. * @default true
  32710. */
  32711. this.depth = depth;
  32712. /**
  32713. * Whether the default framebuffer should have a stencil buffer or not.
  32714. *
  32715. * @type {Boolean}
  32716. * @default false
  32717. */
  32718. this.stencil = stencil;
  32719. /**
  32720. * Holds a series of statistical information about the GPU memory
  32721. * and the rendering process. Useful for debugging and monitoring.
  32722. *
  32723. * @type {Boolean}
  32724. */
  32725. this.info = new Info();
  32726. this.nodes = {
  32727. modelViewMatrix: null,
  32728. modelNormalViewMatrix: null
  32729. };
  32730. /**
  32731. * The node library defines how certain library objects like materials, lights
  32732. * or tone mapping functions are mapped to node types. This is required since
  32733. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  32734. * be part of the scene graph, they are internally represented as nodes for
  32735. * further processing.
  32736. *
  32737. * @type {NodeLibrary}
  32738. */
  32739. this.library = new NodeLibrary();
  32740. /**
  32741. * A map-like data structure for managing lights.
  32742. *
  32743. * @type {Lighting}
  32744. */
  32745. this.lighting = new Lighting();
  32746. // internals
  32747. /**
  32748. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  32749. *
  32750. * @private
  32751. * @type {Function}
  32752. */
  32753. this._getFallback = getFallback;
  32754. /**
  32755. * The renderer's pixel ration.
  32756. *
  32757. * @private
  32758. * @type {Number}
  32759. * @default 1
  32760. */
  32761. this._pixelRatio = 1;
  32762. /**
  32763. * The width of the renderer's default framebuffer in logical pixel unit.
  32764. *
  32765. * @private
  32766. * @type {Number}
  32767. */
  32768. this._width = this.domElement.width;
  32769. /**
  32770. * The height of the renderer's default framebuffer in logical pixel unit.
  32771. *
  32772. * @private
  32773. * @type {Number}
  32774. */
  32775. this._height = this.domElement.height;
  32776. /**
  32777. * The viewport of the renderer in logical pixel unit.
  32778. *
  32779. * @private
  32780. * @type {Vector4}
  32781. */
  32782. this._viewport = new Vector4( 0, 0, this._width, this._height );
  32783. /**
  32784. * The scissor rectangle of the renderer in logical pixel unit.
  32785. *
  32786. * @private
  32787. * @type {Vector4}
  32788. */
  32789. this._scissor = new Vector4( 0, 0, this._width, this._height );
  32790. /**
  32791. * Whether the scissor test should be enabled or not.
  32792. *
  32793. * @private
  32794. * @type {Vector4}
  32795. */
  32796. this._scissorTest = false;
  32797. /**
  32798. * A reference to a renderer module for managing shader attributes.
  32799. *
  32800. * @private
  32801. * @type {Attributes?}
  32802. * @default null
  32803. */
  32804. this._attributes = null;
  32805. /**
  32806. * A reference to a renderer module for managing geometries.
  32807. *
  32808. * @private
  32809. * @type {Geometries?}
  32810. * @default null
  32811. */
  32812. this._geometries = null;
  32813. /**
  32814. * A reference to a renderer module for managing node related logic.
  32815. *
  32816. * @private
  32817. * @type {Nodes?}
  32818. * @default null
  32819. */
  32820. this._nodes = null;
  32821. /**
  32822. * A reference to a renderer module for managing the internal animation loop.
  32823. *
  32824. * @private
  32825. * @type {Animation?}
  32826. * @default null
  32827. */
  32828. this._animation = null;
  32829. /**
  32830. * A reference to a renderer module for managing shader program bindings.
  32831. *
  32832. * @private
  32833. * @type {Bindings?}
  32834. * @default null
  32835. */
  32836. this._bindings = null;
  32837. /**
  32838. * A reference to a renderer module for managing render objects.
  32839. *
  32840. * @private
  32841. * @type {RenderObjects?}
  32842. * @default null
  32843. */
  32844. this._objects = null;
  32845. /**
  32846. * A reference to a renderer module for managing render and cmopute pipelines.
  32847. *
  32848. * @private
  32849. * @type {Pipelines?}
  32850. * @default null
  32851. */
  32852. this._pipelines = null;
  32853. /**
  32854. * A reference to a renderer module for managing render bundles.
  32855. *
  32856. * @private
  32857. * @type {RenderBundles?}
  32858. * @default null
  32859. */
  32860. this._bundles = null;
  32861. /**
  32862. * A reference to a renderer module for managing render lists.
  32863. *
  32864. * @private
  32865. * @type {RenderLists?}
  32866. * @default null
  32867. */
  32868. this._renderLists = null;
  32869. /**
  32870. * A reference to a renderer module for managing render contexts.
  32871. *
  32872. * @private
  32873. * @type {RenderContexts?}
  32874. * @default null
  32875. */
  32876. this._renderContexts = null;
  32877. /**
  32878. * A reference to a renderer module for managing textures.
  32879. *
  32880. * @private
  32881. * @type {Textures?}
  32882. * @default null
  32883. */
  32884. this._textures = null;
  32885. /**
  32886. * A reference to a renderer module for backgrounds.
  32887. *
  32888. * @private
  32889. * @type {Background?}
  32890. * @default null
  32891. */
  32892. this._background = null;
  32893. /**
  32894. * This fullscreen quad is used for internal render passes
  32895. * like the tone mapping and color space output pass.
  32896. *
  32897. * @private
  32898. * @type {QuadMesh}
  32899. */
  32900. this._quad = new QuadMesh( new NodeMaterial() );
  32901. this._quad.material.name = 'Renderer_output';
  32902. /**
  32903. * A reference to the current render context.
  32904. *
  32905. * @private
  32906. * @type {RenderContext?}
  32907. * @default null
  32908. */
  32909. this._currentRenderContext = null;
  32910. /**
  32911. * A custom sort function for the opaque render list.
  32912. *
  32913. * @private
  32914. * @type {Function?}
  32915. * @default null
  32916. */
  32917. this._opaqueSort = null;
  32918. /**
  32919. * A custom sort function for the transparent render list.
  32920. *
  32921. * @private
  32922. * @type {Function?}
  32923. * @default null
  32924. */
  32925. this._transparentSort = null;
  32926. /**
  32927. * The framebuffer target.
  32928. *
  32929. * @private
  32930. * @type {RenderTarget?}
  32931. * @default null
  32932. */
  32933. this._frameBufferTarget = null;
  32934. const alphaClear = this.alpha === true ? 0 : 1;
  32935. /**
  32936. * The clear color value.
  32937. *
  32938. * @private
  32939. * @type {Color4}
  32940. */
  32941. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  32942. /**
  32943. * The clear depth value.
  32944. *
  32945. * @private
  32946. * @type {Number}
  32947. * @default 1
  32948. */
  32949. this._clearDepth = 1;
  32950. /**
  32951. * The clear stencil value.
  32952. *
  32953. * @private
  32954. * @type {Number}
  32955. * @default 0
  32956. */
  32957. this._clearStencil = 0;
  32958. /**
  32959. * The current render target.
  32960. *
  32961. * @private
  32962. * @type {RenderTarget?}
  32963. * @default null
  32964. */
  32965. this._renderTarget = null;
  32966. /**
  32967. * The active cube face.
  32968. *
  32969. * @private
  32970. * @type {Number}
  32971. * @default 0
  32972. */
  32973. this._activeCubeFace = 0;
  32974. /**
  32975. * The active mipmap level.
  32976. *
  32977. * @private
  32978. * @type {Number}
  32979. * @default 0
  32980. */
  32981. this._activeMipmapLevel = 0;
  32982. /**
  32983. * The MRT setting.
  32984. *
  32985. * @private
  32986. * @type {MRTNode?}
  32987. * @default null
  32988. */
  32989. this._mrt = null;
  32990. /**
  32991. * This function defines how a render object is going
  32992. * to be rendered.
  32993. *
  32994. * @private
  32995. * @type {Function?}
  32996. * @default null
  32997. */
  32998. this._renderObjectFunction = null;
  32999. /**
  33000. * Used to keep track of the current render object function.
  33001. *
  33002. * @private
  33003. * @type {Function?}
  33004. * @default null
  33005. */
  33006. this._currentRenderObjectFunction = null;
  33007. /**
  33008. * Used to keep track of the current render bundle.
  33009. *
  33010. * @private
  33011. * @type {RenderBundle?}
  33012. * @default null
  33013. */
  33014. this._currentRenderBundle = null;
  33015. /**
  33016. * Next to `_renderObjectFunction()`, this function provides another hook
  33017. * for influening the render process of a render object. It is meant for internal
  33018. * use and only relevant for `compileAsync()` right now. Instead of using
  33019. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  33020. * a different function might be used which performs no draw but just the node
  33021. * and pipeline updates.
  33022. *
  33023. * @private
  33024. * @type {Function?}
  33025. * @default null
  33026. */
  33027. this._handleObjectFunction = this._renderObjectDirect;
  33028. /**
  33029. * Indicates whether the device has been lost or not. In WebGL terms, the device
  33030. * lost is considered as a context lost. When this is set to `true`, rendering
  33031. * isn't possible anymore.
  33032. *
  33033. * @private
  33034. * @type {Boolean}
  33035. * @default false
  33036. */
  33037. this._isDeviceLost = false;
  33038. /**
  33039. * A callback function that defines what should happen when a device/context lost occurs.
  33040. *
  33041. * @type {Function}
  33042. */
  33043. this.onDeviceLost = this._onDeviceLost;
  33044. /**
  33045. * Whether the renderer has been initialized or not.
  33046. *
  33047. * @private
  33048. * @type {Boolean}
  33049. * @default false
  33050. */
  33051. this._initialized = false;
  33052. /**
  33053. * A reference to the promise which initializes the renderer.
  33054. *
  33055. * @private
  33056. * @type {Promise?}
  33057. * @default null
  33058. */
  33059. this._initPromise = null;
  33060. /**
  33061. * An array of compilation promises which are used in `compileAsync()`.
  33062. *
  33063. * @private
  33064. * @type {Array<Promise>?}
  33065. * @default null
  33066. */
  33067. this._compilationPromises = null;
  33068. /**
  33069. * Whether the renderer should render transparent render objects or not.
  33070. *
  33071. * @type {Boolean}
  33072. * @default true
  33073. */
  33074. this.transparent = true;
  33075. /**
  33076. * Whether the renderer should render opaque render objects or not.
  33077. *
  33078. * @type {Boolean}
  33079. * @default true
  33080. */
  33081. this.opaque = true;
  33082. /**
  33083. * Shadow map configuration
  33084. * @typedef {Object} ShadowMapConfig
  33085. * @property {Boolean} enabled - Whether to globally enable shadows or not.
  33086. * @property {Number} type - The shadow map type.
  33087. */
  33088. /**
  33089. * The renderer's shadow configuration.
  33090. *
  33091. * @type {module:Renderer~ShadowMapConfig}
  33092. */
  33093. this.shadowMap = {
  33094. enabled: false,
  33095. type: PCFShadowMap
  33096. };
  33097. /**
  33098. * XR configuration.
  33099. * @typedef {Object} XRConfig
  33100. * @property {Boolean} enabled - Whether to globally enable XR or not.
  33101. */
  33102. /**
  33103. * The renderer's XR configuration.
  33104. *
  33105. * @type {module:Renderer~XRConfig}
  33106. */
  33107. this.xr = {
  33108. enabled: false
  33109. };
  33110. /**
  33111. * Debug configuration.
  33112. * @typedef {Object} DebugConfig
  33113. * @property {Boolean} checkShaderErrors - Whether shader errors should be checked or not.
  33114. * @property {Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  33115. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camerea and 3D object.
  33116. */
  33117. /**
  33118. * The renderer's debug configuration.
  33119. *
  33120. * @type {module:Renderer~DebugConfig}
  33121. */
  33122. this.debug = {
  33123. checkShaderErrors: true,
  33124. onShaderError: null,
  33125. getShaderAsync: async ( scene, camera, object ) => {
  33126. await this.compileAsync( scene, camera );
  33127. const renderList = this._renderLists.get( scene, camera );
  33128. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  33129. const material = scene.overrideMaterial || object.material;
  33130. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  33131. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  33132. return { fragmentShader, vertexShader };
  33133. }
  33134. };
  33135. }
  33136. /**
  33137. * Initializes the renderer so it is ready for usage.
  33138. *
  33139. * @async
  33140. * @return {Promise} A Promise that resolves when the renderer has been initialized.
  33141. */
  33142. async init() {
  33143. if ( this._initialized ) {
  33144. throw new Error( 'Renderer: Backend has already been initialized.' );
  33145. }
  33146. if ( this._initPromise !== null ) {
  33147. return this._initPromise;
  33148. }
  33149. this._initPromise = new Promise( async ( resolve, reject ) => {
  33150. let backend = this.backend;
  33151. try {
  33152. await backend.init( this );
  33153. } catch ( error ) {
  33154. if ( this._getFallback !== null ) {
  33155. // try the fallback
  33156. try {
  33157. this.backend = backend = this._getFallback( error );
  33158. await backend.init( this );
  33159. } catch ( error ) {
  33160. reject( error );
  33161. return;
  33162. }
  33163. } else {
  33164. reject( error );
  33165. return;
  33166. }
  33167. }
  33168. this._nodes = new Nodes( this, backend );
  33169. this._animation = new Animation( this._nodes, this.info );
  33170. this._attributes = new Attributes( backend );
  33171. this._background = new Background( this, this._nodes );
  33172. this._geometries = new Geometries( this._attributes, this.info );
  33173. this._textures = new Textures( this, backend, this.info );
  33174. this._pipelines = new Pipelines( backend, this._nodes );
  33175. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  33176. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  33177. this._renderLists = new RenderLists( this.lighting );
  33178. this._bundles = new RenderBundles();
  33179. this._renderContexts = new RenderContexts();
  33180. //
  33181. this._animation.start();
  33182. this._initialized = true;
  33183. resolve();
  33184. } );
  33185. return this._initPromise;
  33186. }
  33187. /**
  33188. * The coordinate system of the renderer. The value of this property
  33189. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  33190. * `THREE.WebGPUCoordinateSystem`.
  33191. *
  33192. * @readonly
  33193. * @type {Number}
  33194. */
  33195. get coordinateSystem() {
  33196. return this.backend.coordinateSystem;
  33197. }
  33198. /**
  33199. * Compiles all materials in the given scene. This can be useful to avoid a
  33200. * phenomenon which is called "shader compilation stutter", which occurs when
  33201. * rendering an object with a new shader for the first time.
  33202. *
  33203. * If you want to add a 3D object to an existing scene, use the third optional
  33204. * parameter for applying the target scene. Note that the (target) scene's lighting
  33205. * and environment must be configured before calling this method.
  33206. *
  33207. * @async
  33208. * @param {Object3D} scene - The scene or 3D object to precompile.
  33209. * @param {Camera} camera - The camera that is used to render the scene.
  33210. * @param {Scene} targetScene - If the first argument is a 3D object, this parameter must represent the scene the 3D object is going to be added.
  33211. * @return {Promise} A Promise that resolves when the compile has been finished.
  33212. */
  33213. async compileAsync( scene, camera, targetScene = null ) {
  33214. if ( this._isDeviceLost === true ) return;
  33215. if ( this._initialized === false ) await this.init();
  33216. // preserve render tree
  33217. const nodeFrame = this._nodes.nodeFrame;
  33218. const previousRenderId = nodeFrame.renderId;
  33219. const previousRenderContext = this._currentRenderContext;
  33220. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  33221. const previousCompilationPromises = this._compilationPromises;
  33222. //
  33223. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  33224. if ( targetScene === null ) targetScene = scene;
  33225. const renderTarget = this._renderTarget;
  33226. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  33227. const activeMipmapLevel = this._activeMipmapLevel;
  33228. const compilationPromises = [];
  33229. this._currentRenderContext = renderContext;
  33230. this._currentRenderObjectFunction = this.renderObject;
  33231. this._handleObjectFunction = this._createObjectPipeline;
  33232. this._compilationPromises = compilationPromises;
  33233. nodeFrame.renderId ++;
  33234. //
  33235. nodeFrame.update();
  33236. //
  33237. renderContext.depth = this.depth;
  33238. renderContext.stencil = this.stencil;
  33239. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  33240. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  33241. //
  33242. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  33243. //
  33244. const renderList = this._renderLists.get( scene, camera );
  33245. renderList.begin();
  33246. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  33247. // include lights from target scene
  33248. if ( targetScene !== scene ) {
  33249. targetScene.traverseVisible( function ( object ) {
  33250. if ( object.isLight && object.layers.test( camera.layers ) ) {
  33251. renderList.pushLight( object );
  33252. }
  33253. } );
  33254. }
  33255. renderList.finish();
  33256. //
  33257. if ( renderTarget !== null ) {
  33258. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  33259. const renderTargetData = this._textures.get( renderTarget );
  33260. renderContext.textures = renderTargetData.textures;
  33261. renderContext.depthTexture = renderTargetData.depthTexture;
  33262. } else {
  33263. renderContext.textures = null;
  33264. renderContext.depthTexture = null;
  33265. }
  33266. //
  33267. this._background.update( sceneRef, renderList, renderContext );
  33268. // process render lists
  33269. const opaqueObjects = renderList.opaque;
  33270. const transparentObjects = renderList.transparent;
  33271. const transparentDoublePassObjects = renderList.transparentDoublePass;
  33272. const lightsNode = renderList.lightsNode;
  33273. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  33274. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  33275. // restore render tree
  33276. nodeFrame.renderId = previousRenderId;
  33277. this._currentRenderContext = previousRenderContext;
  33278. this._currentRenderObjectFunction = previousRenderObjectFunction;
  33279. this._compilationPromises = previousCompilationPromises;
  33280. this._handleObjectFunction = this._renderObjectDirect;
  33281. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  33282. await Promise.all( compilationPromises );
  33283. }
  33284. /**
  33285. * Renders the scene in an async fashion.
  33286. *
  33287. * @async
  33288. * @param {Object3D} scene - The scene or 3D object to render.
  33289. * @param {Camera} camera - The camera.
  33290. * @return {Promise} A Promise that resolves when the render has been finished.
  33291. */
  33292. async renderAsync( scene, camera ) {
  33293. if ( this._initialized === false ) await this.init();
  33294. const renderContext = this._renderScene( scene, camera );
  33295. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  33296. }
  33297. /**
  33298. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  33299. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  33300. *
  33301. * @async
  33302. * @return {Promise} A Promise that resolves when synchronization has been finished.
  33303. */
  33304. async waitForGPU() {
  33305. await this.backend.waitForGPU();
  33306. }
  33307. /**
  33308. * Sets the given MRT configuration.
  33309. *
  33310. * @param {MRTNode} mrt - The MRT node to set.
  33311. * @return {Renderer} A reference to this renderer.
  33312. */
  33313. setMRT( mrt ) {
  33314. this._mrt = mrt;
  33315. return this;
  33316. }
  33317. /**
  33318. * Returns the MRT configuration.
  33319. *
  33320. * @return {MRTNode} The MRT configuration.
  33321. */
  33322. getMRT() {
  33323. return this._mrt;
  33324. }
  33325. /**
  33326. * Default implementation of the device lost callback.
  33327. *
  33328. * @private
  33329. * @param {Object} info - Information about the context lost.
  33330. */
  33331. _onDeviceLost( info ) {
  33332. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  33333. if ( info.reason ) {
  33334. errorMessage += `\nReason: ${info.reason}`;
  33335. }
  33336. console.error( errorMessage );
  33337. this._isDeviceLost = true;
  33338. }
  33339. /**
  33340. * Renders the given render bundle.
  33341. *
  33342. * @private
  33343. * @param {Object} bundle - Render bundle data.
  33344. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  33345. * @param {LightsNode} lightsNode - The current lights node.
  33346. */
  33347. _renderBundle( bundle, sceneRef, lightsNode ) {
  33348. const { bundleGroup, camera, renderList } = bundle;
  33349. const renderContext = this._currentRenderContext;
  33350. //
  33351. const renderBundle = this._bundles.get( bundleGroup, camera );
  33352. const renderBundleData = this.backend.get( renderBundle );
  33353. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  33354. //
  33355. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  33356. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  33357. renderBundleData.renderContexts.add( renderContext );
  33358. if ( renderBundleNeedsUpdate ) {
  33359. this.backend.beginBundle( renderContext );
  33360. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  33361. renderBundleData.renderObjects = [];
  33362. }
  33363. this._currentRenderBundle = renderBundle;
  33364. const opaqueObjects = renderList.opaque;
  33365. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  33366. this._currentRenderBundle = null;
  33367. //
  33368. this.backend.finishBundle( renderContext, renderBundle );
  33369. renderBundleData.version = bundleGroup.version;
  33370. } else {
  33371. const { renderObjects } = renderBundleData;
  33372. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  33373. const renderObject = renderObjects[ i ];
  33374. if ( this._nodes.needsRefresh( renderObject ) ) {
  33375. this._nodes.updateBefore( renderObject );
  33376. this._nodes.updateForRender( renderObject );
  33377. this._bindings.updateForRender( renderObject );
  33378. this._nodes.updateAfter( renderObject );
  33379. }
  33380. }
  33381. }
  33382. this.backend.addBundle( renderContext, renderBundle );
  33383. }
  33384. /**
  33385. * Renders the scene or 3D object with the given camera. This method can only be called
  33386. * if the renderer has been initialized.
  33387. *
  33388. * The target of the method is the default framebuffer (meaning the canvas)
  33389. * or alternatively a render target when specified via `setRenderTarget()`.
  33390. *
  33391. * @param {Object3D} scene - The scene or 3D object to render.
  33392. * @param {Camera} camera - The camera to render the scene with.
  33393. * @return {Promise?} A Promise that resolve when the scene has been rendered.
  33394. * Only returned when the renderer has not been initialized.
  33395. */
  33396. render( scene, camera ) {
  33397. if ( this._initialized === false ) {
  33398. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  33399. return this.renderAsync( scene, camera );
  33400. }
  33401. this._renderScene( scene, camera );
  33402. }
  33403. /**
  33404. * Returns an internal render target which is used when computing the output tone mapping
  33405. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  33406. * pass and not inline to achieve more correct results.
  33407. *
  33408. * @private
  33409. * @return {RenderTarget?} The render target. The method returns `null` if no output conversion should be applied.
  33410. */
  33411. _getFrameBufferTarget() {
  33412. const { currentToneMapping, currentColorSpace } = this;
  33413. const useToneMapping = currentToneMapping !== NoToneMapping;
  33414. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  33415. if ( useToneMapping === false && useColorSpace === false ) return null;
  33416. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  33417. const { depth, stencil } = this;
  33418. let frameBufferTarget = this._frameBufferTarget;
  33419. if ( frameBufferTarget === null ) {
  33420. frameBufferTarget = new RenderTarget( width, height, {
  33421. depthBuffer: depth,
  33422. stencilBuffer: stencil,
  33423. type: HalfFloatType, // FloatType
  33424. format: RGBAFormat,
  33425. colorSpace: LinearSRGBColorSpace,
  33426. generateMipmaps: false,
  33427. minFilter: LinearFilter,
  33428. magFilter: LinearFilter,
  33429. samples: this.samples
  33430. } );
  33431. frameBufferTarget.isPostProcessingRenderTarget = true;
  33432. this._frameBufferTarget = frameBufferTarget;
  33433. }
  33434. frameBufferTarget.depthBuffer = depth;
  33435. frameBufferTarget.stencilBuffer = stencil;
  33436. frameBufferTarget.setSize( width, height );
  33437. frameBufferTarget.viewport.copy( this._viewport );
  33438. frameBufferTarget.scissor.copy( this._scissor );
  33439. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  33440. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  33441. frameBufferTarget.scissorTest = this._scissorTest;
  33442. return frameBufferTarget;
  33443. }
  33444. /**
  33445. * Renders the scene or 3D object with the given camera.
  33446. *
  33447. * @private
  33448. * @param {Object3D} scene - The scene or 3D object to render.
  33449. * @param {Camera} camera - The camera to render the scene with.
  33450. * @param {Boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  33451. * @return {RenderContext} The current render context.
  33452. */
  33453. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  33454. if ( this._isDeviceLost === true ) return;
  33455. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  33456. // preserve render tree
  33457. const nodeFrame = this._nodes.nodeFrame;
  33458. const previousRenderId = nodeFrame.renderId;
  33459. const previousRenderContext = this._currentRenderContext;
  33460. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  33461. //
  33462. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  33463. const outputRenderTarget = this._renderTarget;
  33464. const activeCubeFace = this._activeCubeFace;
  33465. const activeMipmapLevel = this._activeMipmapLevel;
  33466. //
  33467. let renderTarget;
  33468. if ( frameBufferTarget !== null ) {
  33469. renderTarget = frameBufferTarget;
  33470. this.setRenderTarget( renderTarget );
  33471. } else {
  33472. renderTarget = outputRenderTarget;
  33473. }
  33474. //
  33475. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  33476. this._currentRenderContext = renderContext;
  33477. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  33478. //
  33479. this.info.calls ++;
  33480. this.info.render.calls ++;
  33481. this.info.render.frameCalls ++;
  33482. nodeFrame.renderId = this.info.calls;
  33483. //
  33484. const coordinateSystem = this.coordinateSystem;
  33485. if ( camera.coordinateSystem !== coordinateSystem ) {
  33486. camera.coordinateSystem = coordinateSystem;
  33487. camera.updateProjectionMatrix();
  33488. }
  33489. //
  33490. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  33491. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  33492. //
  33493. let viewport = this._viewport;
  33494. let scissor = this._scissor;
  33495. let pixelRatio = this._pixelRatio;
  33496. if ( renderTarget !== null ) {
  33497. viewport = renderTarget.viewport;
  33498. scissor = renderTarget.scissor;
  33499. pixelRatio = 1;
  33500. }
  33501. this.getDrawingBufferSize( _drawingBufferSize );
  33502. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  33503. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  33504. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  33505. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  33506. renderContext.viewportValue.width >>= activeMipmapLevel;
  33507. renderContext.viewportValue.height >>= activeMipmapLevel;
  33508. renderContext.viewportValue.minDepth = minDepth;
  33509. renderContext.viewportValue.maxDepth = maxDepth;
  33510. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  33511. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  33512. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  33513. renderContext.scissorValue.width >>= activeMipmapLevel;
  33514. renderContext.scissorValue.height >>= activeMipmapLevel;
  33515. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  33516. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  33517. //
  33518. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  33519. //
  33520. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  33521. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  33522. const renderList = this._renderLists.get( scene, camera );
  33523. renderList.begin();
  33524. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  33525. renderList.finish();
  33526. if ( this.sortObjects === true ) {
  33527. renderList.sort( this._opaqueSort, this._transparentSort );
  33528. }
  33529. //
  33530. if ( renderTarget !== null ) {
  33531. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  33532. const renderTargetData = this._textures.get( renderTarget );
  33533. renderContext.textures = renderTargetData.textures;
  33534. renderContext.depthTexture = renderTargetData.depthTexture;
  33535. renderContext.width = renderTargetData.width;
  33536. renderContext.height = renderTargetData.height;
  33537. renderContext.renderTarget = renderTarget;
  33538. renderContext.depth = renderTarget.depthBuffer;
  33539. renderContext.stencil = renderTarget.stencilBuffer;
  33540. } else {
  33541. renderContext.textures = null;
  33542. renderContext.depthTexture = null;
  33543. renderContext.width = this.domElement.width;
  33544. renderContext.height = this.domElement.height;
  33545. renderContext.depth = this.depth;
  33546. renderContext.stencil = this.stencil;
  33547. }
  33548. renderContext.width >>= activeMipmapLevel;
  33549. renderContext.height >>= activeMipmapLevel;
  33550. renderContext.activeCubeFace = activeCubeFace;
  33551. renderContext.activeMipmapLevel = activeMipmapLevel;
  33552. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  33553. //
  33554. this._background.update( sceneRef, renderList, renderContext );
  33555. //
  33556. this.backend.beginRender( renderContext );
  33557. // process render lists
  33558. const {
  33559. bundles,
  33560. lightsNode,
  33561. transparentDoublePass: transparentDoublePassObjects,
  33562. transparent: transparentObjects,
  33563. opaque: opaqueObjects
  33564. } = renderList;
  33565. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  33566. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  33567. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  33568. // finish render pass
  33569. this.backend.finishRender( renderContext );
  33570. // restore render tree
  33571. nodeFrame.renderId = previousRenderId;
  33572. this._currentRenderContext = previousRenderContext;
  33573. this._currentRenderObjectFunction = previousRenderObjectFunction;
  33574. //
  33575. if ( frameBufferTarget !== null ) {
  33576. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  33577. const quad = this._quad;
  33578. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  33579. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  33580. quad.material.needsUpdate = true;
  33581. }
  33582. this._renderScene( quad, quad.camera, false );
  33583. }
  33584. //
  33585. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  33586. //
  33587. return renderContext;
  33588. }
  33589. /**
  33590. * Returns the maximum available anisotropy for texture filtering.
  33591. *
  33592. * @return {Number} The maximum available anisotropy.
  33593. */
  33594. getMaxAnisotropy() {
  33595. return this.backend.getMaxAnisotropy();
  33596. }
  33597. /**
  33598. * Returns the active cube face.
  33599. *
  33600. * @return {Number} The active cube face.
  33601. */
  33602. getActiveCubeFace() {
  33603. return this._activeCubeFace;
  33604. }
  33605. /**
  33606. * Returns the active mipmap level.
  33607. *
  33608. * @return {Number} The active mipmap level.
  33609. */
  33610. getActiveMipmapLevel() {
  33611. return this._activeMipmapLevel;
  33612. }
  33613. /**
  33614. * Applications are advised to always define the animation loop
  33615. * with this method and not manually with `requestAnimationFrame()`
  33616. * for best compatibility.
  33617. *
  33618. * @async
  33619. * @param {Function} callback - The application's animation loop.
  33620. * @return {Promise} A Promise that resolves when the set has been exeucted.
  33621. */
  33622. async setAnimationLoop( callback ) {
  33623. if ( this._initialized === false ) await this.init();
  33624. this._animation.setAnimationLoop( callback );
  33625. }
  33626. /**
  33627. * Can be used to transfer buffer data from a storage buffer attribute
  33628. * from the GPU to the CPU in context of compute shaders.
  33629. *
  33630. * @async
  33631. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  33632. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  33633. */
  33634. async getArrayBufferAsync( attribute ) {
  33635. return await this.backend.getArrayBufferAsync( attribute );
  33636. }
  33637. /**
  33638. * Returns the rendering context.
  33639. *
  33640. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  33641. */
  33642. getContext() {
  33643. return this.backend.getContext();
  33644. }
  33645. /**
  33646. * Returns the pixel ratio.
  33647. *
  33648. * @return {Number} The pixel ratio.
  33649. */
  33650. getPixelRatio() {
  33651. return this._pixelRatio;
  33652. }
  33653. /**
  33654. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  33655. *
  33656. * @param {Vector2} target - The method writes the result in this target object.
  33657. * @return {Vector2} The drawing buffer size.
  33658. */
  33659. getDrawingBufferSize( target ) {
  33660. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  33661. }
  33662. /**
  33663. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  33664. *
  33665. * @param {Vector2} target - The method writes the result in this target object.
  33666. * @return {Vector2} The drawing buffer size.
  33667. */
  33668. getSize( target ) {
  33669. return target.set( this._width, this._height );
  33670. }
  33671. /**
  33672. * Sets the given pixel ration and resizes the canvas if necessary.
  33673. *
  33674. * @param {Number} [value=1] - The pixel ratio.
  33675. */
  33676. setPixelRatio( value = 1 ) {
  33677. if ( this._pixelRatio === value ) return;
  33678. this._pixelRatio = value;
  33679. this.setSize( this._width, this._height, false );
  33680. }
  33681. /**
  33682. * This method allows to define the drawing buffer size by specifying
  33683. * width, height and pixel ratio all at once. The size of the drawing
  33684. * buffer is computed with this formula:
  33685. * ````
  33686. * size.x = width * pixelRatio;
  33687. * size.y = height * pixelRatio;
  33688. *```
  33689. *
  33690. * @param {Number} width - The width in logical pixels.
  33691. * @param {Number} height - The height in logical pixels.
  33692. * @param {Number} pixelRatio - The pixel ratio.
  33693. */
  33694. setDrawingBufferSize( width, height, pixelRatio ) {
  33695. this._width = width;
  33696. this._height = height;
  33697. this._pixelRatio = pixelRatio;
  33698. this.domElement.width = Math.floor( width * pixelRatio );
  33699. this.domElement.height = Math.floor( height * pixelRatio );
  33700. this.setViewport( 0, 0, width, height );
  33701. if ( this._initialized ) this.backend.updateSize();
  33702. }
  33703. /**
  33704. * Sets the size of the renderer.
  33705. *
  33706. * @param {Number} width - The width in logical pixels.
  33707. * @param {Number} height - The height in logical pixels.
  33708. * @param {Boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  33709. */
  33710. setSize( width, height, updateStyle = true ) {
  33711. this._width = width;
  33712. this._height = height;
  33713. this.domElement.width = Math.floor( width * this._pixelRatio );
  33714. this.domElement.height = Math.floor( height * this._pixelRatio );
  33715. if ( updateStyle === true ) {
  33716. this.domElement.style.width = width + 'px';
  33717. this.domElement.style.height = height + 'px';
  33718. }
  33719. this.setViewport( 0, 0, width, height );
  33720. if ( this._initialized ) this.backend.updateSize();
  33721. }
  33722. /**
  33723. * Defines a manual sort function for the opaque render list.
  33724. * Pass `null` to use the default sort.
  33725. *
  33726. * @param {Function} method - The sort function.
  33727. */
  33728. setOpaqueSort( method ) {
  33729. this._opaqueSort = method;
  33730. }
  33731. /**
  33732. * Defines a manual sort function for the transparent render list.
  33733. * Pass `null` to use the default sort.
  33734. *
  33735. * @param {Function} method - The sort function.
  33736. */
  33737. setTransparentSort( method ) {
  33738. this._transparentSort = method;
  33739. }
  33740. /**
  33741. * Returns the scissor rectangle.
  33742. *
  33743. * @param {Vector4} target - The method writes the result in this target object.
  33744. * @return {Vector4} The scissor rectangle.
  33745. */
  33746. getScissor( target ) {
  33747. const scissor = this._scissor;
  33748. target.x = scissor.x;
  33749. target.y = scissor.y;
  33750. target.width = scissor.width;
  33751. target.height = scissor.height;
  33752. return target;
  33753. }
  33754. /**
  33755. * Defines the scissor rectangle.
  33756. *
  33757. * @param {Number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  33758. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  33759. * @param {Number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  33760. * @param {Number} width - The width of the scissor box in logical pixel unit.
  33761. * @param {Number} height - The height of the scissor box in logical pixel unit.
  33762. */
  33763. setScissor( x, y, width, height ) {
  33764. const scissor = this._scissor;
  33765. if ( x.isVector4 ) {
  33766. scissor.copy( x );
  33767. } else {
  33768. scissor.set( x, y, width, height );
  33769. }
  33770. }
  33771. /**
  33772. * Returns the scissor test value.
  33773. *
  33774. * @return {Boolean} Whether the scissor test should be enabled or not.
  33775. */
  33776. getScissorTest() {
  33777. return this._scissorTest;
  33778. }
  33779. /**
  33780. * Defines the scissor test.
  33781. *
  33782. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  33783. */
  33784. setScissorTest( boolean ) {
  33785. this._scissorTest = boolean;
  33786. this.backend.setScissorTest( boolean );
  33787. }
  33788. /**
  33789. * Returns the viewport definition.
  33790. *
  33791. * @param {Vector4} target - The method writes the result in this target object.
  33792. * @return {Vector4} The viewport definition.
  33793. */
  33794. getViewport( target ) {
  33795. return target.copy( this._viewport );
  33796. }
  33797. /**
  33798. * Defines the viewport.
  33799. *
  33800. * @param {Number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  33801. * @param {Number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  33802. * @param {Number} width - The width of the viewport in logical pixel unit.
  33803. * @param {Number} height - The height of the viewport in logical pixel unit.
  33804. * @param {Number} minDepth - The minimum depth value of the viewport. WebGPU only.
  33805. * @param {Number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  33806. */
  33807. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  33808. const viewport = this._viewport;
  33809. if ( x.isVector4 ) {
  33810. viewport.copy( x );
  33811. } else {
  33812. viewport.set( x, y, width, height );
  33813. }
  33814. viewport.minDepth = minDepth;
  33815. viewport.maxDepth = maxDepth;
  33816. }
  33817. /**
  33818. * Returns the clear color.
  33819. *
  33820. * @param {Color} target - The method writes the result in this target object.
  33821. * @return {Color} The clear color.
  33822. */
  33823. getClearColor( target ) {
  33824. return target.copy( this._clearColor );
  33825. }
  33826. /**
  33827. * Defines the clear color and optionally the clear alpha.
  33828. *
  33829. * @param {Color} color - The clear color.
  33830. * @param {Number} [alpha=1] - The clear alpha.
  33831. */
  33832. setClearColor( color, alpha = 1 ) {
  33833. this._clearColor.set( color );
  33834. this._clearColor.a = alpha;
  33835. }
  33836. /**
  33837. * Returns the clear alpha.
  33838. *
  33839. * @return {Number} The clear alpha.
  33840. */
  33841. getClearAlpha() {
  33842. return this._clearColor.a;
  33843. }
  33844. /**
  33845. * Defines the clear alpha.
  33846. *
  33847. * @param {Number} alpha - The clear alpha.
  33848. */
  33849. setClearAlpha( alpha ) {
  33850. this._clearColor.a = alpha;
  33851. }
  33852. /**
  33853. * Returns the clear depth.
  33854. *
  33855. * @return {Number} The clear depth.
  33856. */
  33857. getClearDepth() {
  33858. return this._clearDepth;
  33859. }
  33860. /**
  33861. * Defines the clear depth.
  33862. *
  33863. * @param {Number} depth - The clear depth.
  33864. */
  33865. setClearDepth( depth ) {
  33866. this._clearDepth = depth;
  33867. }
  33868. /**
  33869. * Returns the clear stencil.
  33870. *
  33871. * @return {Number} The clear stencil.
  33872. */
  33873. getClearStencil() {
  33874. return this._clearStencil;
  33875. }
  33876. /**
  33877. * Defines the clear stencil.
  33878. *
  33879. * @param {Number} stencil - The clear stencil.
  33880. */
  33881. setClearStencil( stencil ) {
  33882. this._clearStencil = stencil;
  33883. }
  33884. /**
  33885. * This method performs an occlusion query for the given 3D object.
  33886. * It returns `true` if the given 3D object is fully occluded by other
  33887. * 3D objects in the scene.
  33888. *
  33889. * @param {Object3D} object - The 3D object to test.
  33890. * @return {Boolean} Whether the 3D object is fully occluded or not.
  33891. */
  33892. isOccluded( object ) {
  33893. const renderContext = this._currentRenderContext;
  33894. return renderContext && this.backend.isOccluded( renderContext, object );
  33895. }
  33896. /**
  33897. * Performs a manual clear operation. This method ignores `autoClear` properties.
  33898. *
  33899. * @param {Boolean} [color=true] - Whether the color buffer should be cleared or not.
  33900. * @param {Boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  33901. * @param {Boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  33902. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  33903. * Only returned when the renderer has not been initialized.
  33904. */
  33905. clear( color = true, depth = true, stencil = true ) {
  33906. if ( this._initialized === false ) {
  33907. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  33908. return this.clearAsync( color, depth, stencil );
  33909. }
  33910. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  33911. let renderContext = null;
  33912. if ( renderTarget !== null ) {
  33913. this._textures.updateRenderTarget( renderTarget );
  33914. const renderTargetData = this._textures.get( renderTarget );
  33915. renderContext = this._renderContexts.get( null, null, renderTarget );
  33916. renderContext.textures = renderTargetData.textures;
  33917. renderContext.depthTexture = renderTargetData.depthTexture;
  33918. renderContext.width = renderTargetData.width;
  33919. renderContext.height = renderTargetData.height;
  33920. renderContext.renderTarget = renderTarget;
  33921. renderContext.depth = renderTarget.depthBuffer;
  33922. renderContext.stencil = renderTarget.stencilBuffer;
  33923. }
  33924. this.backend.clear( color, depth, stencil, renderContext );
  33925. if ( renderTarget !== null && this._renderTarget === null ) {
  33926. // If a color space transform or tone mapping is required,
  33927. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  33928. const quad = this._quad;
  33929. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  33930. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  33931. quad.material.needsUpdate = true;
  33932. }
  33933. this._renderScene( quad, quad.camera, false );
  33934. }
  33935. }
  33936. /**
  33937. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  33938. *
  33939. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  33940. * Only returned when the renderer has not been initialized.
  33941. */
  33942. clearColor() {
  33943. return this.clear( true, false, false );
  33944. }
  33945. /**
  33946. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  33947. *
  33948. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  33949. * Only returned when the renderer has not been initialized.
  33950. */
  33951. clearDepth() {
  33952. return this.clear( false, true, false );
  33953. }
  33954. /**
  33955. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  33956. *
  33957. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  33958. * Only returned when the renderer has not been initialized.
  33959. */
  33960. clearStencil() {
  33961. return this.clear( false, false, true );
  33962. }
  33963. /**
  33964. * Async version of {@link module:Renderer~Renderer#clear}.
  33965. *
  33966. * @async
  33967. * @param {Boolean} [color=true] - Whether the color buffer should be cleared or not.
  33968. * @param {Boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  33969. * @param {Boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  33970. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  33971. */
  33972. async clearAsync( color = true, depth = true, stencil = true ) {
  33973. if ( this._initialized === false ) await this.init();
  33974. this.clear( color, depth, stencil );
  33975. }
  33976. /**
  33977. * Async version of {@link module:Renderer~Renderer#clearColor}.
  33978. *
  33979. * @async
  33980. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  33981. */
  33982. async clearColorAsync() {
  33983. this.clearAsync( true, false, false );
  33984. }
  33985. /**
  33986. * Async version of {@link module:Renderer~Renderer#clearDepth}.
  33987. *
  33988. * @async
  33989. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  33990. */
  33991. async clearDepthAsync() {
  33992. this.clearAsync( false, true, false );
  33993. }
  33994. /**
  33995. * Async version of {@link module:Renderer~Renderer#clearStencil}.
  33996. *
  33997. * @async
  33998. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  33999. */
  34000. async clearStencilAsync() {
  34001. this.clearAsync( false, false, true );
  34002. }
  34003. /**
  34004. * The current output tone mapping of the renderer. When a render target is set,
  34005. * the output tone mapping is always `NoToneMapping`.
  34006. *
  34007. * @type {Number}
  34008. */
  34009. get currentToneMapping() {
  34010. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  34011. }
  34012. /**
  34013. * The current output color space of the renderer. When a render target is set,
  34014. * the output color space is always `LinearSRGBColorSpace`.
  34015. *
  34016. * @type {String}
  34017. */
  34018. get currentColorSpace() {
  34019. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  34020. }
  34021. /**
  34022. * Frees all internal resources of the renderer. Call this method if the renderer
  34023. * is no longer in use by your app.
  34024. */
  34025. dispose() {
  34026. this.info.dispose();
  34027. this.backend.dispose();
  34028. this._animation.dispose();
  34029. this._objects.dispose();
  34030. this._pipelines.dispose();
  34031. this._nodes.dispose();
  34032. this._bindings.dispose();
  34033. this._renderLists.dispose();
  34034. this._renderContexts.dispose();
  34035. this._textures.dispose();
  34036. this.setRenderTarget( null );
  34037. this.setAnimationLoop( null );
  34038. }
  34039. /**
  34040. * Sets the given render target. Calling this method means the renderer does not
  34041. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  34042. * Use `null` as the first argument to reset the state.
  34043. *
  34044. * @param {RenderTarget?} renderTarget - The render target to set.
  34045. * @param {Number} [activeCubeFace=0] - The active cube face.
  34046. * @param {Number} [activeMipmapLevel=0] - The active mipmap level.
  34047. */
  34048. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  34049. this._renderTarget = renderTarget;
  34050. this._activeCubeFace = activeCubeFace;
  34051. this._activeMipmapLevel = activeMipmapLevel;
  34052. }
  34053. /**
  34054. * Returns the current render target.
  34055. *
  34056. * @return {RenderTarget?} The render target. Returns `null` if no render target is set.
  34057. */
  34058. getRenderTarget() {
  34059. return this._renderTarget;
  34060. }
  34061. /**
  34062. * Callback for {@link module:Renderer~Renderer#setRenderObjectFunction}.
  34063. *
  34064. * @callback renderObjectFunction
  34065. * @param {Object3D} object - The 3D object.
  34066. * @param {Scene} scene - The scene the 3D object belongs to.
  34067. * @param {Camera} camera - The camera the object should be rendered with.
  34068. * @param {BufferGeometry} geometry - The object's geometry.
  34069. * @param {Material} material - The object's material.
  34070. * @param {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  34071. * @param {LightsNode} lightsNode - The current lights node.
  34072. * @param {ClippingContext} clippingContext - The clipping context.
  34073. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  34074. */
  34075. /**
  34076. * Sets the given render object function. Calling this method overwrites the default implementation
  34077. * which is {@link module:Renderer~Renderer#renderObject}. Defining a custom function can be useful
  34078. * if you want to modify the way objects are rendered. For example you can define things like "every
  34079. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  34080. * The custom function must always call `renderObject()` in its implementation.
  34081. *
  34082. * Use `null` as the first argument to reset the state.
  34083. *
  34084. * @param {module:Renderer~renderObjectFunction?} renderObjectFunction - The render object function.
  34085. */
  34086. setRenderObjectFunction( renderObjectFunction ) {
  34087. this._renderObjectFunction = renderObjectFunction;
  34088. }
  34089. /**
  34090. * Returns the current render object function.
  34091. *
  34092. * @return {Function?} The current render object function. Returns `null` if no function is set.
  34093. */
  34094. getRenderObjectFunction() {
  34095. return this._renderObjectFunction;
  34096. }
  34097. /**
  34098. * Execute a single or an array of compute nodes. This method can only be called
  34099. * if the renderer has been initialized.
  34100. *
  34101. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  34102. * @return {Promise?} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  34103. */
  34104. compute( computeNodes ) {
  34105. if ( this.isDeviceLost === true ) return;
  34106. if ( this._initialized === false ) {
  34107. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  34108. return this.computeAsync( computeNodes );
  34109. }
  34110. //
  34111. const nodeFrame = this._nodes.nodeFrame;
  34112. const previousRenderId = nodeFrame.renderId;
  34113. //
  34114. this.info.calls ++;
  34115. this.info.compute.calls ++;
  34116. this.info.compute.frameCalls ++;
  34117. nodeFrame.renderId = this.info.calls;
  34118. //
  34119. const backend = this.backend;
  34120. const pipelines = this._pipelines;
  34121. const bindings = this._bindings;
  34122. const nodes = this._nodes;
  34123. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  34124. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  34125. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  34126. }
  34127. backend.beginCompute( computeNodes );
  34128. for ( const computeNode of computeList ) {
  34129. // onInit
  34130. if ( pipelines.has( computeNode ) === false ) {
  34131. const dispose = () => {
  34132. computeNode.removeEventListener( 'dispose', dispose );
  34133. pipelines.delete( computeNode );
  34134. bindings.delete( computeNode );
  34135. nodes.delete( computeNode );
  34136. };
  34137. computeNode.addEventListener( 'dispose', dispose );
  34138. //
  34139. const onInitFn = computeNode.onInitFunction;
  34140. if ( onInitFn !== null ) {
  34141. onInitFn.call( computeNode, { renderer: this } );
  34142. }
  34143. }
  34144. nodes.updateForCompute( computeNode );
  34145. bindings.updateForCompute( computeNode );
  34146. const computeBindings = bindings.getForCompute( computeNode );
  34147. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  34148. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  34149. }
  34150. backend.finishCompute( computeNodes );
  34151. //
  34152. nodeFrame.renderId = previousRenderId;
  34153. }
  34154. /**
  34155. * Execute a single or an array of compute nodes.
  34156. *
  34157. * @async
  34158. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  34159. * @return {Promise?} A Promise that resolve when the compute has finished.
  34160. */
  34161. async computeAsync( computeNodes ) {
  34162. if ( this._initialized === false ) await this.init();
  34163. this.compute( computeNodes );
  34164. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  34165. }
  34166. /**
  34167. * Checks if the given feature is supported by the selected backend.
  34168. *
  34169. * @async
  34170. * @param {String} name - The feature's name.
  34171. * @return {Promise<Boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  34172. */
  34173. async hasFeatureAsync( name ) {
  34174. if ( this._initialized === false ) await this.init();
  34175. return this.backend.hasFeature( name );
  34176. }
  34177. /**
  34178. * Checks if the given feature is supported by the selected backend. If the
  34179. * renderer has not been initialized, this method always returns `false`.
  34180. *
  34181. * @param {String} name - The feature's name.
  34182. * @return {Boolean} Whether the feature is supported or not.
  34183. */
  34184. hasFeature( name ) {
  34185. if ( this._initialized === false ) {
  34186. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  34187. return false;
  34188. }
  34189. return this.backend.hasFeature( name );
  34190. }
  34191. /**
  34192. * Returns `true` when the renderer has been initialized.
  34193. *
  34194. * @return {Boolean} Whether the renderer has been initialized or not.
  34195. */
  34196. hasInitialized() {
  34197. return this._initialized;
  34198. }
  34199. /**
  34200. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  34201. * (which can cause noticeable lags due to decode and GPU upload overhead).
  34202. *
  34203. * @async
  34204. * @param {Texture} texture - The texture.
  34205. * @return {Promise} A Promise that resolves when the texture has been initialized.
  34206. */
  34207. async initTextureAsync( texture ) {
  34208. if ( this._initialized === false ) await this.init();
  34209. this._textures.updateTexture( texture );
  34210. }
  34211. /**
  34212. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  34213. * (which can cause noticeable lags due to decode and GPU upload overhead).
  34214. *
  34215. * This method can only be used if the renderer has been initialized.
  34216. *
  34217. * @param {Texture} texture - The texture.
  34218. */
  34219. initTexture( texture ) {
  34220. if ( this._initialized === false ) {
  34221. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  34222. }
  34223. this._textures.updateTexture( texture );
  34224. }
  34225. /**
  34226. * Copies the current bound framebuffer into the given texture.
  34227. *
  34228. * @param {FramebufferTexture} framebufferTexture - The texture.
  34229. * @param {Vector2|Vector4} rectangle - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  34230. */
  34231. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  34232. if ( rectangle !== null ) {
  34233. if ( rectangle.isVector2 ) {
  34234. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  34235. } else if ( rectangle.isVector4 ) {
  34236. rectangle = _vector4.copy( rectangle ).floor();
  34237. } else {
  34238. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  34239. return;
  34240. }
  34241. } else {
  34242. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  34243. }
  34244. //
  34245. let renderContext = this._currentRenderContext;
  34246. let renderTarget;
  34247. if ( renderContext !== null ) {
  34248. renderTarget = renderContext.renderTarget;
  34249. } else {
  34250. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  34251. if ( renderTarget !== null ) {
  34252. this._textures.updateRenderTarget( renderTarget );
  34253. renderContext = this._textures.get( renderTarget );
  34254. }
  34255. }
  34256. //
  34257. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  34258. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  34259. }
  34260. /**
  34261. * Copies data of source texture into a destination texture.
  34262. *
  34263. * @param {Texture} srcTexture - The source texture.
  34264. * @param {Texture} dstTexture - The destination texture.
  34265. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  34266. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  34267. * @param {Number} level - The mipmap level to copy.
  34268. */
  34269. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  34270. this._textures.updateTexture( srcTexture );
  34271. this._textures.updateTexture( dstTexture );
  34272. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  34273. }
  34274. /**
  34275. * Reads pixel data from the given render target.
  34276. *
  34277. * @async
  34278. * @param {RenderTarget} renderTarget - The render target to read from.
  34279. * @param {Number} x - The `x` coordinate of the copy region's origin.
  34280. * @param {Number} y - The `y` coordinate of the copy region's origin.
  34281. * @param {Number} width - The width of the copy region.
  34282. * @param {Number} height - The height of the copy region.
  34283. * @param {Number} [textureIndex=0] - The texture index of a MRT render target.
  34284. * @param {Number} [faceIndex=0] - The active cube face index.
  34285. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  34286. */
  34287. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  34288. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  34289. }
  34290. /**
  34291. * Analyzes the given 3D object's hierarchy and builds render lists from the
  34292. * processed hierarchy.
  34293. *
  34294. * @param {Object3D} object - The 3D object to process (usually a scene).
  34295. * @param {Camera} camera - The camera the object is rendered with.
  34296. * @param {Number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  34297. * @param {RenderList} renderList - The current render list.
  34298. * @param {ClippingContext} clippingContext - The current clipping context.
  34299. */
  34300. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  34301. if ( object.visible === false ) return;
  34302. const visible = object.layers.test( camera.layers );
  34303. if ( visible ) {
  34304. if ( object.isGroup ) {
  34305. groupOrder = object.renderOrder;
  34306. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  34307. } else if ( object.isLOD ) {
  34308. if ( object.autoUpdate === true ) object.update( camera );
  34309. } else if ( object.isLight ) {
  34310. renderList.pushLight( object );
  34311. } else if ( object.isSprite ) {
  34312. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  34313. if ( this.sortObjects === true ) {
  34314. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  34315. }
  34316. const { geometry, material } = object;
  34317. if ( material.visible ) {
  34318. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  34319. }
  34320. }
  34321. } else if ( object.isLineLoop ) {
  34322. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  34323. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  34324. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  34325. const { geometry, material } = object;
  34326. if ( this.sortObjects === true ) {
  34327. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  34328. _vector4
  34329. .copy( geometry.boundingSphere.center )
  34330. .applyMatrix4( object.matrixWorld )
  34331. .applyMatrix4( _projScreenMatrix );
  34332. }
  34333. if ( Array.isArray( material ) ) {
  34334. const groups = geometry.groups;
  34335. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  34336. const group = groups[ i ];
  34337. const groupMaterial = material[ group.materialIndex ];
  34338. if ( groupMaterial && groupMaterial.visible ) {
  34339. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  34340. }
  34341. }
  34342. } else if ( material.visible ) {
  34343. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  34344. }
  34345. }
  34346. }
  34347. }
  34348. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  34349. const baseRenderList = renderList;
  34350. // replace render list
  34351. renderList = this._renderLists.get( object, camera );
  34352. renderList.begin();
  34353. baseRenderList.pushBundle( {
  34354. bundleGroup: object,
  34355. camera,
  34356. renderList,
  34357. } );
  34358. renderList.finish();
  34359. }
  34360. const children = object.children;
  34361. for ( let i = 0, l = children.length; i < l; i ++ ) {
  34362. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  34363. }
  34364. }
  34365. /**
  34366. * Renders the given render bundles.
  34367. *
  34368. * @private
  34369. * @param {Array<Object>} bundles - Array with render bundle data.
  34370. * @param {Scene} sceneRef - The scene the render bundles belong to.
  34371. * @param {LightsNode} lightsNode - The current lights node.
  34372. */
  34373. _renderBundles( bundles, sceneRef, lightsNode ) {
  34374. for ( const bundle of bundles ) {
  34375. this._renderBundle( bundle, sceneRef, lightsNode );
  34376. }
  34377. }
  34378. /**
  34379. * Renders the transparent objects from the given render lists.
  34380. *
  34381. * @private
  34382. * @param {Array<Object>} renderList - The transparent render list.
  34383. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  34384. * @param {Camera} camera - The camera the render list should be rendered with.
  34385. * @param {Scene} scene - The scene the render list belongs to.
  34386. * @param {LightsNode} lightsNode - The current lights node.
  34387. */
  34388. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  34389. if ( doublePassList.length > 0 ) {
  34390. // render back side
  34391. for ( const { material } of doublePassList ) {
  34392. material.side = BackSide;
  34393. }
  34394. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  34395. // render front side
  34396. for ( const { material } of doublePassList ) {
  34397. material.side = FrontSide;
  34398. }
  34399. this._renderObjects( renderList, camera, scene, lightsNode );
  34400. // restore
  34401. for ( const { material } of doublePassList ) {
  34402. material.side = DoubleSide;
  34403. }
  34404. } else {
  34405. this._renderObjects( renderList, camera, scene, lightsNode );
  34406. }
  34407. }
  34408. /**
  34409. * Renders the objects from the given render list.
  34410. *
  34411. * @private
  34412. * @param {Array<Object>} renderList - The render list.
  34413. * @param {Camera} camera - The camera the render list should be rendered with.
  34414. * @param {Scene} scene - The scene the render list belongs to.
  34415. * @param {LightsNode} lightsNode - The current lights node.
  34416. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  34417. */
  34418. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  34419. // process renderable objects
  34420. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  34421. const renderItem = renderList[ i ];
  34422. // @TODO: Add support for multiple materials per object. This will require to extract
  34423. // the material from the renderItem object and pass it with its group data to renderObject().
  34424. const { object, geometry, material, group, clippingContext } = renderItem;
  34425. if ( camera.isArrayCamera ) {
  34426. const cameras = camera.cameras;
  34427. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  34428. const camera2 = cameras[ j ];
  34429. if ( object.layers.test( camera2.layers ) ) {
  34430. const vp = camera2.viewport;
  34431. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  34432. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  34433. const viewportValue = this._currentRenderContext.viewportValue;
  34434. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  34435. viewportValue.minDepth = minDepth;
  34436. viewportValue.maxDepth = maxDepth;
  34437. this.backend.updateViewport( this._currentRenderContext );
  34438. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode, clippingContext, passId );
  34439. }
  34440. }
  34441. } else {
  34442. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  34443. }
  34444. }
  34445. }
  34446. /**
  34447. * This method represents the default render object function that manages the render lifecycle
  34448. * of the object.
  34449. *
  34450. * @param {Object3D} object - The 3D object.
  34451. * @param {Scene} scene - The scene the 3D object belongs to.
  34452. * @param {Camera} camera - The camera the object should be rendered with.
  34453. * @param {BufferGeometry} geometry - The object's geometry.
  34454. * @param {Material} material - The object's material.
  34455. * @param {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  34456. * @param {LightsNode} lightsNode - The current lights node.
  34457. * @param {ClippingContext} clippingContext - The clipping context.
  34458. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  34459. */
  34460. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  34461. let overridePositionNode;
  34462. let overrideColorNode;
  34463. let overrideDepthNode;
  34464. //
  34465. object.onBeforeRender( this, scene, camera, geometry, material, group );
  34466. //
  34467. if ( scene.overrideMaterial !== null ) {
  34468. const overrideMaterial = scene.overrideMaterial;
  34469. if ( material.positionNode && material.positionNode.isNode ) {
  34470. overridePositionNode = overrideMaterial.positionNode;
  34471. overrideMaterial.positionNode = material.positionNode;
  34472. }
  34473. overrideMaterial.alphaTest = material.alphaTest;
  34474. overrideMaterial.alphaMap = material.alphaMap;
  34475. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  34476. if ( overrideMaterial.isShadowNodeMaterial ) {
  34477. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  34478. if ( material.depthNode && material.depthNode.isNode ) {
  34479. overrideDepthNode = overrideMaterial.depthNode;
  34480. overrideMaterial.depthNode = material.depthNode;
  34481. }
  34482. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  34483. overrideColorNode = overrideMaterial.colorNode;
  34484. overrideMaterial.colorNode = material.castShadowNode;
  34485. }
  34486. }
  34487. material = overrideMaterial;
  34488. }
  34489. //
  34490. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  34491. material.side = BackSide;
  34492. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  34493. material.side = FrontSide;
  34494. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  34495. material.side = DoubleSide;
  34496. } else {
  34497. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  34498. }
  34499. //
  34500. if ( overridePositionNode !== undefined ) {
  34501. scene.overrideMaterial.positionNode = overridePositionNode;
  34502. }
  34503. if ( overrideDepthNode !== undefined ) {
  34504. scene.overrideMaterial.depthNode = overrideDepthNode;
  34505. }
  34506. if ( overrideColorNode !== undefined ) {
  34507. scene.overrideMaterial.colorNode = overrideColorNode;
  34508. }
  34509. //
  34510. object.onAfterRender( this, scene, camera, geometry, material, group );
  34511. }
  34512. /**
  34513. * This method represents the default `_handleObjectFunction` implementation which creates
  34514. * a render object from the given data and performs the draw command with the selected backend.
  34515. *
  34516. * @private
  34517. * @param {Object3D} object - The 3D object.
  34518. * @param {Material} material - The object's material.
  34519. * @param {Scene} scene - The scene the 3D object belongs to.
  34520. * @param {Camera} camera - The camera the object should be rendered with.
  34521. * @param {LightsNode} lightsNode - The current lights node.
  34522. * @param {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  34523. * @param {ClippingContext} clippingContext - The clipping context.
  34524. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  34525. */
  34526. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  34527. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  34528. renderObject.drawRange = object.geometry.drawRange;
  34529. renderObject.group = group;
  34530. //
  34531. const needsRefresh = this._nodes.needsRefresh( renderObject );
  34532. if ( needsRefresh ) {
  34533. this._nodes.updateBefore( renderObject );
  34534. this._geometries.updateForRender( renderObject );
  34535. this._nodes.updateForRender( renderObject );
  34536. this._bindings.updateForRender( renderObject );
  34537. }
  34538. this._pipelines.updateForRender( renderObject );
  34539. //
  34540. if ( this._currentRenderBundle !== null ) {
  34541. const renderBundleData = this.backend.get( this._currentRenderBundle );
  34542. renderBundleData.renderObjects.push( renderObject );
  34543. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  34544. }
  34545. this.backend.draw( renderObject, this.info );
  34546. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  34547. }
  34548. /**
  34549. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  34550. * Used in `compileAsync()`.
  34551. *
  34552. * @private
  34553. * @param {Object3D} object - The 3D object.
  34554. * @param {Material} material - The object's material.
  34555. * @param {Scene} scene - The scene the 3D object belongs to.
  34556. * @param {Camera} camera - The camera the object should be rendered with.
  34557. * @param {LightsNode} lightsNode - The current lights node.
  34558. * @param {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  34559. * @param {ClippingContext} clippingContext - The clipping context.
  34560. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  34561. */
  34562. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  34563. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  34564. renderObject.drawRange = object.geometry.drawRange;
  34565. renderObject.group = group;
  34566. //
  34567. this._nodes.updateBefore( renderObject );
  34568. this._geometries.updateForRender( renderObject );
  34569. this._nodes.updateForRender( renderObject );
  34570. this._bindings.updateForRender( renderObject );
  34571. this._pipelines.getForRender( renderObject, this._compilationPromises );
  34572. this._nodes.updateAfter( renderObject );
  34573. }
  34574. /**
  34575. * Alias for `compileAsync()`.
  34576. *
  34577. * @method
  34578. * @param {Object3D} scene - The scene or 3D object to precompile.
  34579. * @param {Camera} camera - The camera that is used to render the scene.
  34580. * @param {Scene} targetScene - If the first argument is a 3D object, this parameter must represent the scene the 3D object is going to be added.
  34581. * @return {Promise} A Promise that resolves when the compile has been finished.
  34582. */
  34583. get compile() {
  34584. return this.compileAsync;
  34585. }
  34586. }
  34587. /**
  34588. * A binding represents the connection between a resource (like a texture, sampler
  34589. * or uniform buffer) and the resource definition in a shader stage.
  34590. *
  34591. * This module is an abstract base class for all concrete bindings types.
  34592. *
  34593. * @abstract
  34594. * @private
  34595. */
  34596. class Binding {
  34597. /**
  34598. * Constructs a new binding.
  34599. *
  34600. * @param {String} [name=''] - The binding's name.
  34601. */
  34602. constructor( name = '' ) {
  34603. /**
  34604. * The binding's name.
  34605. *
  34606. * @type {String}
  34607. */
  34608. this.name = name;
  34609. /**
  34610. * A bitmask that defines in what shader stages the
  34611. * binding's resource is accessible.
  34612. *
  34613. * @type {String}
  34614. */
  34615. this.visibility = 0;
  34616. }
  34617. /**
  34618. * Makes sure binding's resource is visible for the given shader stage.
  34619. *
  34620. * @param {Number} visibility - The shader stage.
  34621. */
  34622. setVisibility( visibility ) {
  34623. this.visibility |= visibility;
  34624. }
  34625. /**
  34626. * Clones the binding.
  34627. *
  34628. * @return {Binding} The cloned binding.
  34629. */
  34630. clone() {
  34631. return Object.assign( new this.constructor(), this );
  34632. }
  34633. }
  34634. /** @module BufferUtils **/
  34635. /**
  34636. * This function is usually called with the length in bytes of an array buffer.
  34637. * It returns an padded value whic ensure chunk size alignment according to STD140 layout.
  34638. *
  34639. * @function
  34640. * @param {Number} floatLength - The buffer length.
  34641. * @return {Number} The padded length.
  34642. */
  34643. function getFloatLength( floatLength ) {
  34644. // ensure chunk size alignment (STD140 layout)
  34645. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  34646. }
  34647. /**
  34648. * Represents a buffer binding type.
  34649. *
  34650. * @private
  34651. * @abstract
  34652. * @augments Binding
  34653. */
  34654. class Buffer extends Binding {
  34655. /**
  34656. * Constructs a new buffer.
  34657. *
  34658. * @param {String} name - The buffer's name.
  34659. * @param {TypedArray} [buffer=null] - The buffer.
  34660. */
  34661. constructor( name, buffer = null ) {
  34662. super( name );
  34663. /**
  34664. * This flag can be used for type testing.
  34665. *
  34666. * @type {Boolean}
  34667. * @readonly
  34668. * @default true
  34669. */
  34670. this.isBuffer = true;
  34671. /**
  34672. * The bytes per element.
  34673. *
  34674. * @type {Number}
  34675. */
  34676. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  34677. /**
  34678. * A reference to the internal buffer.
  34679. *
  34680. * @private
  34681. * @type {TypedArray}
  34682. */
  34683. this._buffer = buffer;
  34684. }
  34685. /**
  34686. * The buffer's byte length.
  34687. *
  34688. * @type {Number}
  34689. * @readonly
  34690. */
  34691. get byteLength() {
  34692. return getFloatLength( this._buffer.byteLength );
  34693. }
  34694. /**
  34695. * A reference to the internal buffer.
  34696. *
  34697. * @type {Float32Array}
  34698. * @readonly
  34699. */
  34700. get buffer() {
  34701. return this._buffer;
  34702. }
  34703. /**
  34704. * Updates the binding.
  34705. *
  34706. * @return {Boolean} Whether the buffer has been updated and must be
  34707. * uploaded to the GPU.
  34708. */
  34709. update() {
  34710. return true;
  34711. }
  34712. }
  34713. /**
  34714. * Represents a uniform buffer binding type.
  34715. *
  34716. * @private
  34717. * @augments Buffer
  34718. */
  34719. class UniformBuffer extends Buffer {
  34720. /**
  34721. * Constructs a new uniform buffer.
  34722. *
  34723. * @param {String} name - The buffer's name.
  34724. * @param {TypedArray} [buffer=null] - The buffer.
  34725. */
  34726. constructor( name, buffer = null ) {
  34727. super( name, buffer );
  34728. /**
  34729. * This flag can be used for type testing.
  34730. *
  34731. * @type {Boolean}
  34732. * @readonly
  34733. * @default true
  34734. */
  34735. this.isUniformBuffer = true;
  34736. }
  34737. }
  34738. let _id$4 = 0;
  34739. /**
  34740. * A special form of uniform buffer binding type.
  34741. * It's buffer value is managed by a node object.
  34742. *
  34743. * @private
  34744. * @augments UniformBuffer
  34745. */
  34746. class NodeUniformBuffer extends UniformBuffer {
  34747. /**
  34748. * Constructs a new node-based uniform buffer.
  34749. *
  34750. * @param {BufferNode} nodeUniform - The uniform buffer node.
  34751. * @param {UniformGroupNode} groupNode - The uniform group node.
  34752. */
  34753. constructor( nodeUniform, groupNode ) {
  34754. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  34755. /**
  34756. * The uniform buffer node.
  34757. *
  34758. * @type {BufferNode}
  34759. */
  34760. this.nodeUniform = nodeUniform;
  34761. /**
  34762. * The uniform group node.
  34763. *
  34764. * @type {UniformGroupNode}
  34765. */
  34766. this.groupNode = groupNode;
  34767. }
  34768. /**
  34769. * The uniform buffer.
  34770. *
  34771. * @type {Float32Array}
  34772. */
  34773. get buffer() {
  34774. return this.nodeUniform.value;
  34775. }
  34776. }
  34777. /**
  34778. * This class represents a uniform buffer binding but with
  34779. * an API that allows to maintain individual uniform objects.
  34780. *
  34781. * @private
  34782. * @augments UniformBuffer
  34783. */
  34784. class UniformsGroup extends UniformBuffer {
  34785. /**
  34786. * Constructs a new uniforms group.
  34787. *
  34788. * @param {String} name - The group's name.
  34789. */
  34790. constructor( name ) {
  34791. super( name );
  34792. /**
  34793. * This flag can be used for type testing.
  34794. *
  34795. * @type {Boolean}
  34796. * @readonly
  34797. * @default true
  34798. */
  34799. this.isUniformsGroup = true;
  34800. /**
  34801. * An array with the raw uniform values.
  34802. *
  34803. * @private
  34804. * @type {Array<Number>?}
  34805. * @default null
  34806. */
  34807. this._values = null;
  34808. /**
  34809. * An array of uniform objects.
  34810. *
  34811. * The order of uniforms in this array must match the order of uniforms in the shader.
  34812. *
  34813. * @type {Array<Uniform>}
  34814. */
  34815. this.uniforms = [];
  34816. }
  34817. /**
  34818. * Adds a uniform to this group.
  34819. *
  34820. * @param {Uniform} uniform - The uniform to add.
  34821. * @return {UniformsGroup} A reference to this group.
  34822. */
  34823. addUniform( uniform ) {
  34824. this.uniforms.push( uniform );
  34825. return this;
  34826. }
  34827. /**
  34828. * Removes a uniform from this group.
  34829. *
  34830. * @param {Uniform} uniform - The uniform to remove.
  34831. * @return {UniformsGroup} A reference to this group.
  34832. */
  34833. removeUniform( uniform ) {
  34834. const index = this.uniforms.indexOf( uniform );
  34835. if ( index !== - 1 ) {
  34836. this.uniforms.splice( index, 1 );
  34837. }
  34838. return this;
  34839. }
  34840. /**
  34841. * An array with the raw uniform values.
  34842. *
  34843. * @type {Array<Number>}
  34844. */
  34845. get values() {
  34846. if ( this._values === null ) {
  34847. this._values = Array.from( this.buffer );
  34848. }
  34849. return this._values;
  34850. }
  34851. /**
  34852. * A Float32 array buffer with the uniform values.
  34853. *
  34854. * @type {Float32Array}
  34855. */
  34856. get buffer() {
  34857. let buffer = this._buffer;
  34858. if ( buffer === null ) {
  34859. const byteLength = this.byteLength;
  34860. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  34861. this._buffer = buffer;
  34862. }
  34863. return buffer;
  34864. }
  34865. /**
  34866. * The byte length of the buffer with correct buffer alignment.
  34867. *
  34868. * @type {Number}
  34869. */
  34870. get byteLength() {
  34871. let offset = 0; // global buffer offset in bytes
  34872. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  34873. const uniform = this.uniforms[ i ];
  34874. const { boundary, itemSize } = uniform;
  34875. // offset within a single chunk in bytes
  34876. const chunkOffset = offset % GPU_CHUNK_BYTES;
  34877. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  34878. // conformance tests
  34879. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  34880. // check for chunk overflow
  34881. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  34882. } else if ( chunkOffset % boundary !== 0 ) {
  34883. // check for correct alignment
  34884. offset += ( chunkOffset % boundary );
  34885. }
  34886. uniform.offset = ( offset / this.bytesPerElement );
  34887. offset += ( itemSize * this.bytesPerElement );
  34888. }
  34889. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  34890. }
  34891. /**
  34892. * Updates this group by updating each uniform object of
  34893. * the internal uniform list. The uniform objects check if their
  34894. * values has actually changed so this method only returns
  34895. * `true` if there is a real value change.
  34896. *
  34897. * @return {Boolean} Whether the uniforms have been updated and
  34898. * must be uploaded to the GPU.
  34899. */
  34900. update() {
  34901. let updated = false;
  34902. for ( const uniform of this.uniforms ) {
  34903. if ( this.updateByType( uniform ) === true ) {
  34904. updated = true;
  34905. }
  34906. }
  34907. return updated;
  34908. }
  34909. /**
  34910. * Updates a given uniform by calling an update method matching
  34911. * the uniforms type.
  34912. *
  34913. * @param {Uniform} uniform - The uniform to update.
  34914. * @return {Boolean} Whether the uniform has been updated or not.
  34915. */
  34916. updateByType( uniform ) {
  34917. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  34918. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  34919. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  34920. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  34921. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  34922. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  34923. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  34924. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  34925. }
  34926. /**
  34927. * Updates a given Number uniform.
  34928. *
  34929. * @param {NumberUniform} uniform - The Number uniform.
  34930. * @return {Boolean} Whether the uniform has been updated or not.
  34931. */
  34932. updateNumber( uniform ) {
  34933. let updated = false;
  34934. const a = this.values;
  34935. const v = uniform.getValue();
  34936. const offset = uniform.offset;
  34937. const type = uniform.getType();
  34938. if ( a[ offset ] !== v ) {
  34939. const b = this._getBufferForType( type );
  34940. b[ offset ] = a[ offset ] = v;
  34941. updated = true;
  34942. }
  34943. return updated;
  34944. }
  34945. /**
  34946. * Updates a given Vector2 uniform.
  34947. *
  34948. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  34949. * @return {Boolean} Whether the uniform has been updated or not.
  34950. */
  34951. updateVector2( uniform ) {
  34952. let updated = false;
  34953. const a = this.values;
  34954. const v = uniform.getValue();
  34955. const offset = uniform.offset;
  34956. const type = uniform.getType();
  34957. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  34958. const b = this._getBufferForType( type );
  34959. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  34960. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  34961. updated = true;
  34962. }
  34963. return updated;
  34964. }
  34965. /**
  34966. * Updates a given Vector3 uniform.
  34967. *
  34968. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  34969. * @return {Boolean} Whether the uniform has been updated or not.
  34970. */
  34971. updateVector3( uniform ) {
  34972. let updated = false;
  34973. const a = this.values;
  34974. const v = uniform.getValue();
  34975. const offset = uniform.offset;
  34976. const type = uniform.getType();
  34977. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  34978. const b = this._getBufferForType( type );
  34979. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  34980. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  34981. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  34982. updated = true;
  34983. }
  34984. return updated;
  34985. }
  34986. /**
  34987. * Updates a given Vector4 uniform.
  34988. *
  34989. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  34990. * @return {Boolean} Whether the uniform has been updated or not.
  34991. */
  34992. updateVector4( uniform ) {
  34993. let updated = false;
  34994. const a = this.values;
  34995. const v = uniform.getValue();
  34996. const offset = uniform.offset;
  34997. const type = uniform.getType();
  34998. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  34999. const b = this._getBufferForType( type );
  35000. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  35001. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  35002. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  35003. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  35004. updated = true;
  35005. }
  35006. return updated;
  35007. }
  35008. /**
  35009. * Updates a given Color uniform.
  35010. *
  35011. * @param {ColorUniform} uniform - The Color uniform.
  35012. * @return {Boolean} Whether the uniform has been updated or not.
  35013. */
  35014. updateColor( uniform ) {
  35015. let updated = false;
  35016. const a = this.values;
  35017. const c = uniform.getValue();
  35018. const offset = uniform.offset;
  35019. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  35020. const b = this.buffer;
  35021. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  35022. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  35023. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  35024. updated = true;
  35025. }
  35026. return updated;
  35027. }
  35028. /**
  35029. * Updates a given Matrix3 uniform.
  35030. *
  35031. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  35032. * @return {Boolean} Whether the uniform has been updated or not.
  35033. */
  35034. updateMatrix3( uniform ) {
  35035. let updated = false;
  35036. const a = this.values;
  35037. const e = uniform.getValue().elements;
  35038. const offset = uniform.offset;
  35039. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  35040. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  35041. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  35042. const b = this.buffer;
  35043. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  35044. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  35045. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  35046. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  35047. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  35048. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  35049. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  35050. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  35051. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  35052. updated = true;
  35053. }
  35054. return updated;
  35055. }
  35056. /**
  35057. * Updates a given Matrix4 uniform.
  35058. *
  35059. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  35060. * @return {Boolean} Whether the uniform has been updated or not.
  35061. */
  35062. updateMatrix4( uniform ) {
  35063. let updated = false;
  35064. const a = this.values;
  35065. const e = uniform.getValue().elements;
  35066. const offset = uniform.offset;
  35067. if ( arraysEqual( a, e, offset ) === false ) {
  35068. const b = this.buffer;
  35069. b.set( e, offset );
  35070. setArray( a, e, offset );
  35071. updated = true;
  35072. }
  35073. return updated;
  35074. }
  35075. /**
  35076. * Returns a typed array that matches the given data type.
  35077. *
  35078. * @param {String} type - The data type.
  35079. * @return {TypedArray} The typed array.
  35080. */
  35081. _getBufferForType( type ) {
  35082. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  35083. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  35084. return this.buffer;
  35085. }
  35086. }
  35087. /**
  35088. * Sets the values of the second array to the first array.
  35089. *
  35090. * @param {TypedArray} a - The first array.
  35091. * @param {TypedArray} b - The second array.
  35092. * @param {Number} offset - An index offset for the first array.
  35093. */
  35094. function setArray( a, b, offset ) {
  35095. for ( let i = 0, l = b.length; i < l; i ++ ) {
  35096. a[ offset + i ] = b[ i ];
  35097. }
  35098. }
  35099. /**
  35100. * Returns `true` if the given arrays are equal.
  35101. *
  35102. * @param {TypedArray} a - The first array.
  35103. * @param {TypedArray} b - The second array.
  35104. * @param {Number} offset - An index offset for the first array.
  35105. * @return {Boolean} Whether the given arrays are equal or not.
  35106. */
  35107. function arraysEqual( a, b, offset ) {
  35108. for ( let i = 0, l = b.length; i < l; i ++ ) {
  35109. if ( a[ offset + i ] !== b[ i ] ) return false;
  35110. }
  35111. return true;
  35112. }
  35113. let _id$3 = 0;
  35114. /**
  35115. * A special form of uniforms group that represents
  35116. * the individual uniforms as node-based uniforms.
  35117. *
  35118. * @private
  35119. * @augments UniformsGroup
  35120. */
  35121. class NodeUniformsGroup extends UniformsGroup {
  35122. /**
  35123. * Constructs a new node-based uniforms group.
  35124. *
  35125. * @param {String} name - The group's name.
  35126. * @param {UniformGroupNode} groupNode - The uniform group node.
  35127. */
  35128. constructor( name, groupNode ) {
  35129. super( name );
  35130. /**
  35131. * The group's ID.
  35132. *
  35133. * @type {Number}
  35134. */
  35135. this.id = _id$3 ++;
  35136. /**
  35137. * The uniform group node.
  35138. *
  35139. * @type {UniformGroupNode}
  35140. */
  35141. this.groupNode = groupNode;
  35142. /**
  35143. * This flag can be used for type testing.
  35144. *
  35145. * @type {Boolean}
  35146. * @readonly
  35147. * @default true
  35148. */
  35149. this.isNodeUniformsGroup = true;
  35150. }
  35151. }
  35152. let _id$2 = 0;
  35153. /**
  35154. * Represents a sampled texture binding type.
  35155. *
  35156. * @private
  35157. * @augments Binding
  35158. */
  35159. class SampledTexture extends Binding {
  35160. /**
  35161. * Constructs a new sampled texture.
  35162. *
  35163. * @param {String} name - The sampled texture's name.
  35164. * @param {Texture?} texture - The texture this binding is referring to.
  35165. */
  35166. constructor( name, texture ) {
  35167. super( name );
  35168. /**
  35169. * This identifier.
  35170. *
  35171. * @type {Number}
  35172. */
  35173. this.id = _id$2 ++;
  35174. /**
  35175. * The texture this binding is referring to.
  35176. *
  35177. * @type {Texture?}
  35178. */
  35179. this.texture = texture;
  35180. /**
  35181. * The binding's version.
  35182. *
  35183. * @type {Number}
  35184. */
  35185. this.version = texture ? texture.version : 0;
  35186. /**
  35187. * Whether the texture is a storage texture or not.
  35188. *
  35189. * @type {Boolean}
  35190. * @default false
  35191. */
  35192. this.store = false;
  35193. /**
  35194. * The binding's generation which is an additional version
  35195. * qualifier.
  35196. *
  35197. * @type {Number?}
  35198. * @default null
  35199. */
  35200. this.generation = null;
  35201. /**
  35202. * This flag can be used for type testing.
  35203. *
  35204. * @type {Boolean}
  35205. * @readonly
  35206. * @default true
  35207. */
  35208. this.isSampledTexture = true;
  35209. }
  35210. /**
  35211. * Returns `true` whether this binding requires an update for the
  35212. * given generation.
  35213. *
  35214. * @param {Number} generation - The generation.
  35215. * @return {Boolean} Whether an update is required or not.
  35216. */
  35217. needsBindingsUpdate( generation ) {
  35218. const { texture } = this;
  35219. if ( generation !== this.generation ) {
  35220. this.generation = generation;
  35221. return true;
  35222. }
  35223. return texture.isVideoTexture;
  35224. }
  35225. /**
  35226. * Updates the binding.
  35227. *
  35228. * @param {Number} generation - The generation.
  35229. * @return {Boolean} Whether the texture has been updated and must be
  35230. * uploaded to the GPU.
  35231. */
  35232. update() {
  35233. const { texture, version } = this;
  35234. if ( version !== texture.version ) {
  35235. this.version = texture.version;
  35236. return true;
  35237. }
  35238. return false;
  35239. }
  35240. }
  35241. /**
  35242. * A special form of sampled texture binding type.
  35243. * It's texture value is managed by a node object.
  35244. *
  35245. * @private
  35246. * @augments SampledTexture
  35247. */
  35248. class NodeSampledTexture extends SampledTexture {
  35249. /**
  35250. * Constructs a new node-based sampled texture.
  35251. *
  35252. * @param {String} name - The textures's name.
  35253. * @param {TextureNode} textureNode - The texture node.
  35254. * @param {UniformGroupNode} groupNode - The uniform group node.
  35255. * @param {String?} [access=null] - The access type.
  35256. */
  35257. constructor( name, textureNode, groupNode, access = null ) {
  35258. super( name, textureNode ? textureNode.value : null );
  35259. /**
  35260. * The texture node.
  35261. *
  35262. * @type {TextureNode}
  35263. */
  35264. this.textureNode = textureNode;
  35265. /**
  35266. * The uniform group node.
  35267. *
  35268. * @type {UniformGroupNode}
  35269. */
  35270. this.groupNode = groupNode;
  35271. /**
  35272. * The access type.
  35273. *
  35274. * @type {String?}
  35275. * @default null
  35276. */
  35277. this.access = access;
  35278. }
  35279. /**
  35280. * Overwrites the default to additionally check if the node value has changed.
  35281. *
  35282. * @param {Number} generation - The generation.
  35283. * @return {Boolean} Whether an update is required or not.
  35284. */
  35285. needsBindingsUpdate( generation ) {
  35286. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  35287. }
  35288. /**
  35289. * Updates the binding.
  35290. *
  35291. * @param {Number} generation - The generation.
  35292. * @return {Boolean} Whether the texture has been updated and must be
  35293. * uploaded to the GPU.
  35294. */
  35295. update() {
  35296. const { textureNode } = this;
  35297. if ( this.texture !== textureNode.value ) {
  35298. this.texture = textureNode.value;
  35299. return true;
  35300. }
  35301. return super.update();
  35302. }
  35303. }
  35304. /**
  35305. * A special form of sampled cube texture binding type.
  35306. * It's texture value is managed by a node object.
  35307. *
  35308. * @private
  35309. * @augments NodeSampledTexture
  35310. */
  35311. class NodeSampledCubeTexture extends NodeSampledTexture {
  35312. /**
  35313. * Constructs a new node-based sampled cube texture.
  35314. *
  35315. * @param {String} name - The textures's name.
  35316. * @param {TextureNode} textureNode - The texture node.
  35317. * @param {UniformGroupNode} groupNode - The uniform group node.
  35318. * @param {String?} [access=null] - The access type.
  35319. */
  35320. constructor( name, textureNode, groupNode, access = null ) {
  35321. super( name, textureNode, groupNode, access );
  35322. /**
  35323. * This flag can be used for type testing.
  35324. *
  35325. * @type {Boolean}
  35326. * @readonly
  35327. * @default true
  35328. */
  35329. this.isSampledCubeTexture = true;
  35330. }
  35331. }
  35332. /**
  35333. * A special form of sampled 3D texture binding type.
  35334. * It's texture value is managed by a node object.
  35335. *
  35336. * @private
  35337. * @augments NodeSampledTexture
  35338. */
  35339. class NodeSampledTexture3D extends NodeSampledTexture {
  35340. /**
  35341. * Constructs a new node-based sampled 3D texture.
  35342. *
  35343. * @param {String} name - The textures's name.
  35344. * @param {TextureNode} textureNode - The texture node.
  35345. * @param {UniformGroupNode} groupNode - The uniform group node.
  35346. * @param {String?} [access=null] - The access type.
  35347. */
  35348. constructor( name, textureNode, groupNode, access = null ) {
  35349. super( name, textureNode, groupNode, access );
  35350. /**
  35351. * This flag can be used for type testing.
  35352. *
  35353. * @type {Boolean}
  35354. * @readonly
  35355. * @default true
  35356. */
  35357. this.isSampledTexture3D = true;
  35358. }
  35359. }
  35360. const glslMethods = {
  35361. textureDimensions: 'textureSize',
  35362. equals: 'equal'
  35363. };
  35364. const precisionLib = {
  35365. low: 'lowp',
  35366. medium: 'mediump',
  35367. high: 'highp'
  35368. };
  35369. const supports$1 = {
  35370. swizzleAssign: true,
  35371. storageBuffer: false
  35372. };
  35373. const defaultPrecisions = `
  35374. precision highp float;
  35375. precision highp int;
  35376. precision highp sampler2D;
  35377. precision highp sampler3D;
  35378. precision highp samplerCube;
  35379. precision highp sampler2DArray;
  35380. precision highp usampler2D;
  35381. precision highp usampler3D;
  35382. precision highp usamplerCube;
  35383. precision highp usampler2DArray;
  35384. precision highp isampler2D;
  35385. precision highp isampler3D;
  35386. precision highp isamplerCube;
  35387. precision highp isampler2DArray;
  35388. precision lowp sampler2DShadow;
  35389. `;
  35390. class GLSLNodeBuilder extends NodeBuilder {
  35391. constructor( object, renderer ) {
  35392. super( object, renderer, new GLSLNodeParser() );
  35393. this.uniformGroups = {};
  35394. this.transforms = [];
  35395. this.extensions = {};
  35396. this.builtins = { vertex: [], fragment: [], compute: [] };
  35397. this.useComparisonMethod = true;
  35398. }
  35399. needsToWorkingColorSpace( texture ) {
  35400. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  35401. }
  35402. getMethod( method ) {
  35403. return glslMethods[ method ] || method;
  35404. }
  35405. getOutputStructName() {
  35406. return '';
  35407. }
  35408. buildFunctionCode( shaderNode ) {
  35409. const layout = shaderNode.layout;
  35410. const flowData = this.flowShaderNode( shaderNode );
  35411. const parameters = [];
  35412. for ( const input of layout.inputs ) {
  35413. parameters.push( this.getType( input.type ) + ' ' + input.name );
  35414. }
  35415. //
  35416. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  35417. ${ flowData.vars }
  35418. ${ flowData.code }
  35419. return ${ flowData.result };
  35420. }`;
  35421. //
  35422. return code;
  35423. }
  35424. setupPBO( storageBufferNode ) {
  35425. const attribute = storageBufferNode.value;
  35426. if ( attribute.pbo === undefined ) {
  35427. const originalArray = attribute.array;
  35428. const numElements = attribute.count * attribute.itemSize;
  35429. const { itemSize } = attribute;
  35430. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  35431. let format = isInteger ? RedIntegerFormat : RedFormat;
  35432. if ( itemSize === 2 ) {
  35433. format = isInteger ? RGIntegerFormat : RGFormat;
  35434. } else if ( itemSize === 3 ) {
  35435. format = isInteger ? RGBIntegerFormat : RGBFormat;
  35436. } else if ( itemSize === 4 ) {
  35437. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  35438. }
  35439. const typeMap = {
  35440. Float32Array: FloatType,
  35441. Uint8Array: UnsignedByteType,
  35442. Uint16Array: UnsignedShortType,
  35443. Uint32Array: UnsignedIntType,
  35444. Int8Array: ByteType,
  35445. Int16Array: ShortType,
  35446. Int32Array: IntType,
  35447. Uint8ClampedArray: UnsignedByteType,
  35448. };
  35449. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  35450. let height = Math.ceil( ( numElements / itemSize ) / width );
  35451. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  35452. const newSize = width * height * itemSize;
  35453. const newArray = new originalArray.constructor( newSize );
  35454. newArray.set( originalArray, 0 );
  35455. attribute.array = newArray;
  35456. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  35457. pboTexture.needsUpdate = true;
  35458. pboTexture.isPBOTexture = true;
  35459. const pbo = new TextureNode( pboTexture, null, null );
  35460. pbo.setPrecision( 'high' );
  35461. attribute.pboNode = pbo;
  35462. attribute.pbo = pbo.value;
  35463. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  35464. }
  35465. }
  35466. getPropertyName( node, shaderStage = this.shaderStage ) {
  35467. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  35468. return shaderStage.charAt( 0 ) + '_' + node.name;
  35469. }
  35470. return super.getPropertyName( node, shaderStage );
  35471. }
  35472. generatePBO( storageArrayElementNode ) {
  35473. const { node, indexNode } = storageArrayElementNode;
  35474. const attribute = node.value;
  35475. if ( this.renderer.backend.has( attribute ) ) {
  35476. const attributeData = this.renderer.backend.get( attribute );
  35477. attributeData.pbo = attribute.pbo;
  35478. }
  35479. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  35480. const textureName = this.getPropertyName( nodeUniform );
  35481. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  35482. const indexSnippet = indexNode.build( this, 'uint' );
  35483. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  35484. let propertyName = elementNodeData.propertyName;
  35485. if ( propertyName === undefined ) {
  35486. // property element
  35487. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  35488. propertyName = this.getPropertyName( nodeVar );
  35489. // property size
  35490. const bufferNodeData = this.getDataFromNode( node );
  35491. let propertySizeName = bufferNodeData.propertySizeName;
  35492. if ( propertySizeName === undefined ) {
  35493. propertySizeName = propertyName + 'Size';
  35494. this.getVarFromNode( node, propertySizeName, 'uint' );
  35495. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  35496. bufferNodeData.propertySizeName = propertySizeName;
  35497. }
  35498. //
  35499. const { itemSize } = attribute;
  35500. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  35501. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  35502. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  35503. //
  35504. let prefix = 'vec4';
  35505. if ( attribute.pbo.type === UnsignedIntType ) {
  35506. prefix = 'uvec4';
  35507. } else if ( attribute.pbo.type === IntType ) {
  35508. prefix = 'ivec4';
  35509. }
  35510. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  35511. elementNodeData.propertyName = propertyName;
  35512. }
  35513. return propertyName;
  35514. }
  35515. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  35516. if ( depthSnippet ) {
  35517. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  35518. } else {
  35519. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  35520. }
  35521. }
  35522. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  35523. if ( texture.isDepthTexture ) {
  35524. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  35525. } else {
  35526. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  35527. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  35528. }
  35529. }
  35530. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  35531. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  35532. }
  35533. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  35534. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  35535. }
  35536. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  35537. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  35538. }
  35539. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  35540. if ( shaderStage === 'fragment' ) {
  35541. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  35542. } else {
  35543. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  35544. }
  35545. }
  35546. getVars( shaderStage ) {
  35547. const snippets = [];
  35548. const vars = this.vars[ shaderStage ];
  35549. if ( vars !== undefined ) {
  35550. for ( const variable of vars ) {
  35551. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  35552. }
  35553. }
  35554. return snippets.join( '\n\t' );
  35555. }
  35556. getUniforms( shaderStage ) {
  35557. const uniforms = this.uniforms[ shaderStage ];
  35558. const bindingSnippets = [];
  35559. const uniformGroups = {};
  35560. for ( const uniform of uniforms ) {
  35561. let snippet = null;
  35562. let group = false;
  35563. if ( uniform.type === 'texture' ) {
  35564. const texture = uniform.node.value;
  35565. let typePrefix = '';
  35566. if ( texture.isDataTexture === true ) {
  35567. if ( texture.type === UnsignedIntType ) {
  35568. typePrefix = 'u';
  35569. } else if ( texture.type === IntType ) {
  35570. typePrefix = 'i';
  35571. }
  35572. }
  35573. if ( texture.compareFunction ) {
  35574. snippet = `sampler2DShadow ${ uniform.name };`;
  35575. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  35576. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  35577. } else {
  35578. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  35579. }
  35580. } else if ( uniform.type === 'cubeTexture' ) {
  35581. snippet = `samplerCube ${ uniform.name };`;
  35582. } else if ( uniform.type === 'texture3D' ) {
  35583. snippet = `sampler3D ${ uniform.name };`;
  35584. } else if ( uniform.type === 'buffer' ) {
  35585. const bufferNode = uniform.node;
  35586. const bufferType = this.getType( bufferNode.bufferType );
  35587. const bufferCount = bufferNode.bufferCount;
  35588. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  35589. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  35590. } else {
  35591. const vectorType = this.getVectorType( uniform.type );
  35592. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  35593. group = true;
  35594. }
  35595. const precision = uniform.node.precision;
  35596. if ( precision !== null ) {
  35597. snippet = precisionLib[ precision ] + ' ' + snippet;
  35598. }
  35599. if ( group ) {
  35600. snippet = '\t' + snippet;
  35601. const groupName = uniform.groupNode.name;
  35602. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  35603. groupSnippets.push( snippet );
  35604. } else {
  35605. snippet = 'uniform ' + snippet;
  35606. bindingSnippets.push( snippet );
  35607. }
  35608. }
  35609. let output = '';
  35610. for ( const name in uniformGroups ) {
  35611. const groupSnippets = uniformGroups[ name ];
  35612. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  35613. }
  35614. output += bindingSnippets.join( '\n' );
  35615. return output;
  35616. }
  35617. getTypeFromAttribute( attribute ) {
  35618. let nodeType = super.getTypeFromAttribute( attribute );
  35619. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  35620. let dataAttribute = attribute;
  35621. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  35622. const array = dataAttribute.array;
  35623. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  35624. nodeType = nodeType.slice( 1 );
  35625. }
  35626. }
  35627. return nodeType;
  35628. }
  35629. getAttributes( shaderStage ) {
  35630. let snippet = '';
  35631. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  35632. const attributes = this.getAttributesArray();
  35633. let location = 0;
  35634. for ( const attribute of attributes ) {
  35635. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  35636. }
  35637. }
  35638. return snippet;
  35639. }
  35640. getStructMembers( struct ) {
  35641. const snippets = [];
  35642. const members = struct.getMemberTypes();
  35643. for ( let i = 0; i < members.length; i ++ ) {
  35644. const member = members[ i ];
  35645. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  35646. }
  35647. return snippets.join( '\n' );
  35648. }
  35649. getStructs( shaderStage ) {
  35650. const snippets = [];
  35651. const structs = this.structs[ shaderStage ];
  35652. if ( structs.length === 0 ) {
  35653. return 'layout( location = 0 ) out vec4 fragColor;\n';
  35654. }
  35655. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  35656. const struct = structs[ index ];
  35657. let snippet = '\n';
  35658. snippet += this.getStructMembers( struct );
  35659. snippet += '\n';
  35660. snippets.push( snippet );
  35661. }
  35662. return snippets.join( '\n\n' );
  35663. }
  35664. getVaryings( shaderStage ) {
  35665. let snippet = '';
  35666. const varyings = this.varyings;
  35667. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  35668. for ( const varying of varyings ) {
  35669. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  35670. const type = this.getType( varying.type );
  35671. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  35672. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  35673. }
  35674. } else if ( shaderStage === 'fragment' ) {
  35675. for ( const varying of varyings ) {
  35676. if ( varying.needsInterpolation ) {
  35677. const type = this.getType( varying.type );
  35678. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  35679. snippet += `${flat}in ${type} ${varying.name};\n`;
  35680. }
  35681. }
  35682. }
  35683. for ( const builtin of this.builtins[ shaderStage ] ) {
  35684. snippet += `${builtin};\n`;
  35685. }
  35686. return snippet;
  35687. }
  35688. getVertexIndex() {
  35689. return 'uint( gl_VertexID )';
  35690. }
  35691. getInstanceIndex() {
  35692. return 'uint( gl_InstanceID )';
  35693. }
  35694. getInvocationLocalIndex() {
  35695. const workgroupSize = this.object.workgroupSize;
  35696. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  35697. return `uint( gl_InstanceID ) % ${size}u`;
  35698. }
  35699. getDrawIndex() {
  35700. const extensions = this.renderer.backend.extensions;
  35701. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  35702. return 'uint( gl_DrawID )';
  35703. }
  35704. return null;
  35705. }
  35706. getFrontFacing() {
  35707. return 'gl_FrontFacing';
  35708. }
  35709. getFragCoord() {
  35710. return 'gl_FragCoord.xy';
  35711. }
  35712. getFragDepth() {
  35713. return 'gl_FragDepth';
  35714. }
  35715. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  35716. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  35717. if ( map.has( name ) === false ) {
  35718. map.set( name, {
  35719. name,
  35720. behavior
  35721. } );
  35722. }
  35723. }
  35724. getExtensions( shaderStage ) {
  35725. const snippets = [];
  35726. if ( shaderStage === 'vertex' ) {
  35727. const ext = this.renderer.backend.extensions;
  35728. const isBatchedMesh = this.object.isBatchedMesh;
  35729. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  35730. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  35731. }
  35732. }
  35733. const extensions = this.extensions[ shaderStage ];
  35734. if ( extensions !== undefined ) {
  35735. for ( const { name, behavior } of extensions.values() ) {
  35736. snippets.push( `#extension ${name} : ${behavior}` );
  35737. }
  35738. }
  35739. return snippets.join( '\n' );
  35740. }
  35741. getClipDistance() {
  35742. return 'gl_ClipDistance';
  35743. }
  35744. isAvailable( name ) {
  35745. let result = supports$1[ name ];
  35746. if ( result === undefined ) {
  35747. let extensionName;
  35748. result = false;
  35749. switch ( name ) {
  35750. case 'float32Filterable':
  35751. extensionName = 'OES_texture_float_linear';
  35752. break;
  35753. case 'clipDistance':
  35754. extensionName = 'WEBGL_clip_cull_distance';
  35755. break;
  35756. }
  35757. if ( extensionName !== undefined ) {
  35758. const extensions = this.renderer.backend.extensions;
  35759. if ( extensions.has( extensionName ) ) {
  35760. extensions.get( extensionName );
  35761. result = true;
  35762. }
  35763. }
  35764. supports$1[ name ] = result;
  35765. }
  35766. return result;
  35767. }
  35768. isFlipY() {
  35769. return true;
  35770. }
  35771. enableHardwareClipping( planeCount ) {
  35772. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  35773. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  35774. }
  35775. registerTransform( varyingName, attributeNode ) {
  35776. this.transforms.push( { varyingName, attributeNode } );
  35777. }
  35778. getTransforms( /* shaderStage */ ) {
  35779. const transforms = this.transforms;
  35780. let snippet = '';
  35781. for ( let i = 0; i < transforms.length; i ++ ) {
  35782. const transform = transforms[ i ];
  35783. const attributeName = this.getPropertyName( transform.attributeNode );
  35784. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  35785. }
  35786. return snippet;
  35787. }
  35788. _getGLSLUniformStruct( name, vars ) {
  35789. return `
  35790. layout( std140 ) uniform ${name} {
  35791. ${vars}
  35792. };`;
  35793. }
  35794. _getGLSLVertexCode( shaderData ) {
  35795. return `#version 300 es
  35796. ${ this.getSignature() }
  35797. // extensions
  35798. ${shaderData.extensions}
  35799. // precision
  35800. ${ defaultPrecisions }
  35801. // uniforms
  35802. ${shaderData.uniforms}
  35803. // varyings
  35804. ${shaderData.varyings}
  35805. // attributes
  35806. ${shaderData.attributes}
  35807. // codes
  35808. ${shaderData.codes}
  35809. void main() {
  35810. // vars
  35811. ${shaderData.vars}
  35812. // transforms
  35813. ${shaderData.transforms}
  35814. // flow
  35815. ${shaderData.flow}
  35816. gl_PointSize = 1.0;
  35817. }
  35818. `;
  35819. }
  35820. _getGLSLFragmentCode( shaderData ) {
  35821. return `#version 300 es
  35822. ${ this.getSignature() }
  35823. // precision
  35824. ${ defaultPrecisions }
  35825. // uniforms
  35826. ${shaderData.uniforms}
  35827. // varyings
  35828. ${shaderData.varyings}
  35829. // codes
  35830. ${shaderData.codes}
  35831. ${shaderData.structs}
  35832. void main() {
  35833. // vars
  35834. ${shaderData.vars}
  35835. // flow
  35836. ${shaderData.flow}
  35837. }
  35838. `;
  35839. }
  35840. buildCode() {
  35841. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  35842. this.sortBindingGroups();
  35843. for ( const shaderStage in shadersData ) {
  35844. let flow = '// code\n\n';
  35845. flow += this.flowCode[ shaderStage ];
  35846. const flowNodes = this.flowNodes[ shaderStage ];
  35847. const mainNode = flowNodes[ flowNodes.length - 1 ];
  35848. for ( const node of flowNodes ) {
  35849. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  35850. const slotName = node.name;
  35851. if ( slotName ) {
  35852. if ( flow.length > 0 ) flow += '\n';
  35853. flow += `\t// flow -> ${ slotName }\n\t`;
  35854. }
  35855. flow += `${ flowSlotData.code }\n\t`;
  35856. if ( node === mainNode && shaderStage !== 'compute' ) {
  35857. flow += '// result\n\t';
  35858. if ( shaderStage === 'vertex' ) {
  35859. flow += 'gl_Position = ';
  35860. flow += `${ flowSlotData.result };`;
  35861. } else if ( shaderStage === 'fragment' ) {
  35862. if ( ! node.outputNode.isOutputStructNode ) {
  35863. flow += 'fragColor = ';
  35864. flow += `${ flowSlotData.result };`;
  35865. }
  35866. }
  35867. }
  35868. }
  35869. const stageData = shadersData[ shaderStage ];
  35870. stageData.extensions = this.getExtensions( shaderStage );
  35871. stageData.uniforms = this.getUniforms( shaderStage );
  35872. stageData.attributes = this.getAttributes( shaderStage );
  35873. stageData.varyings = this.getVaryings( shaderStage );
  35874. stageData.vars = this.getVars( shaderStage );
  35875. stageData.structs = this.getStructs( shaderStage );
  35876. stageData.codes = this.getCodes( shaderStage );
  35877. stageData.transforms = this.getTransforms( shaderStage );
  35878. stageData.flow = flow;
  35879. }
  35880. if ( this.material !== null ) {
  35881. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  35882. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  35883. } else {
  35884. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  35885. }
  35886. }
  35887. getUniformFromNode( node, type, shaderStage, name = null ) {
  35888. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  35889. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  35890. let uniformGPU = nodeData.uniformGPU;
  35891. if ( uniformGPU === undefined ) {
  35892. const group = node.groupNode;
  35893. const groupName = group.name;
  35894. const bindings = this.getBindGroupArray( groupName, shaderStage );
  35895. if ( type === 'texture' ) {
  35896. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  35897. bindings.push( uniformGPU );
  35898. } else if ( type === 'cubeTexture' ) {
  35899. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  35900. bindings.push( uniformGPU );
  35901. } else if ( type === 'texture3D' ) {
  35902. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  35903. bindings.push( uniformGPU );
  35904. } else if ( type === 'buffer' ) {
  35905. node.name = `NodeBuffer_${ node.id }`;
  35906. uniformNode.name = `buffer${ node.id }`;
  35907. const buffer = new NodeUniformBuffer( node, group );
  35908. buffer.name = node.name;
  35909. bindings.push( buffer );
  35910. uniformGPU = buffer;
  35911. } else {
  35912. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  35913. let uniformsGroup = uniformsStage[ groupName ];
  35914. if ( uniformsGroup === undefined ) {
  35915. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  35916. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  35917. uniformsStage[ groupName ] = uniformsGroup;
  35918. bindings.push( uniformsGroup );
  35919. }
  35920. uniformGPU = this.getNodeUniform( uniformNode, type );
  35921. uniformsGroup.addUniform( uniformGPU );
  35922. }
  35923. nodeData.uniformGPU = uniformGPU;
  35924. }
  35925. return uniformNode;
  35926. }
  35927. }
  35928. let _vector2 = null;
  35929. let _color4 = null;
  35930. /**
  35931. * Most of the rendering related logic is implemented in the
  35932. * {@link module:Renderer} module and related management components.
  35933. * Sometimes it is required though to execute commands which are
  35934. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  35935. * This abstract base class defines an interface that encapsulates
  35936. * all backend-related logic. Derived classes for each backend must
  35937. * implement the interface.
  35938. *
  35939. * @abstract
  35940. * @private
  35941. */
  35942. class Backend {
  35943. /**
  35944. * Constructs a new backend.
  35945. *
  35946. * @param {Object} parameters - An object holding parameters for the backend.
  35947. */
  35948. constructor( parameters = {} ) {
  35949. /**
  35950. * The parameters of the backend.
  35951. *
  35952. * @type {Object}
  35953. */
  35954. this.parameters = Object.assign( {}, parameters );
  35955. /**
  35956. * This weak map holds backend-specific data of objects
  35957. * like textures, attributes or render targets.
  35958. *
  35959. * @type {WeakMap}
  35960. */
  35961. this.data = new WeakMap();
  35962. /**
  35963. * A reference to the renderer.
  35964. *
  35965. * @type {Renderer?}
  35966. * @default null
  35967. */
  35968. this.renderer = null;
  35969. /**
  35970. * A reference to the canvas element the renderer is drawing to.
  35971. *
  35972. * @type {(HTMLCanvasElement|OffscreenCanvas)?}
  35973. * @default null
  35974. */
  35975. this.domElement = null;
  35976. }
  35977. /**
  35978. * Initializes the backend so it is ready for usage. Concrete backends
  35979. * are supposed to implement their rendering context creation and related
  35980. * operations in this method.
  35981. *
  35982. * @async
  35983. * @param {Renderer} renderer - The renderer.
  35984. * @return {Promise} A Promise that resolves when the backend has been initialized.
  35985. */
  35986. async init( renderer ) {
  35987. this.renderer = renderer;
  35988. }
  35989. /**
  35990. * The coordinate system of the backend.
  35991. *
  35992. * @abstract
  35993. * @type {Number}
  35994. * @readonly
  35995. */
  35996. get coordinateSystem() {}
  35997. // render context
  35998. /**
  35999. * This method is executed at the beginning of a render call and
  36000. * can be used by the backend to prepare the state for upcoming
  36001. * draw calls.
  36002. *
  36003. * @abstract
  36004. * @param {RenderContext} renderContext - The render context.
  36005. */
  36006. beginRender( /*renderContext*/ ) {}
  36007. /**
  36008. * This method is executed at the end of a render call and
  36009. * can be used by the backend to finalize work after draw
  36010. * calls.
  36011. *
  36012. * @abstract
  36013. * @param {RenderContext} renderContext - The render context.
  36014. */
  36015. finishRender( /*renderContext*/ ) {}
  36016. /**
  36017. * This method is executed at the beginning of a compute call and
  36018. * can be used by the backend to prepare the state for upcoming
  36019. * compute tasks.
  36020. *
  36021. * @abstract
  36022. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  36023. */
  36024. beginCompute( /*computeGroup*/ ) {}
  36025. /**
  36026. * This method is executed at the end of a compute call and
  36027. * can be used by the backend to finalize work after compute
  36028. * tasks.
  36029. *
  36030. * @abstract
  36031. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  36032. */
  36033. finishCompute( /*computeGroup*/ ) {}
  36034. // render object
  36035. /**
  36036. * Executes a draw command for the given render object.
  36037. *
  36038. * @abstract
  36039. * @param {RenderObject} renderObject - The render object to draw.
  36040. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  36041. */
  36042. draw( /*renderObject, info*/ ) { }
  36043. // compute node
  36044. /**
  36045. * Executes a compute command for the given compute node.
  36046. *
  36047. * @abstract
  36048. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  36049. * @param {Node} computeNode - The compute node.
  36050. * @param {Array<BindGroup>} bindings - The bindings.
  36051. * @param {ComputePipeline} computePipeline - The compute pipeline.
  36052. */
  36053. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  36054. // program
  36055. /**
  36056. * Creates a shader program from the given programmable stage.
  36057. *
  36058. * @abstract
  36059. * @param {ProgrammableStage} program - The programmable stage.
  36060. */
  36061. createProgram( /*program*/ ) { }
  36062. /**
  36063. * Destroys the shader program of the given programmable stage.
  36064. *
  36065. * @abstract
  36066. * @param {ProgrammableStage} program - The programmable stage.
  36067. */
  36068. destroyProgram( /*program*/ ) { }
  36069. // bindings
  36070. /**
  36071. * Creates bindings from the given bind group definition.
  36072. *
  36073. * @abstract
  36074. * @param {BindGroup} bindGroup - The bind group.
  36075. * @param {Array<BindGroup>} bindings - Array of bind groups.
  36076. * @param {Number} cacheIndex - The cache index.
  36077. * @param {Number} version - The version.
  36078. */
  36079. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  36080. /**
  36081. * Updates the given bind group definition.
  36082. *
  36083. * @abstract
  36084. * @param {BindGroup} bindGroup - The bind group.
  36085. * @param {Array<BindGroup>} bindings - Array of bind groups.
  36086. * @param {Number} cacheIndex - The cache index.
  36087. * @param {Number} version - The version.
  36088. */
  36089. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  36090. /**
  36091. * Updates a buffer binding.
  36092. *
  36093. * @abstract
  36094. * @param {Buffer} binding - The buffer binding to update.
  36095. */
  36096. updateBinding( /*binding*/ ) { }
  36097. // pipeline
  36098. /**
  36099. * Creates a render pipeline for the given render object.
  36100. *
  36101. * @abstract
  36102. * @param {RenderObject} renderObject - The render object.
  36103. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  36104. */
  36105. createRenderPipeline( /*renderObject, promises*/ ) { }
  36106. /**
  36107. * Creates a compute pipeline for the given compute node.
  36108. *
  36109. * @abstract
  36110. * @param {ComputePipeline} computePipeline - The compute pipeline.
  36111. * @param {Array<BindGroup>} bindings - The bindings.
  36112. */
  36113. createComputePipeline( /*computePipeline, bindings*/ ) { }
  36114. // cache key
  36115. /**
  36116. * Returns `true` if the render pipeline requires an update.
  36117. *
  36118. * @abstract
  36119. * @param {RenderObject} renderObject - The render object.
  36120. * @return {Boolean} Whether the render pipeline requires an update or not.
  36121. */
  36122. needsRenderUpdate( /*renderObject*/ ) { }
  36123. /**
  36124. * Returns a cache key that is used to identify render pipelines.
  36125. *
  36126. * @abstract
  36127. * @param {RenderObject} renderObject - The render object.
  36128. * @return {String} The cache key.
  36129. */
  36130. getRenderCacheKey( /*renderObject*/ ) { }
  36131. // node builder
  36132. /**
  36133. * Returns a node builder for the given render object.
  36134. *
  36135. * @abstract
  36136. * @param {RenderObject} renderObject - The render object.
  36137. * @param {Renderer} renderer - The renderer.
  36138. * @return {NodeBuilder} The node builder.
  36139. */
  36140. createNodeBuilder( /*renderObject, renderer*/ ) { }
  36141. // textures
  36142. /**
  36143. * Creates a sampler for the given texture.
  36144. *
  36145. * @abstract
  36146. * @param {Texture} texture - The texture to create the sampler for.
  36147. */
  36148. createSampler( /*texture*/ ) { }
  36149. /**
  36150. * Destroys the sampler for the given texture.
  36151. *
  36152. * @abstract
  36153. * @param {Texture} texture - The texture to destroy the sampler for.
  36154. */
  36155. destroySampler( /*texture*/ ) {}
  36156. /**
  36157. * Creates a default texture for the given texture that can be used
  36158. * as a placeholder until the actual texture is ready for usage.
  36159. *
  36160. * @abstract
  36161. * @param {Texture} texture - The texture to create a default texture for.
  36162. */
  36163. createDefaultTexture( /*texture*/ ) { }
  36164. /**
  36165. * Defines a texture on the GPU for the given texture object.
  36166. *
  36167. * @abstract
  36168. * @param {Texture} texture - The texture.
  36169. * @param {Object} [options={}] - Optional configuration parameter.
  36170. */
  36171. createTexture( /*texture, options={}*/ ) { }
  36172. /**
  36173. * Uploads the updated texture data to the GPU.
  36174. *
  36175. * @abstract
  36176. * @param {Texture} texture - The texture.
  36177. * @param {Object} [options={}] - Optional configuration parameter.
  36178. */
  36179. updateTexture( /*texture, options = {}*/ ) { }
  36180. /**
  36181. * Generates mipmaps for the given texture
  36182. *
  36183. * @abstract
  36184. * @param {Texture} texture - The texture.
  36185. */
  36186. generateMipmaps( /*texture*/ ) { }
  36187. /**
  36188. * Destroys the GPU data for the given texture object.
  36189. *
  36190. * @abstract
  36191. * @param {Texture} texture - The texture.
  36192. */
  36193. destroyTexture( /*texture*/ ) { }
  36194. /**
  36195. * Returns texture data as a typed array.
  36196. *
  36197. * @abstract
  36198. * @param {Texture} texture - The texture to copy.
  36199. * @param {Number} x - The x coordinate of the copy origin.
  36200. * @param {Number} y - The y coordinate of the copy origin.
  36201. * @param {Number} width - The width of the copy.
  36202. * @param {Number} height - The height of the copy.
  36203. * @param {Number} faceIndex - The face index.
  36204. * @return {TypedArray} The texture data as a typed array.
  36205. */
  36206. copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  36207. /**
  36208. * Copies data of the given source texture to the given destination texture.
  36209. *
  36210. * @abstract
  36211. * @param {Texture} srcTexture - The source texture.
  36212. * @param {Texture} dstTexture - The destination texture.
  36213. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  36214. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  36215. * @param {Number} [level=0] - The mip level to copy.
  36216. */
  36217. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0*/ ) {}
  36218. /**
  36219. * Copies the current bound framebuffer to the given texture.
  36220. *
  36221. * @abstract
  36222. * @param {Texture} texture - The destination texture.
  36223. * @param {RenderContext} renderContext - The render context.
  36224. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  36225. */
  36226. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  36227. // attributes
  36228. /**
  36229. * Creates the buffer of a shader attribute.
  36230. *
  36231. * @abstract
  36232. * @param {BufferAttribute} attribute - The buffer attribute.
  36233. */
  36234. createAttribute( /*attribute*/ ) { }
  36235. /**
  36236. * Creates the buffer of an indexed shader attribute.
  36237. *
  36238. * @abstract
  36239. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  36240. */
  36241. createIndexAttribute( /*attribute*/ ) { }
  36242. /**
  36243. * Creates the buffer of a storage attribute.
  36244. *
  36245. * @abstract
  36246. * @param {BufferAttribute} attribute - The buffer attribute.
  36247. */
  36248. createStorageAttribute( /*attribute*/ ) { }
  36249. /**
  36250. * Updates the buffer of a shader attribute.
  36251. *
  36252. * @abstract
  36253. * @param {BufferAttribute} attribute - The buffer attribute to update.
  36254. */
  36255. updateAttribute( /*attribute*/ ) { }
  36256. /**
  36257. * Destroys the buffer of a shader attribute.
  36258. *
  36259. * @abstract
  36260. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  36261. */
  36262. destroyAttribute( /*attribute*/ ) { }
  36263. // canvas
  36264. /**
  36265. * Returns the backend's rendering context.
  36266. *
  36267. * @abstract
  36268. * @return {Object} The rendering context.
  36269. */
  36270. getContext() { }
  36271. /**
  36272. * Backends can use this method if they have to run
  36273. * logic when the renderer gets resized.
  36274. *
  36275. * @abstract
  36276. */
  36277. updateSize() { }
  36278. /**
  36279. * Updates the viewport with the values from the given render context.
  36280. *
  36281. * @abstract
  36282. * @param {RenderContext} renderContext - The render context.
  36283. */
  36284. updateViewport( /*renderContext*/ ) {}
  36285. // utils
  36286. /**
  36287. * Returns `true` if the given 3D object is fully occluded by other
  36288. * 3D objects in the scene. Backends must implement this method by using
  36289. * a Occlusion Query API.
  36290. *
  36291. * @abstract
  36292. * @param {RenderContext} renderContext - The render context.
  36293. * @param {Object3D} object - The 3D object to test.
  36294. * @return {Boolean} Whether the 3D object is fully occluded or not.
  36295. */
  36296. isOccluded( /*renderContext, object*/ ) {}
  36297. /**
  36298. * Resolves the time stamp for the given render context and type.
  36299. *
  36300. * @async
  36301. * @abstract
  36302. * @param {RenderContext} renderContext - The render context.
  36303. * @param {String} type - The render context.
  36304. * @return {Promise} A Promise that resolves when the time stamp has been computed.
  36305. */
  36306. async resolveTimestampAsync( /*renderContext, type*/ ) { }
  36307. /**
  36308. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  36309. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  36310. *
  36311. * @async
  36312. * @abstract
  36313. * @return {Promise} A Promise that resolves when synchronization has been finished.
  36314. */
  36315. async waitForGPU() {}
  36316. /**
  36317. * Checks if the given feature is supported by the backend.
  36318. *
  36319. * @async
  36320. * @abstract
  36321. * @param {String} name - The feature's name.
  36322. * @return {Promise<Boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  36323. */
  36324. async hasFeatureAsync( /*name*/ ) { }
  36325. /**
  36326. * Checks if the given feature is supported by the backend.
  36327. *
  36328. * @abstract
  36329. * @param {String} name - The feature's name.
  36330. * @return {Boolean} Whether the feature is supported or not.
  36331. */
  36332. hasFeature( /*name*/ ) {}
  36333. /**
  36334. * Returns the maximum anisotropy texture filtering value.
  36335. *
  36336. * @abstract
  36337. * @return {Number} The maximum anisotropy texture filtering value.
  36338. */
  36339. getMaxAnisotropy() {}
  36340. /**
  36341. * Returns the drawing buffer size.
  36342. *
  36343. * @return {Vector2} The drawing buffer size.
  36344. */
  36345. getDrawingBufferSize() {
  36346. _vector2 = _vector2 || new Vector2();
  36347. return this.renderer.getDrawingBufferSize( _vector2 );
  36348. }
  36349. /**
  36350. * Defines the scissor test.
  36351. *
  36352. * @abstract
  36353. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  36354. */
  36355. setScissorTest( /*boolean*/ ) { }
  36356. /**
  36357. * Returns the clear color and alpha into a single
  36358. * color object.
  36359. *
  36360. * @return {Color4} The clear color.
  36361. */
  36362. getClearColor() {
  36363. const renderer = this.renderer;
  36364. _color4 = _color4 || new Color4();
  36365. renderer.getClearColor( _color4 );
  36366. _color4.getRGB( _color4, this.renderer.currentColorSpace );
  36367. return _color4;
  36368. }
  36369. /**
  36370. * Returns the DOM element. If no DOM element exists, the backend
  36371. * creates a new one.
  36372. *
  36373. * @return {HTMLCanvasElement} The DOM element.
  36374. */
  36375. getDomElement() {
  36376. let domElement = this.domElement;
  36377. if ( domElement === null ) {
  36378. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  36379. // OffscreenCanvas does not have setAttribute, see #22811
  36380. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  36381. this.domElement = domElement;
  36382. }
  36383. return domElement;
  36384. }
  36385. /**
  36386. * Sets a dictionary for the given object into the
  36387. * internal data structure.
  36388. *
  36389. * @param {Object} object - The object.
  36390. * @param {Object} value - The dictionary to set.
  36391. */
  36392. set( object, value ) {
  36393. this.data.set( object, value );
  36394. }
  36395. /**
  36396. * Returns the dictionary for the given object.
  36397. *
  36398. * @param {Object} object - The object.
  36399. * @return {Object} The object's dictionary.
  36400. */
  36401. get( object ) {
  36402. let map = this.data.get( object );
  36403. if ( map === undefined ) {
  36404. map = {};
  36405. this.data.set( object, map );
  36406. }
  36407. return map;
  36408. }
  36409. /**
  36410. * Checks if the given object has a dictionary
  36411. * with data defined.
  36412. *
  36413. * @param {Object} object - The object.
  36414. * @return {Boolean} Whether a dictionary for the given object as been defined or not.
  36415. */
  36416. has( object ) {
  36417. return this.data.has( object );
  36418. }
  36419. /**
  36420. * Deletes an object from the internal data structure.
  36421. *
  36422. * @param {Object} object - The object to delete.
  36423. */
  36424. delete( object ) {
  36425. this.data.delete( object );
  36426. }
  36427. /**
  36428. * Frees internal resources.
  36429. *
  36430. * @abstract
  36431. */
  36432. dispose() { }
  36433. }
  36434. let _id$1 = 0;
  36435. class DualAttributeData {
  36436. constructor( attributeData, dualBuffer ) {
  36437. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  36438. this.type = attributeData.type;
  36439. this.bufferType = attributeData.bufferType;
  36440. this.pbo = attributeData.pbo;
  36441. this.byteLength = attributeData.byteLength;
  36442. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  36443. this.version = attributeData.version;
  36444. this.isInteger = attributeData.isInteger;
  36445. this.activeBufferIndex = 0;
  36446. this.baseId = attributeData.id;
  36447. }
  36448. get id() {
  36449. return `${ this.baseId }|${ this.activeBufferIndex }`;
  36450. }
  36451. get bufferGPU() {
  36452. return this.buffers[ this.activeBufferIndex ];
  36453. }
  36454. get transformBuffer() {
  36455. return this.buffers[ this.activeBufferIndex ^ 1 ];
  36456. }
  36457. switchBuffers() {
  36458. this.activeBufferIndex ^= 1;
  36459. }
  36460. }
  36461. class WebGLAttributeUtils {
  36462. constructor( backend ) {
  36463. this.backend = backend;
  36464. }
  36465. createAttribute( attribute, bufferType ) {
  36466. const backend = this.backend;
  36467. const { gl } = backend;
  36468. const array = attribute.array;
  36469. const usage = attribute.usage || gl.STATIC_DRAW;
  36470. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  36471. const bufferData = backend.get( bufferAttribute );
  36472. let bufferGPU = bufferData.bufferGPU;
  36473. if ( bufferGPU === undefined ) {
  36474. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  36475. bufferData.bufferGPU = bufferGPU;
  36476. bufferData.bufferType = bufferType;
  36477. bufferData.version = bufferAttribute.version;
  36478. }
  36479. //attribute.onUploadCallback();
  36480. let type;
  36481. if ( array instanceof Float32Array ) {
  36482. type = gl.FLOAT;
  36483. } else if ( array instanceof Uint16Array ) {
  36484. if ( attribute.isFloat16BufferAttribute ) {
  36485. type = gl.HALF_FLOAT;
  36486. } else {
  36487. type = gl.UNSIGNED_SHORT;
  36488. }
  36489. } else if ( array instanceof Int16Array ) {
  36490. type = gl.SHORT;
  36491. } else if ( array instanceof Uint32Array ) {
  36492. type = gl.UNSIGNED_INT;
  36493. } else if ( array instanceof Int32Array ) {
  36494. type = gl.INT;
  36495. } else if ( array instanceof Int8Array ) {
  36496. type = gl.BYTE;
  36497. } else if ( array instanceof Uint8Array ) {
  36498. type = gl.UNSIGNED_BYTE;
  36499. } else if ( array instanceof Uint8ClampedArray ) {
  36500. type = gl.UNSIGNED_BYTE;
  36501. } else {
  36502. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  36503. }
  36504. let attributeData = {
  36505. bufferGPU,
  36506. bufferType,
  36507. type,
  36508. byteLength: array.byteLength,
  36509. bytesPerElement: array.BYTES_PER_ELEMENT,
  36510. version: attribute.version,
  36511. pbo: attribute.pbo,
  36512. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  36513. id: _id$1 ++
  36514. };
  36515. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  36516. // create buffer for transform feedback use
  36517. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  36518. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  36519. }
  36520. backend.set( attribute, attributeData );
  36521. }
  36522. updateAttribute( attribute ) {
  36523. const backend = this.backend;
  36524. const { gl } = backend;
  36525. const array = attribute.array;
  36526. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  36527. const bufferData = backend.get( bufferAttribute );
  36528. const bufferType = bufferData.bufferType;
  36529. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  36530. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  36531. if ( updateRanges.length === 0 ) {
  36532. // Not using update ranges
  36533. gl.bufferSubData( bufferType, 0, array );
  36534. } else {
  36535. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  36536. const range = updateRanges[ i ];
  36537. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  36538. array, range.start, range.count );
  36539. }
  36540. bufferAttribute.clearUpdateRanges();
  36541. }
  36542. gl.bindBuffer( bufferType, null );
  36543. bufferData.version = bufferAttribute.version;
  36544. }
  36545. destroyAttribute( attribute ) {
  36546. const backend = this.backend;
  36547. const { gl } = backend;
  36548. if ( attribute.isInterleavedBufferAttribute ) {
  36549. backend.delete( attribute.data );
  36550. }
  36551. const attributeData = backend.get( attribute );
  36552. gl.deleteBuffer( attributeData.bufferGPU );
  36553. backend.delete( attribute );
  36554. }
  36555. async getArrayBufferAsync( attribute ) {
  36556. const backend = this.backend;
  36557. const { gl } = backend;
  36558. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  36559. const { bufferGPU } = backend.get( bufferAttribute );
  36560. const array = attribute.array;
  36561. const byteLength = array.byteLength;
  36562. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  36563. const writeBuffer = gl.createBuffer();
  36564. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  36565. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  36566. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  36567. await backend.utils._clientWaitAsync();
  36568. const dstBuffer = new attribute.array.constructor( array.length );
  36569. // Ensure the buffer is bound before reading
  36570. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  36571. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  36572. gl.deleteBuffer( writeBuffer );
  36573. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  36574. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  36575. return dstBuffer.buffer;
  36576. }
  36577. _createBuffer( gl, bufferType, array, usage ) {
  36578. const bufferGPU = gl.createBuffer();
  36579. gl.bindBuffer( bufferType, bufferGPU );
  36580. gl.bufferData( bufferType, array, usage );
  36581. gl.bindBuffer( bufferType, null );
  36582. return bufferGPU;
  36583. }
  36584. }
  36585. let initialized$1 = false, equationToGL, factorToGL;
  36586. class WebGLState {
  36587. constructor( backend ) {
  36588. this.backend = backend;
  36589. this.gl = this.backend.gl;
  36590. this.enabled = {};
  36591. this.currentFlipSided = null;
  36592. this.currentCullFace = null;
  36593. this.currentProgram = null;
  36594. this.currentBlendingEnabled = false;
  36595. this.currentBlending = null;
  36596. this.currentBlendSrc = null;
  36597. this.currentBlendDst = null;
  36598. this.currentBlendSrcAlpha = null;
  36599. this.currentBlendDstAlpha = null;
  36600. this.currentPremultipledAlpha = null;
  36601. this.currentPolygonOffsetFactor = null;
  36602. this.currentPolygonOffsetUnits = null;
  36603. this.currentColorMask = null;
  36604. this.currentDepthFunc = null;
  36605. this.currentDepthMask = null;
  36606. this.currentStencilFunc = null;
  36607. this.currentStencilRef = null;
  36608. this.currentStencilFuncMask = null;
  36609. this.currentStencilFail = null;
  36610. this.currentStencilZFail = null;
  36611. this.currentStencilZPass = null;
  36612. this.currentStencilMask = null;
  36613. this.currentLineWidth = null;
  36614. this.currentClippingPlanes = 0;
  36615. this.currentBoundFramebuffers = {};
  36616. this.currentDrawbuffers = new WeakMap();
  36617. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  36618. this.currentTextureSlot = null;
  36619. this.currentBoundTextures = {};
  36620. this.currentBoundBufferBases = {};
  36621. if ( initialized$1 === false ) {
  36622. this._init( this.gl );
  36623. initialized$1 = true;
  36624. }
  36625. }
  36626. _init( gl ) {
  36627. // Store only WebGL constants here.
  36628. equationToGL = {
  36629. [ AddEquation ]: gl.FUNC_ADD,
  36630. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  36631. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  36632. };
  36633. factorToGL = {
  36634. [ ZeroFactor ]: gl.ZERO,
  36635. [ OneFactor ]: gl.ONE,
  36636. [ SrcColorFactor ]: gl.SRC_COLOR,
  36637. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  36638. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  36639. [ DstColorFactor ]: gl.DST_COLOR,
  36640. [ DstAlphaFactor ]: gl.DST_ALPHA,
  36641. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  36642. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  36643. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  36644. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  36645. };
  36646. }
  36647. enable( id ) {
  36648. const { enabled } = this;
  36649. if ( enabled[ id ] !== true ) {
  36650. this.gl.enable( id );
  36651. enabled[ id ] = true;
  36652. }
  36653. }
  36654. disable( id ) {
  36655. const { enabled } = this;
  36656. if ( enabled[ id ] !== false ) {
  36657. this.gl.disable( id );
  36658. enabled[ id ] = false;
  36659. }
  36660. }
  36661. setFlipSided( flipSided ) {
  36662. if ( this.currentFlipSided !== flipSided ) {
  36663. const { gl } = this;
  36664. if ( flipSided ) {
  36665. gl.frontFace( gl.CW );
  36666. } else {
  36667. gl.frontFace( gl.CCW );
  36668. }
  36669. this.currentFlipSided = flipSided;
  36670. }
  36671. }
  36672. setCullFace( cullFace ) {
  36673. const { gl } = this;
  36674. if ( cullFace !== CullFaceNone ) {
  36675. this.enable( gl.CULL_FACE );
  36676. if ( cullFace !== this.currentCullFace ) {
  36677. if ( cullFace === CullFaceBack ) {
  36678. gl.cullFace( gl.BACK );
  36679. } else if ( cullFace === CullFaceFront ) {
  36680. gl.cullFace( gl.FRONT );
  36681. } else {
  36682. gl.cullFace( gl.FRONT_AND_BACK );
  36683. }
  36684. }
  36685. } else {
  36686. this.disable( gl.CULL_FACE );
  36687. }
  36688. this.currentCullFace = cullFace;
  36689. }
  36690. setLineWidth( width ) {
  36691. const { currentLineWidth, gl } = this;
  36692. if ( width !== currentLineWidth ) {
  36693. gl.lineWidth( width );
  36694. this.currentLineWidth = width;
  36695. }
  36696. }
  36697. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  36698. const { gl } = this;
  36699. if ( blending === NoBlending ) {
  36700. if ( this.currentBlendingEnabled === true ) {
  36701. this.disable( gl.BLEND );
  36702. this.currentBlendingEnabled = false;
  36703. }
  36704. return;
  36705. }
  36706. if ( this.currentBlendingEnabled === false ) {
  36707. this.enable( gl.BLEND );
  36708. this.currentBlendingEnabled = true;
  36709. }
  36710. if ( blending !== CustomBlending ) {
  36711. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  36712. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  36713. gl.blendEquation( gl.FUNC_ADD );
  36714. this.currentBlendEquation = AddEquation;
  36715. this.currentBlendEquationAlpha = AddEquation;
  36716. }
  36717. if ( premultipliedAlpha ) {
  36718. switch ( blending ) {
  36719. case NormalBlending:
  36720. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  36721. break;
  36722. case AdditiveBlending:
  36723. gl.blendFunc( gl.ONE, gl.ONE );
  36724. break;
  36725. case SubtractiveBlending:
  36726. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  36727. break;
  36728. case MultiplyBlending:
  36729. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  36730. break;
  36731. default:
  36732. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  36733. break;
  36734. }
  36735. } else {
  36736. switch ( blending ) {
  36737. case NormalBlending:
  36738. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  36739. break;
  36740. case AdditiveBlending:
  36741. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  36742. break;
  36743. case SubtractiveBlending:
  36744. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  36745. break;
  36746. case MultiplyBlending:
  36747. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  36748. break;
  36749. default:
  36750. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  36751. break;
  36752. }
  36753. }
  36754. this.currentBlendSrc = null;
  36755. this.currentBlendDst = null;
  36756. this.currentBlendSrcAlpha = null;
  36757. this.currentBlendDstAlpha = null;
  36758. this.currentBlending = blending;
  36759. this.currentPremultipledAlpha = premultipliedAlpha;
  36760. }
  36761. return;
  36762. }
  36763. // custom blending
  36764. blendEquationAlpha = blendEquationAlpha || blendEquation;
  36765. blendSrcAlpha = blendSrcAlpha || blendSrc;
  36766. blendDstAlpha = blendDstAlpha || blendDst;
  36767. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  36768. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  36769. this.currentBlendEquation = blendEquation;
  36770. this.currentBlendEquationAlpha = blendEquationAlpha;
  36771. }
  36772. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  36773. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  36774. this.currentBlendSrc = blendSrc;
  36775. this.currentBlendDst = blendDst;
  36776. this.currentBlendSrcAlpha = blendSrcAlpha;
  36777. this.currentBlendDstAlpha = blendDstAlpha;
  36778. }
  36779. this.currentBlending = blending;
  36780. this.currentPremultipledAlpha = false;
  36781. }
  36782. setColorMask( colorMask ) {
  36783. if ( this.currentColorMask !== colorMask ) {
  36784. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  36785. this.currentColorMask = colorMask;
  36786. }
  36787. }
  36788. setDepthTest( depthTest ) {
  36789. const { gl } = this;
  36790. if ( depthTest ) {
  36791. this.enable( gl.DEPTH_TEST );
  36792. } else {
  36793. this.disable( gl.DEPTH_TEST );
  36794. }
  36795. }
  36796. setDepthMask( depthMask ) {
  36797. if ( this.currentDepthMask !== depthMask ) {
  36798. this.gl.depthMask( depthMask );
  36799. this.currentDepthMask = depthMask;
  36800. }
  36801. }
  36802. setDepthFunc( depthFunc ) {
  36803. if ( this.currentDepthFunc !== depthFunc ) {
  36804. const { gl } = this;
  36805. switch ( depthFunc ) {
  36806. case NeverDepth:
  36807. gl.depthFunc( gl.NEVER );
  36808. break;
  36809. case AlwaysDepth:
  36810. gl.depthFunc( gl.ALWAYS );
  36811. break;
  36812. case LessDepth:
  36813. gl.depthFunc( gl.LESS );
  36814. break;
  36815. case LessEqualDepth:
  36816. gl.depthFunc( gl.LEQUAL );
  36817. break;
  36818. case EqualDepth:
  36819. gl.depthFunc( gl.EQUAL );
  36820. break;
  36821. case GreaterEqualDepth:
  36822. gl.depthFunc( gl.GEQUAL );
  36823. break;
  36824. case GreaterDepth:
  36825. gl.depthFunc( gl.GREATER );
  36826. break;
  36827. case NotEqualDepth:
  36828. gl.depthFunc( gl.NOTEQUAL );
  36829. break;
  36830. default:
  36831. gl.depthFunc( gl.LEQUAL );
  36832. }
  36833. this.currentDepthFunc = depthFunc;
  36834. }
  36835. }
  36836. setStencilTest( stencilTest ) {
  36837. const { gl } = this;
  36838. if ( stencilTest ) {
  36839. this.enable( gl.STENCIL_TEST );
  36840. } else {
  36841. this.disable( gl.STENCIL_TEST );
  36842. }
  36843. }
  36844. setStencilMask( stencilMask ) {
  36845. if ( this.currentStencilMask !== stencilMask ) {
  36846. this.gl.stencilMask( stencilMask );
  36847. this.currentStencilMask = stencilMask;
  36848. }
  36849. }
  36850. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  36851. if ( this.currentStencilFunc !== stencilFunc ||
  36852. this.currentStencilRef !== stencilRef ||
  36853. this.currentStencilFuncMask !== stencilMask ) {
  36854. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  36855. this.currentStencilFunc = stencilFunc;
  36856. this.currentStencilRef = stencilRef;
  36857. this.currentStencilFuncMask = stencilMask;
  36858. }
  36859. }
  36860. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  36861. if ( this.currentStencilFail !== stencilFail ||
  36862. this.currentStencilZFail !== stencilZFail ||
  36863. this.currentStencilZPass !== stencilZPass ) {
  36864. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  36865. this.currentStencilFail = stencilFail;
  36866. this.currentStencilZFail = stencilZFail;
  36867. this.currentStencilZPass = stencilZPass;
  36868. }
  36869. }
  36870. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  36871. const { gl } = this;
  36872. material.side === DoubleSide
  36873. ? this.disable( gl.CULL_FACE )
  36874. : this.enable( gl.CULL_FACE );
  36875. let flipSided = ( material.side === BackSide );
  36876. if ( frontFaceCW ) flipSided = ! flipSided;
  36877. this.setFlipSided( flipSided );
  36878. ( material.blending === NormalBlending && material.transparent === false )
  36879. ? this.setBlending( NoBlending )
  36880. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  36881. this.setDepthFunc( material.depthFunc );
  36882. this.setDepthTest( material.depthTest );
  36883. this.setDepthMask( material.depthWrite );
  36884. this.setColorMask( material.colorWrite );
  36885. const stencilWrite = material.stencilWrite;
  36886. this.setStencilTest( stencilWrite );
  36887. if ( stencilWrite ) {
  36888. this.setStencilMask( material.stencilWriteMask );
  36889. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  36890. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  36891. }
  36892. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  36893. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  36894. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  36895. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  36896. if ( hardwareClippingPlanes > 0 ) {
  36897. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  36898. const CLIP_DISTANCE0_WEBGL = 0x3000;
  36899. for ( let i = 0; i < 8; i ++ ) {
  36900. if ( i < hardwareClippingPlanes ) {
  36901. this.enable( CLIP_DISTANCE0_WEBGL + i );
  36902. } else {
  36903. this.disable( CLIP_DISTANCE0_WEBGL + i );
  36904. }
  36905. }
  36906. }
  36907. }
  36908. }
  36909. setPolygonOffset( polygonOffset, factor, units ) {
  36910. const { gl } = this;
  36911. if ( polygonOffset ) {
  36912. this.enable( gl.POLYGON_OFFSET_FILL );
  36913. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  36914. gl.polygonOffset( factor, units );
  36915. this.currentPolygonOffsetFactor = factor;
  36916. this.currentPolygonOffsetUnits = units;
  36917. }
  36918. } else {
  36919. this.disable( gl.POLYGON_OFFSET_FILL );
  36920. }
  36921. }
  36922. useProgram( program ) {
  36923. if ( this.currentProgram !== program ) {
  36924. this.gl.useProgram( program );
  36925. this.currentProgram = program;
  36926. return true;
  36927. }
  36928. return false;
  36929. }
  36930. // framebuffer
  36931. bindFramebuffer( target, framebuffer ) {
  36932. const { gl, currentBoundFramebuffers } = this;
  36933. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  36934. gl.bindFramebuffer( target, framebuffer );
  36935. currentBoundFramebuffers[ target ] = framebuffer;
  36936. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  36937. if ( target === gl.DRAW_FRAMEBUFFER ) {
  36938. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  36939. }
  36940. if ( target === gl.FRAMEBUFFER ) {
  36941. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  36942. }
  36943. return true;
  36944. }
  36945. return false;
  36946. }
  36947. drawBuffers( renderContext, framebuffer ) {
  36948. const { gl } = this;
  36949. let drawBuffers = [];
  36950. let needsUpdate = false;
  36951. if ( renderContext.textures !== null ) {
  36952. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  36953. if ( drawBuffers === undefined ) {
  36954. drawBuffers = [];
  36955. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  36956. }
  36957. const textures = renderContext.textures;
  36958. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  36959. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  36960. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  36961. }
  36962. drawBuffers.length = textures.length;
  36963. needsUpdate = true;
  36964. }
  36965. } else {
  36966. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  36967. drawBuffers[ 0 ] = gl.BACK;
  36968. needsUpdate = true;
  36969. }
  36970. }
  36971. if ( needsUpdate ) {
  36972. gl.drawBuffers( drawBuffers );
  36973. }
  36974. }
  36975. // texture
  36976. activeTexture( webglSlot ) {
  36977. const { gl, currentTextureSlot, maxTextures } = this;
  36978. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  36979. if ( currentTextureSlot !== webglSlot ) {
  36980. gl.activeTexture( webglSlot );
  36981. this.currentTextureSlot = webglSlot;
  36982. }
  36983. }
  36984. bindTexture( webglType, webglTexture, webglSlot ) {
  36985. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  36986. if ( webglSlot === undefined ) {
  36987. if ( currentTextureSlot === null ) {
  36988. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  36989. } else {
  36990. webglSlot = currentTextureSlot;
  36991. }
  36992. }
  36993. let boundTexture = currentBoundTextures[ webglSlot ];
  36994. if ( boundTexture === undefined ) {
  36995. boundTexture = { type: undefined, texture: undefined };
  36996. currentBoundTextures[ webglSlot ] = boundTexture;
  36997. }
  36998. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  36999. if ( currentTextureSlot !== webglSlot ) {
  37000. gl.activeTexture( webglSlot );
  37001. this.currentTextureSlot = webglSlot;
  37002. }
  37003. gl.bindTexture( webglType, webglTexture );
  37004. boundTexture.type = webglType;
  37005. boundTexture.texture = webglTexture;
  37006. }
  37007. }
  37008. bindBufferBase( target, index, buffer ) {
  37009. const { gl } = this;
  37010. const key = `${target}-${index}`;
  37011. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  37012. gl.bindBufferBase( target, index, buffer );
  37013. this.currentBoundBufferBases[ key ] = buffer;
  37014. return true;
  37015. }
  37016. return false;
  37017. }
  37018. unbindTexture() {
  37019. const { gl, currentTextureSlot, currentBoundTextures } = this;
  37020. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  37021. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  37022. gl.bindTexture( boundTexture.type, null );
  37023. boundTexture.type = undefined;
  37024. boundTexture.texture = undefined;
  37025. }
  37026. }
  37027. }
  37028. class WebGLUtils {
  37029. constructor( backend ) {
  37030. this.backend = backend;
  37031. this.gl = this.backend.gl;
  37032. this.extensions = backend.extensions;
  37033. }
  37034. convert( p, colorSpace = NoColorSpace ) {
  37035. const { gl, extensions } = this;
  37036. let extension;
  37037. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  37038. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  37039. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  37040. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  37041. if ( p === ByteType ) return gl.BYTE;
  37042. if ( p === ShortType ) return gl.SHORT;
  37043. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  37044. if ( p === IntType ) return gl.INT;
  37045. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  37046. if ( p === FloatType ) return gl.FLOAT;
  37047. if ( p === HalfFloatType ) {
  37048. return gl.HALF_FLOAT;
  37049. }
  37050. if ( p === AlphaFormat ) return gl.ALPHA;
  37051. if ( p === RGBFormat ) return gl.RGB;
  37052. if ( p === RGBAFormat ) return gl.RGBA;
  37053. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  37054. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  37055. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  37056. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  37057. // WebGL2 formats.
  37058. if ( p === RedFormat ) return gl.RED;
  37059. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  37060. if ( p === RGFormat ) return gl.RG;
  37061. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  37062. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  37063. // S3TC
  37064. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  37065. if ( colorSpace === SRGBColorSpace ) {
  37066. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  37067. if ( extension !== null ) {
  37068. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  37069. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  37070. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  37071. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  37072. } else {
  37073. return null;
  37074. }
  37075. } else {
  37076. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  37077. if ( extension !== null ) {
  37078. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  37079. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  37080. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  37081. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  37082. } else {
  37083. return null;
  37084. }
  37085. }
  37086. }
  37087. // PVRTC
  37088. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  37089. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  37090. if ( extension !== null ) {
  37091. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  37092. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  37093. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  37094. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  37095. } else {
  37096. return null;
  37097. }
  37098. }
  37099. // ETC
  37100. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  37101. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  37102. if ( extension !== null ) {
  37103. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  37104. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  37105. } else {
  37106. return null;
  37107. }
  37108. }
  37109. // ASTC
  37110. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  37111. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  37112. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  37113. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  37114. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  37115. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  37116. if ( extension !== null ) {
  37117. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  37118. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  37119. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  37120. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  37121. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  37122. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  37123. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  37124. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  37125. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  37126. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  37127. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  37128. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  37129. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  37130. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  37131. } else {
  37132. return null;
  37133. }
  37134. }
  37135. // BPTC
  37136. if ( p === RGBA_BPTC_Format ) {
  37137. extension = extensions.get( 'EXT_texture_compression_bptc' );
  37138. if ( extension !== null ) {
  37139. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  37140. } else {
  37141. return null;
  37142. }
  37143. }
  37144. // RGTC
  37145. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  37146. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  37147. if ( extension !== null ) {
  37148. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  37149. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  37150. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  37151. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  37152. } else {
  37153. return null;
  37154. }
  37155. }
  37156. //
  37157. if ( p === UnsignedInt248Type ) {
  37158. return gl.UNSIGNED_INT_24_8;
  37159. }
  37160. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  37161. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  37162. }
  37163. _clientWaitAsync() {
  37164. const { gl } = this;
  37165. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  37166. gl.flush();
  37167. return new Promise( ( resolve, reject ) => {
  37168. function test() {
  37169. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  37170. if ( res === gl.WAIT_FAILED ) {
  37171. gl.deleteSync( sync );
  37172. reject();
  37173. return;
  37174. }
  37175. if ( res === gl.TIMEOUT_EXPIRED ) {
  37176. requestAnimationFrame( test );
  37177. return;
  37178. }
  37179. gl.deleteSync( sync );
  37180. resolve();
  37181. }
  37182. test();
  37183. } );
  37184. }
  37185. }
  37186. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  37187. class WebGLTextureUtils {
  37188. constructor( backend ) {
  37189. this.backend = backend;
  37190. this.gl = backend.gl;
  37191. this.extensions = backend.extensions;
  37192. this.defaultTextures = {};
  37193. if ( initialized === false ) {
  37194. this._init( this.gl );
  37195. initialized = true;
  37196. }
  37197. }
  37198. _init( gl ) {
  37199. // Store only WebGL constants here.
  37200. wrappingToGL = {
  37201. [ RepeatWrapping ]: gl.REPEAT,
  37202. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  37203. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  37204. };
  37205. filterToGL = {
  37206. [ NearestFilter ]: gl.NEAREST,
  37207. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  37208. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  37209. [ LinearFilter ]: gl.LINEAR,
  37210. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  37211. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  37212. };
  37213. compareToGL = {
  37214. [ NeverCompare ]: gl.NEVER,
  37215. [ AlwaysCompare ]: gl.ALWAYS,
  37216. [ LessCompare ]: gl.LESS,
  37217. [ LessEqualCompare ]: gl.LEQUAL,
  37218. [ EqualCompare ]: gl.EQUAL,
  37219. [ GreaterEqualCompare ]: gl.GEQUAL,
  37220. [ GreaterCompare ]: gl.GREATER,
  37221. [ NotEqualCompare ]: gl.NOTEQUAL
  37222. };
  37223. }
  37224. filterFallback( f ) {
  37225. const { gl } = this;
  37226. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  37227. return gl.NEAREST;
  37228. }
  37229. return gl.LINEAR;
  37230. }
  37231. getGLTextureType( texture ) {
  37232. const { gl } = this;
  37233. let glTextureType;
  37234. if ( texture.isCubeTexture === true ) {
  37235. glTextureType = gl.TEXTURE_CUBE_MAP;
  37236. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  37237. glTextureType = gl.TEXTURE_2D_ARRAY;
  37238. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  37239. glTextureType = gl.TEXTURE_3D;
  37240. } else {
  37241. glTextureType = gl.TEXTURE_2D;
  37242. }
  37243. return glTextureType;
  37244. }
  37245. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  37246. const { gl, extensions } = this;
  37247. if ( internalFormatName !== null ) {
  37248. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  37249. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  37250. }
  37251. let internalFormat = glFormat;
  37252. if ( glFormat === gl.RED ) {
  37253. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  37254. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  37255. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  37256. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  37257. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  37258. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  37259. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  37260. if ( glType === gl.INT ) internalFormat = gl.R32I;
  37261. }
  37262. if ( glFormat === gl.RED_INTEGER ) {
  37263. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  37264. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  37265. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  37266. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  37267. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  37268. if ( glType === gl.INT ) internalFormat = gl.R32I;
  37269. }
  37270. if ( glFormat === gl.RG ) {
  37271. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  37272. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  37273. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  37274. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  37275. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  37276. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  37277. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  37278. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  37279. }
  37280. if ( glFormat === gl.RG_INTEGER ) {
  37281. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  37282. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  37283. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  37284. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  37285. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  37286. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  37287. }
  37288. if ( glFormat === gl.RGB ) {
  37289. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  37290. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  37291. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  37292. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  37293. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  37294. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  37295. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  37296. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  37297. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  37298. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  37299. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  37300. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  37301. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  37302. }
  37303. if ( glFormat === gl.RGB_INTEGER ) {
  37304. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  37305. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  37306. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  37307. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  37308. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  37309. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  37310. }
  37311. if ( glFormat === gl.RGBA ) {
  37312. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  37313. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  37314. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  37315. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  37316. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  37317. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  37318. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  37319. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  37320. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  37321. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  37322. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  37323. }
  37324. if ( glFormat === gl.RGBA_INTEGER ) {
  37325. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  37326. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  37327. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  37328. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  37329. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  37330. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  37331. }
  37332. if ( glFormat === gl.DEPTH_COMPONENT ) {
  37333. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  37334. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  37335. }
  37336. if ( glFormat === gl.DEPTH_STENCIL ) {
  37337. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  37338. }
  37339. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  37340. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  37341. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  37342. extensions.get( 'EXT_color_buffer_float' );
  37343. }
  37344. return internalFormat;
  37345. }
  37346. setTextureParameters( textureType, texture ) {
  37347. const { gl, extensions, backend } = this;
  37348. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  37349. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  37350. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  37351. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  37352. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  37353. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  37354. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  37355. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  37356. }
  37357. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  37358. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  37359. // follow WebGPU backend mapping for texture filtering
  37360. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  37361. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  37362. if ( texture.compareFunction ) {
  37363. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  37364. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  37365. }
  37366. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  37367. if ( texture.magFilter === NearestFilter ) return;
  37368. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  37369. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  37370. if ( texture.anisotropy > 1 ) {
  37371. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  37372. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  37373. }
  37374. }
  37375. }
  37376. createDefaultTexture( texture ) {
  37377. const { gl, backend, defaultTextures } = this;
  37378. const glTextureType = this.getGLTextureType( texture );
  37379. let textureGPU = defaultTextures[ glTextureType ];
  37380. if ( textureGPU === undefined ) {
  37381. textureGPU = gl.createTexture();
  37382. backend.state.bindTexture( glTextureType, textureGPU );
  37383. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  37384. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  37385. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  37386. defaultTextures[ glTextureType ] = textureGPU;
  37387. }
  37388. backend.set( texture, {
  37389. textureGPU,
  37390. glTextureType,
  37391. isDefault: true
  37392. } );
  37393. }
  37394. createTexture( texture, options ) {
  37395. const { gl, backend } = this;
  37396. const { levels, width, height, depth } = options;
  37397. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  37398. const glType = backend.utils.convert( texture.type );
  37399. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  37400. const textureGPU = gl.createTexture();
  37401. const glTextureType = this.getGLTextureType( texture );
  37402. backend.state.bindTexture( glTextureType, textureGPU );
  37403. this.setTextureParameters( glTextureType, texture );
  37404. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  37405. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  37406. } else if ( texture.isData3DTexture ) {
  37407. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  37408. } else if ( ! texture.isVideoTexture ) {
  37409. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  37410. }
  37411. backend.set( texture, {
  37412. textureGPU,
  37413. glTextureType,
  37414. glFormat,
  37415. glType,
  37416. glInternalFormat
  37417. } );
  37418. }
  37419. copyBufferToTexture( buffer, texture ) {
  37420. const { gl, backend } = this;
  37421. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  37422. const { width, height } = texture.source.data;
  37423. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  37424. backend.state.bindTexture( glTextureType, textureGPU );
  37425. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  37426. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  37427. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  37428. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  37429. backend.state.unbindTexture();
  37430. // debug
  37431. // const framebuffer = gl.createFramebuffer();
  37432. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  37433. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  37434. // const readout = new Float32Array( width * height * 4 );
  37435. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  37436. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  37437. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  37438. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  37439. // console.log( readout );
  37440. }
  37441. updateTexture( texture, options ) {
  37442. const { gl } = this;
  37443. const { width, height } = options;
  37444. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  37445. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  37446. return;
  37447. const getImage = ( source ) => {
  37448. if ( source.isDataTexture ) {
  37449. return source.image.data;
  37450. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  37451. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  37452. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  37453. source instanceof OffscreenCanvas ) {
  37454. return source;
  37455. }
  37456. return source.data;
  37457. };
  37458. this.backend.state.bindTexture( glTextureType, textureGPU );
  37459. this.setTextureParameters( glTextureType, texture );
  37460. if ( texture.isCompressedTexture ) {
  37461. const mipmaps = texture.mipmaps;
  37462. const image = options.image;
  37463. for ( let i = 0; i < mipmaps.length; i ++ ) {
  37464. const mipmap = mipmaps[ i ];
  37465. if ( texture.isCompressedArrayTexture ) {
  37466. if ( texture.format !== gl.RGBA ) {
  37467. if ( glFormat !== null ) {
  37468. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  37469. } else {
  37470. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  37471. }
  37472. } else {
  37473. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  37474. }
  37475. } else {
  37476. if ( glFormat !== null ) {
  37477. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  37478. } else {
  37479. console.warn( 'Unsupported compressed texture format' );
  37480. }
  37481. }
  37482. }
  37483. } else if ( texture.isCubeTexture ) {
  37484. const images = options.images;
  37485. for ( let i = 0; i < 6; i ++ ) {
  37486. const image = getImage( images[ i ] );
  37487. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  37488. }
  37489. } else if ( texture.isDataArrayTexture ) {
  37490. const image = options.image;
  37491. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  37492. } else if ( texture.isData3DTexture ) {
  37493. const image = options.image;
  37494. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  37495. } else if ( texture.isVideoTexture ) {
  37496. texture.update();
  37497. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  37498. } else {
  37499. const image = getImage( options.image );
  37500. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  37501. }
  37502. }
  37503. generateMipmaps( texture ) {
  37504. const { gl, backend } = this;
  37505. const { textureGPU, glTextureType } = backend.get( texture );
  37506. backend.state.bindTexture( glTextureType, textureGPU );
  37507. gl.generateMipmap( glTextureType );
  37508. }
  37509. deallocateRenderBuffers( renderTarget ) {
  37510. const { gl, backend } = this;
  37511. // remove framebuffer reference
  37512. if ( renderTarget ) {
  37513. const renderContextData = backend.get( renderTarget );
  37514. renderContextData.renderBufferStorageSetup = undefined;
  37515. if ( renderContextData.framebuffers ) {
  37516. for ( const cacheKey in renderContextData.framebuffers ) {
  37517. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  37518. }
  37519. delete renderContextData.framebuffers;
  37520. }
  37521. if ( renderContextData.depthRenderbuffer ) {
  37522. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  37523. delete renderContextData.depthRenderbuffer;
  37524. }
  37525. if ( renderContextData.stencilRenderbuffer ) {
  37526. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  37527. delete renderContextData.stencilRenderbuffer;
  37528. }
  37529. if ( renderContextData.msaaFrameBuffer ) {
  37530. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  37531. delete renderContextData.msaaFrameBuffer;
  37532. }
  37533. if ( renderContextData.msaaRenderbuffers ) {
  37534. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  37535. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  37536. }
  37537. delete renderContextData.msaaRenderbuffers;
  37538. }
  37539. }
  37540. }
  37541. destroyTexture( texture ) {
  37542. const { gl, backend } = this;
  37543. const { textureGPU, renderTarget } = backend.get( texture );
  37544. this.deallocateRenderBuffers( renderTarget );
  37545. gl.deleteTexture( textureGPU );
  37546. backend.delete( texture );
  37547. }
  37548. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  37549. const { gl, backend } = this;
  37550. const { state } = this.backend;
  37551. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  37552. let width, height, minX, minY;
  37553. let dstX, dstY;
  37554. if ( srcRegion !== null ) {
  37555. width = srcRegion.max.x - srcRegion.min.x;
  37556. height = srcRegion.max.y - srcRegion.min.y;
  37557. minX = srcRegion.min.x;
  37558. minY = srcRegion.min.y;
  37559. } else {
  37560. width = srcTexture.image.width;
  37561. height = srcTexture.image.height;
  37562. minX = 0;
  37563. minY = 0;
  37564. }
  37565. if ( dstPosition !== null ) {
  37566. dstX = dstPosition.x;
  37567. dstY = dstPosition.y;
  37568. } else {
  37569. dstX = 0;
  37570. dstY = 0;
  37571. }
  37572. state.bindTexture( glTextureType, dstTextureGPU );
  37573. // As another texture upload may have changed pixelStorei
  37574. // parameters, make sure they are correct for the dstTexture
  37575. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  37576. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  37577. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  37578. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  37579. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  37580. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  37581. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  37582. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  37583. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  37584. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  37585. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  37586. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  37587. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  37588. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  37589. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  37590. const srcTextureData = backend.get( srcTexture );
  37591. const dstTextureData = backend.get( dstTexture );
  37592. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  37593. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  37594. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  37595. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  37596. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  37597. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  37598. let mask = gl.COLOR_BUFFER_BIT;
  37599. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  37600. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  37601. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  37602. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  37603. } else {
  37604. if ( srcTexture.isDataTexture ) {
  37605. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  37606. } else {
  37607. if ( srcTexture.isCompressedTexture ) {
  37608. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  37609. } else {
  37610. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  37611. }
  37612. }
  37613. }
  37614. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  37615. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  37616. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  37617. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  37618. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  37619. // Generate mipmaps only when copying level 0
  37620. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  37621. state.unbindTexture();
  37622. }
  37623. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  37624. const { gl } = this;
  37625. const { state } = this.backend;
  37626. const { textureGPU } = this.backend.get( texture );
  37627. const { x, y, z: width, w: height } = rectangle;
  37628. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  37629. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  37630. if ( requireDrawFrameBuffer ) {
  37631. const partial = ( x !== 0 || y !== 0 );
  37632. let mask;
  37633. let attachment;
  37634. if ( texture.isDepthTexture === true ) {
  37635. mask = gl.DEPTH_BUFFER_BIT;
  37636. attachment = gl.DEPTH_ATTACHMENT;
  37637. if ( renderContext.stencil ) {
  37638. mask |= gl.STENCIL_BUFFER_BIT;
  37639. }
  37640. } else {
  37641. mask = gl.COLOR_BUFFER_BIT;
  37642. attachment = gl.COLOR_ATTACHMENT0;
  37643. }
  37644. if ( partial ) {
  37645. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  37646. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  37647. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  37648. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  37649. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  37650. const flippedY = srcHeight - y - height;
  37651. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  37652. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  37653. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  37654. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  37655. state.unbindTexture();
  37656. } else {
  37657. const fb = gl.createFramebuffer();
  37658. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  37659. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  37660. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  37661. gl.deleteFramebuffer( fb );
  37662. }
  37663. } else {
  37664. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  37665. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  37666. state.unbindTexture();
  37667. }
  37668. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  37669. this.backend._setFramebuffer( renderContext );
  37670. }
  37671. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  37672. setupRenderBufferStorage( renderbuffer, renderContext ) {
  37673. const { gl } = this;
  37674. const renderTarget = renderContext.renderTarget;
  37675. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  37676. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  37677. if ( depthBuffer && ! stencilBuffer ) {
  37678. let glInternalFormat = gl.DEPTH_COMPONENT24;
  37679. if ( samples > 0 ) {
  37680. if ( depthTexture && depthTexture.isDepthTexture ) {
  37681. if ( depthTexture.type === gl.FLOAT ) {
  37682. glInternalFormat = gl.DEPTH_COMPONENT32F;
  37683. }
  37684. }
  37685. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  37686. } else {
  37687. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  37688. }
  37689. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  37690. } else if ( depthBuffer && stencilBuffer ) {
  37691. if ( samples > 0 ) {
  37692. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  37693. } else {
  37694. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  37695. }
  37696. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  37697. }
  37698. }
  37699. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  37700. const { backend, gl } = this;
  37701. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  37702. const fb = gl.createFramebuffer();
  37703. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  37704. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  37705. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  37706. const typedArrayType = this._getTypedArrayType( glType );
  37707. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  37708. const elementCount = width * height;
  37709. const byteLength = elementCount * bytesPerTexel;
  37710. const buffer = gl.createBuffer();
  37711. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  37712. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  37713. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  37714. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  37715. await backend.utils._clientWaitAsync();
  37716. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  37717. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  37718. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  37719. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  37720. gl.deleteFramebuffer( fb );
  37721. return dstBuffer;
  37722. }
  37723. _getTypedArrayType( glType ) {
  37724. const { gl } = this;
  37725. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  37726. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  37727. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  37728. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  37729. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  37730. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  37731. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  37732. if ( glType === gl.FLOAT ) return Float32Array;
  37733. throw new Error( `Unsupported WebGL type: ${glType}` );
  37734. }
  37735. _getBytesPerTexel( glType, glFormat ) {
  37736. const { gl } = this;
  37737. let bytesPerComponent = 0;
  37738. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  37739. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  37740. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  37741. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  37742. glType === gl.UNSIGNED_SHORT ||
  37743. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  37744. if ( glType === gl.UNSIGNED_INT ||
  37745. glType === gl.FLOAT ) bytesPerComponent = 4;
  37746. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  37747. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  37748. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  37749. }
  37750. }
  37751. class WebGLExtensions {
  37752. constructor( backend ) {
  37753. this.backend = backend;
  37754. this.gl = this.backend.gl;
  37755. this.availableExtensions = this.gl.getSupportedExtensions();
  37756. this.extensions = {};
  37757. }
  37758. get( name ) {
  37759. let extension = this.extensions[ name ];
  37760. if ( extension === undefined ) {
  37761. extension = this.gl.getExtension( name );
  37762. this.extensions[ name ] = extension;
  37763. }
  37764. return extension;
  37765. }
  37766. has( name ) {
  37767. return this.availableExtensions.includes( name );
  37768. }
  37769. }
  37770. class WebGLCapabilities {
  37771. constructor( backend ) {
  37772. this.backend = backend;
  37773. this.maxAnisotropy = null;
  37774. }
  37775. getMaxAnisotropy() {
  37776. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  37777. const gl = this.backend.gl;
  37778. const extensions = this.backend.extensions;
  37779. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  37780. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  37781. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  37782. } else {
  37783. this.maxAnisotropy = 0;
  37784. }
  37785. return this.maxAnisotropy;
  37786. }
  37787. }
  37788. const GLFeatureName = {
  37789. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  37790. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  37791. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  37792. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  37793. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  37794. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  37795. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  37796. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  37797. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  37798. };
  37799. class WebGLBufferRenderer {
  37800. constructor( backend ) {
  37801. this.gl = backend.gl;
  37802. this.extensions = backend.extensions;
  37803. this.info = backend.renderer.info;
  37804. this.mode = null;
  37805. this.index = 0;
  37806. this.type = null;
  37807. this.object = null;
  37808. }
  37809. render( start, count ) {
  37810. const { gl, mode, object, type, info, index } = this;
  37811. if ( index !== 0 ) {
  37812. gl.drawElements( mode, count, type, start );
  37813. } else {
  37814. gl.drawArrays( mode, start, count );
  37815. }
  37816. info.update( object, count, mode, 1 );
  37817. }
  37818. renderInstances( start, count, primcount ) {
  37819. const { gl, mode, type, index, object, info } = this;
  37820. if ( primcount === 0 ) return;
  37821. if ( index !== 0 ) {
  37822. gl.drawElementsInstanced( mode, count, type, start, primcount );
  37823. } else {
  37824. gl.drawArraysInstanced( mode, start, count, primcount );
  37825. }
  37826. info.update( object, count, mode, primcount );
  37827. }
  37828. renderMultiDraw( starts, counts, drawCount ) {
  37829. const { extensions, mode, object, info } = this;
  37830. if ( drawCount === 0 ) return;
  37831. const extension = extensions.get( 'WEBGL_multi_draw' );
  37832. if ( extension === null ) {
  37833. for ( let i = 0; i < drawCount; i ++ ) {
  37834. this.render( starts[ i ], counts[ i ] );
  37835. }
  37836. } else {
  37837. if ( this.index !== 0 ) {
  37838. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  37839. } else {
  37840. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  37841. }
  37842. let elementCount = 0;
  37843. for ( let i = 0; i < drawCount; i ++ ) {
  37844. elementCount += counts[ i ];
  37845. }
  37846. info.update( object, elementCount, mode, 1 );
  37847. }
  37848. }
  37849. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  37850. const { extensions, mode, object, info } = this;
  37851. if ( drawCount === 0 ) return;
  37852. const extension = extensions.get( 'WEBGL_multi_draw' );
  37853. if ( extension === null ) {
  37854. for ( let i = 0; i < drawCount; i ++ ) {
  37855. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  37856. }
  37857. } else {
  37858. if ( this.index !== 0 ) {
  37859. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  37860. } else {
  37861. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  37862. }
  37863. let elementCount = 0;
  37864. for ( let i = 0; i < drawCount; i ++ ) {
  37865. elementCount += counts[ i ] * primcount[ i ];
  37866. }
  37867. info.update( object, elementCount, mode, 1 );
  37868. }
  37869. }
  37870. //
  37871. }
  37872. /**
  37873. * A backend implementation targeting WebGL 2.
  37874. *
  37875. * @private
  37876. * @augments Backend
  37877. */
  37878. class WebGLBackend extends Backend {
  37879. /**
  37880. * Constructs a new WebGPU backend.
  37881. *
  37882. * @param {Object} parameters - The configuration parameter.
  37883. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  37884. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  37885. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  37886. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  37887. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  37888. * @param {Number} [parameters.samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  37889. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses it WebGL 2 backend no matter if WebGPU is supported or not.
  37890. * @param {WebGL2RenderingContext} [parameters.context=undefined] - A WebGL 2 rendering context.
  37891. */
  37892. constructor( parameters = {} ) {
  37893. super( parameters );
  37894. /**
  37895. * This flag can be used for type testing.
  37896. *
  37897. * @type {Boolean}
  37898. * @readonly
  37899. * @default true
  37900. */
  37901. this.isWebGLBackend = true;
  37902. /**
  37903. * A reference to a backend module holding shader attribute-related
  37904. * utility functions.
  37905. *
  37906. * @type {WebGLAttributeUtils?}
  37907. * @default null
  37908. */
  37909. this.attributeUtils = null;
  37910. /**
  37911. * A reference to a backend module holding extension-related
  37912. * utility functions.
  37913. *
  37914. * @type {WebGLExtensions?}
  37915. * @default null
  37916. */
  37917. this.extensions = null;
  37918. /**
  37919. * A reference to a backend module holding capability-related
  37920. * utility functions.
  37921. *
  37922. * @type {WebGLCapabilities?}
  37923. * @default null
  37924. */
  37925. this.capabilities = null;
  37926. /**
  37927. * A reference to a backend module holding texture-related
  37928. * utility functions.
  37929. *
  37930. * @type {WebGLTextureUtils?}
  37931. * @default null
  37932. */
  37933. this.textureUtils = null;
  37934. /**
  37935. * A reference to a backend module holding renderer-related
  37936. * utility functions.
  37937. *
  37938. * @type {WebGLBufferRenderer?}
  37939. * @default null
  37940. */
  37941. this.bufferRenderer = null;
  37942. /**
  37943. * A reference to the rendering context.
  37944. *
  37945. * @type {WebGL2RenderingContext?}
  37946. * @default null
  37947. */
  37948. this.gl = null;
  37949. /**
  37950. * A reference to a backend module holding state-related
  37951. * utility functions.
  37952. *
  37953. * @type {WebGLState?}
  37954. * @default null
  37955. */
  37956. this.state = null;
  37957. /**
  37958. * A reference to a backend module holding common
  37959. * utility functions.
  37960. *
  37961. * @type {WebGLUtils?}
  37962. * @default null
  37963. */
  37964. this.utils = null;
  37965. /**
  37966. * Dictionary for caching VAOs.
  37967. *
  37968. * @type {Object<String,WebGLVertexArrayObject>}
  37969. */
  37970. this.vaoCache = {};
  37971. /**
  37972. * Dictionary for caching transform feedback objects.
  37973. *
  37974. * @type {Object<String,WebGLTransformFeedback>}
  37975. */
  37976. this.transformFeedbackCache = {};
  37977. /**
  37978. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  37979. * Only relevant when using compute shaders.
  37980. *
  37981. * @type {Boolean}
  37982. * @default false
  37983. */
  37984. this.discard = false;
  37985. /**
  37986. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  37987. * device does not support the extension.
  37988. *
  37989. * @type {EXTDisjointTimerQueryWebGL2?}
  37990. * @default null
  37991. */
  37992. this.disjoint = null;
  37993. /**
  37994. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  37995. * device does not support the extension.
  37996. *
  37997. * @type {KHRParallelShaderCompile?}
  37998. * @default null
  37999. */
  38000. this.parallel = null;
  38001. /**
  38002. * Whether to track timestamps with a Timestamp Query API or not.
  38003. *
  38004. * @type {Boolean}
  38005. * @default false
  38006. */
  38007. this.trackTimestamp = ( parameters.trackTimestamp === true );
  38008. /**
  38009. * A reference to the current render context.
  38010. *
  38011. * @private
  38012. * @type {RenderContext}
  38013. * @default null
  38014. */
  38015. this._currentContext = null;
  38016. /**
  38017. * A unique collection of bindings.
  38018. *
  38019. * @private
  38020. * @type {WeakSet}
  38021. */
  38022. this._knownBindings = new WeakSet();
  38023. }
  38024. /**
  38025. * Initializes the backend so it is ready for usage.
  38026. *
  38027. * @param {Renderer} renderer - The renderer.
  38028. */
  38029. init( renderer ) {
  38030. super.init( renderer );
  38031. //
  38032. const parameters = this.parameters;
  38033. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  38034. function onContextLost( event ) {
  38035. event.preventDefault();
  38036. const contextLossInfo = {
  38037. api: 'WebGL',
  38038. message: event.statusMessage || 'Unknown reason',
  38039. reason: null,
  38040. originalEvent: event
  38041. };
  38042. renderer.onDeviceLost( contextLossInfo );
  38043. }
  38044. this._onContextLost = onContextLost;
  38045. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  38046. this.gl = glContext;
  38047. this.extensions = new WebGLExtensions( this );
  38048. this.capabilities = new WebGLCapabilities( this );
  38049. this.attributeUtils = new WebGLAttributeUtils( this );
  38050. this.textureUtils = new WebGLTextureUtils( this );
  38051. this.bufferRenderer = new WebGLBufferRenderer( this );
  38052. this.state = new WebGLState( this );
  38053. this.utils = new WebGLUtils( this );
  38054. this.extensions.get( 'EXT_color_buffer_float' );
  38055. this.extensions.get( 'WEBGL_clip_cull_distance' );
  38056. this.extensions.get( 'OES_texture_float_linear' );
  38057. this.extensions.get( 'EXT_color_buffer_half_float' );
  38058. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  38059. this.extensions.get( 'WEBGL_render_shared_exponent' );
  38060. this.extensions.get( 'WEBGL_multi_draw' );
  38061. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  38062. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  38063. }
  38064. /**
  38065. * The coordinate system of the backend.
  38066. *
  38067. * @type {Number}
  38068. * @readonly
  38069. */
  38070. get coordinateSystem() {
  38071. return WebGLCoordinateSystem;
  38072. }
  38073. /**
  38074. * Transfers buffer data from a storage buffer attribute
  38075. * from the GPU to the CPU in context of compute shaders.
  38076. *
  38077. * @async
  38078. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  38079. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  38080. */
  38081. async getArrayBufferAsync( attribute ) {
  38082. return await this.attributeUtils.getArrayBufferAsync( attribute );
  38083. }
  38084. /**
  38085. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  38086. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  38087. *
  38088. * @async
  38089. * @return {Promise} A Promise that resolves when synchronization has been finished.
  38090. */
  38091. async waitForGPU() {
  38092. await this.utils._clientWaitAsync();
  38093. }
  38094. /**
  38095. * Inits a time stamp query for the given render context.
  38096. *
  38097. * @param {RenderContext} renderContext - The render context.
  38098. */
  38099. initTimestampQuery( renderContext ) {
  38100. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  38101. const renderContextData = this.get( renderContext );
  38102. if ( this.queryRunning ) {
  38103. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  38104. renderContextData.queryQueue.push( renderContext );
  38105. return;
  38106. }
  38107. if ( renderContextData.activeQuery ) {
  38108. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  38109. renderContextData.activeQuery = null;
  38110. }
  38111. renderContextData.activeQuery = this.gl.createQuery();
  38112. if ( renderContextData.activeQuery !== null ) {
  38113. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  38114. this.queryRunning = true;
  38115. }
  38116. }
  38117. // timestamp utils
  38118. /**
  38119. * Prepares the timestamp buffer.
  38120. *
  38121. * @param {RenderContext} renderContext - The render context.
  38122. */
  38123. prepareTimestampBuffer( renderContext ) {
  38124. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  38125. const renderContextData = this.get( renderContext );
  38126. if ( renderContextData.activeQuery ) {
  38127. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  38128. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  38129. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  38130. renderContextData.activeQuery = null;
  38131. this.queryRunning = false;
  38132. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  38133. const nextRenderContext = renderContextData.queryQueue.shift();
  38134. this.initTimestampQuery( nextRenderContext );
  38135. }
  38136. }
  38137. }
  38138. /**
  38139. * Resolves the time stamp for the given render context and type.
  38140. *
  38141. * @async
  38142. * @param {RenderContext} renderContext - The render context.
  38143. * @param {String} type - The render context.
  38144. * @return {Promise} A Promise that resolves when the time stamp has been computed.
  38145. */
  38146. async resolveTimestampAsync( renderContext, type = 'render' ) {
  38147. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  38148. const renderContextData = this.get( renderContext );
  38149. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  38150. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  38151. const queryInfo = renderContextData.gpuQueries[ i ];
  38152. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  38153. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  38154. if ( available && ! disjoint ) {
  38155. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  38156. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  38157. this.gl.deleteQuery( queryInfo.query );
  38158. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  38159. i --;
  38160. this.renderer.info.updateTimestamp( type, duration );
  38161. }
  38162. }
  38163. }
  38164. /**
  38165. * Returns the backend's rendering context.
  38166. *
  38167. * @return {WebGL2RenderingContext} The rendering context.
  38168. */
  38169. getContext() {
  38170. return this.gl;
  38171. }
  38172. /**
  38173. * This method is executed at the beginning of a render call and prepares
  38174. * the WebGL state for upcoming render calls
  38175. *
  38176. * @param {RenderContext} renderContext - The render context.
  38177. */
  38178. beginRender( renderContext ) {
  38179. const { gl } = this;
  38180. const renderContextData = this.get( renderContext );
  38181. //
  38182. //
  38183. this.initTimestampQuery( renderContext );
  38184. renderContextData.previousContext = this._currentContext;
  38185. this._currentContext = renderContext;
  38186. this._setFramebuffer( renderContext );
  38187. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  38188. //
  38189. if ( renderContext.viewport ) {
  38190. this.updateViewport( renderContext );
  38191. } else {
  38192. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  38193. }
  38194. if ( renderContext.scissor ) {
  38195. const { x, y, width, height } = renderContext.scissorValue;
  38196. gl.scissor( x, renderContext.height - height - y, width, height );
  38197. }
  38198. const occlusionQueryCount = renderContext.occlusionQueryCount;
  38199. if ( occlusionQueryCount > 0 ) {
  38200. // Get a reference to the array of objects with queries. The renderContextData property
  38201. // can be changed by another render pass before the async reading of all previous queries complete
  38202. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  38203. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  38204. renderContextData.lastOcclusionObject = null;
  38205. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  38206. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  38207. renderContextData.occlusionQueryIndex = 0;
  38208. }
  38209. }
  38210. /**
  38211. * This method is executed at the end of a render call and finalizes work
  38212. * after draw calls.
  38213. *
  38214. * @param {RenderContext} renderContext - The render context.
  38215. */
  38216. finishRender( renderContext ) {
  38217. const { gl, state } = this;
  38218. const renderContextData = this.get( renderContext );
  38219. const previousContext = renderContextData.previousContext;
  38220. const occlusionQueryCount = renderContext.occlusionQueryCount;
  38221. if ( occlusionQueryCount > 0 ) {
  38222. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  38223. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  38224. }
  38225. this.resolveOccludedAsync( renderContext );
  38226. }
  38227. const textures = renderContext.textures;
  38228. if ( textures !== null ) {
  38229. for ( let i = 0; i < textures.length; i ++ ) {
  38230. const texture = textures[ i ];
  38231. if ( texture.generateMipmaps ) {
  38232. this.generateMipmaps( texture );
  38233. }
  38234. }
  38235. }
  38236. this._currentContext = previousContext;
  38237. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  38238. const renderTargetContextData = this.get( renderContext.renderTarget );
  38239. const { samples } = renderContext.renderTarget;
  38240. if ( samples > 0 ) {
  38241. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  38242. const mask = gl.COLOR_BUFFER_BIT;
  38243. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  38244. const textures = renderContext.textures;
  38245. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  38246. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  38247. for ( let i = 0; i < textures.length; i ++ ) {
  38248. // TODO Add support for MRT
  38249. if ( renderContext.scissor ) {
  38250. const { x, y, width, height } = renderContext.scissorValue;
  38251. const viewY = renderContext.height - height - y;
  38252. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  38253. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  38254. } else {
  38255. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  38256. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  38257. }
  38258. }
  38259. }
  38260. }
  38261. if ( previousContext !== null ) {
  38262. this._setFramebuffer( previousContext );
  38263. if ( previousContext.viewport ) {
  38264. this.updateViewport( previousContext );
  38265. } else {
  38266. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  38267. }
  38268. }
  38269. this.prepareTimestampBuffer( renderContext );
  38270. }
  38271. /**
  38272. * This method processes the result of occlusion queries and writes it
  38273. * into render context data.
  38274. *
  38275. * @async
  38276. * @param {RenderContext} renderContext - The render context.
  38277. */
  38278. resolveOccludedAsync( renderContext ) {
  38279. const renderContextData = this.get( renderContext );
  38280. // handle occlusion query results
  38281. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  38282. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  38283. const occluded = new WeakSet();
  38284. const { gl } = this;
  38285. renderContextData.currentOcclusionQueryObjects = null;
  38286. renderContextData.currentOcclusionQueries = null;
  38287. const check = () => {
  38288. let completed = 0;
  38289. // check all queries and requeue as appropriate
  38290. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  38291. const query = currentOcclusionQueries[ i ];
  38292. if ( query === null ) continue;
  38293. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  38294. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  38295. currentOcclusionQueries[ i ] = null;
  38296. gl.deleteQuery( query );
  38297. completed ++;
  38298. }
  38299. }
  38300. if ( completed < currentOcclusionQueries.length ) {
  38301. requestAnimationFrame( check );
  38302. } else {
  38303. renderContextData.occluded = occluded;
  38304. }
  38305. };
  38306. check();
  38307. }
  38308. }
  38309. /**
  38310. * Returns `true` if the given 3D object is fully occluded by other
  38311. * 3D objects in the scene.
  38312. *
  38313. * @param {RenderContext} renderContext - The render context.
  38314. * @param {Object3D} object - The 3D object to test.
  38315. * @return {Boolean} Whether the 3D object is fully occluded or not.
  38316. */
  38317. isOccluded( renderContext, object ) {
  38318. const renderContextData = this.get( renderContext );
  38319. return renderContextData.occluded && renderContextData.occluded.has( object );
  38320. }
  38321. /**
  38322. * Updates the viewport with the values from the given render context.
  38323. *
  38324. * @param {RenderContext} renderContext - The render context.
  38325. */
  38326. updateViewport( renderContext ) {
  38327. const gl = this.gl;
  38328. const { x, y, width, height } = renderContext.viewportValue;
  38329. gl.viewport( x, renderContext.height - height - y, width, height );
  38330. }
  38331. /**
  38332. * Defines the scissor test.
  38333. *
  38334. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  38335. */
  38336. setScissorTest( boolean ) {
  38337. const gl = this.gl;
  38338. if ( boolean ) {
  38339. gl.enable( gl.SCISSOR_TEST );
  38340. } else {
  38341. gl.disable( gl.SCISSOR_TEST );
  38342. }
  38343. }
  38344. /**
  38345. * Performs a clear operation.
  38346. *
  38347. * @param {Boolean} color - Whether the color buffer should be cleared or not.
  38348. * @param {Boolean} depth - Whether the depth buffer should be cleared or not.
  38349. * @param {Boolean} stencil - Whether the stencil buffer should be cleared or not.
  38350. * @param {Object?} [descriptor=null] - The render context of the current set render target.
  38351. * @param {Boolean} [setFrameBuffer=true] - TODO.
  38352. */
  38353. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  38354. const { gl } = this;
  38355. if ( descriptor === null ) {
  38356. const clearColor = this.getClearColor();
  38357. // premultiply alpha
  38358. clearColor.r *= clearColor.a;
  38359. clearColor.g *= clearColor.a;
  38360. clearColor.b *= clearColor.a;
  38361. descriptor = {
  38362. textures: null,
  38363. clearColorValue: clearColor
  38364. };
  38365. }
  38366. //
  38367. let clear = 0;
  38368. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  38369. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  38370. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  38371. if ( clear !== 0 ) {
  38372. let clearColor;
  38373. if ( descriptor.clearColorValue ) {
  38374. clearColor = descriptor.clearColorValue;
  38375. } else {
  38376. clearColor = this.getClearColor();
  38377. // premultiply alpha
  38378. clearColor.r *= clearColor.a;
  38379. clearColor.g *= clearColor.a;
  38380. clearColor.b *= clearColor.a;
  38381. }
  38382. if ( depth ) this.state.setDepthMask( true );
  38383. if ( descriptor.textures === null ) {
  38384. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  38385. gl.clear( clear );
  38386. } else {
  38387. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  38388. if ( color ) {
  38389. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  38390. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  38391. }
  38392. }
  38393. if ( depth && stencil ) {
  38394. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  38395. } else if ( depth ) {
  38396. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  38397. } else if ( stencil ) {
  38398. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  38399. }
  38400. }
  38401. }
  38402. }
  38403. /**
  38404. * This method is executed at the beginning of a compute call and
  38405. * prepares the state for upcoming compute tasks.
  38406. *
  38407. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  38408. */
  38409. beginCompute( computeGroup ) {
  38410. const { state, gl } = this;
  38411. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  38412. this.initTimestampQuery( computeGroup );
  38413. }
  38414. /**
  38415. * Executes a compute command for the given compute node.
  38416. *
  38417. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  38418. * @param {Node} computeNode - The compute node.
  38419. * @param {Array<BindGroup>} bindings - The bindings.
  38420. * @param {ComputePipeline} pipeline - The compute pipeline.
  38421. */
  38422. compute( computeGroup, computeNode, bindings, pipeline ) {
  38423. const { state, gl } = this;
  38424. if ( this.discard === false ) {
  38425. // required here to handle async behaviour of render.compute()
  38426. gl.enable( gl.RASTERIZER_DISCARD );
  38427. this.discard = true;
  38428. }
  38429. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  38430. const vaoKey = this._getVaoKey( null, attributes );
  38431. const vaoGPU = this.vaoCache[ vaoKey ];
  38432. if ( vaoGPU === undefined ) {
  38433. this._createVao( null, attributes );
  38434. } else {
  38435. gl.bindVertexArray( vaoGPU );
  38436. }
  38437. state.useProgram( programGPU );
  38438. this._bindUniforms( bindings );
  38439. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  38440. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  38441. gl.beginTransformFeedback( gl.POINTS );
  38442. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  38443. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  38444. } else {
  38445. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  38446. }
  38447. gl.endTransformFeedback();
  38448. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  38449. // switch active buffers
  38450. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  38451. const dualAttributeData = transformBuffers[ i ];
  38452. if ( dualAttributeData.pbo ) {
  38453. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  38454. }
  38455. dualAttributeData.switchBuffers();
  38456. }
  38457. }
  38458. /**
  38459. * This method is executed at the end of a compute call and
  38460. * finalizes work after compute tasks.
  38461. *
  38462. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  38463. */
  38464. finishCompute( computeGroup ) {
  38465. const gl = this.gl;
  38466. this.discard = false;
  38467. gl.disable( gl.RASTERIZER_DISCARD );
  38468. this.prepareTimestampBuffer( computeGroup );
  38469. if ( this._currentContext ) {
  38470. this._setFramebuffer( this._currentContext );
  38471. }
  38472. }
  38473. /**
  38474. * Executes a draw command for the given render object.
  38475. *
  38476. * @param {RenderObject} renderObject - The render object to draw.
  38477. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  38478. */
  38479. draw( renderObject/*, info*/ ) {
  38480. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  38481. const { programGPU } = this.get( pipeline );
  38482. const { gl, state } = this;
  38483. const contextData = this.get( context );
  38484. const drawParams = renderObject.getDrawParameters();
  38485. if ( drawParams === null ) return;
  38486. //
  38487. this._bindUniforms( renderObject.getBindings() );
  38488. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  38489. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  38490. state.useProgram( programGPU );
  38491. //
  38492. const renderObjectData = this.get( renderObject );
  38493. let vaoGPU = renderObjectData.staticVao;
  38494. if ( vaoGPU === undefined || renderObjectData.geometryId !== renderObject.geometry.id ) {
  38495. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  38496. vaoGPU = this.vaoCache[ vaoKey ];
  38497. if ( vaoGPU === undefined ) {
  38498. let staticVao;
  38499. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  38500. if ( staticVao ) {
  38501. renderObjectData.staticVao = vaoGPU;
  38502. renderObjectData.geometryId = renderObject.geometry.id;
  38503. }
  38504. }
  38505. }
  38506. gl.bindVertexArray( vaoGPU );
  38507. //
  38508. const index = renderObject.getIndex();
  38509. //
  38510. const lastObject = contextData.lastOcclusionObject;
  38511. if ( lastObject !== object && lastObject !== undefined ) {
  38512. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  38513. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  38514. contextData.occlusionQueryIndex ++;
  38515. }
  38516. if ( object.occlusionTest === true ) {
  38517. const query = gl.createQuery();
  38518. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  38519. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  38520. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  38521. }
  38522. contextData.lastOcclusionObject = object;
  38523. }
  38524. //
  38525. const renderer = this.bufferRenderer;
  38526. if ( object.isPoints ) renderer.mode = gl.POINTS;
  38527. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  38528. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  38529. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  38530. else {
  38531. if ( material.wireframe === true ) {
  38532. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  38533. renderer.mode = gl.LINES;
  38534. } else {
  38535. renderer.mode = gl.TRIANGLES;
  38536. }
  38537. }
  38538. //
  38539. const { vertexCount, instanceCount } = drawParams;
  38540. let { firstVertex } = drawParams;
  38541. renderer.object = object;
  38542. if ( index !== null ) {
  38543. firstVertex *= index.array.BYTES_PER_ELEMENT;
  38544. const indexData = this.get( index );
  38545. renderer.index = index.count;
  38546. renderer.type = indexData.type;
  38547. } else {
  38548. renderer.index = 0;
  38549. }
  38550. if ( object.isBatchedMesh ) {
  38551. if ( object._multiDrawInstances !== null ) {
  38552. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  38553. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  38554. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  38555. } else {
  38556. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  38557. }
  38558. } else if ( instanceCount > 1 ) {
  38559. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  38560. } else {
  38561. renderer.render( firstVertex, vertexCount );
  38562. }
  38563. //
  38564. gl.bindVertexArray( null );
  38565. }
  38566. /**
  38567. * Explain why always null is returned.
  38568. *
  38569. * @param {RenderObject} renderObject - The render object.
  38570. * @return {Boolean} Whether the render pipeline requires an update or not.
  38571. */
  38572. needsRenderUpdate( /*renderObject*/ ) {
  38573. return false;
  38574. }
  38575. /**
  38576. * Explain why no cache key is computed.
  38577. *
  38578. * @param {RenderObject} renderObject - The render object.
  38579. * @return {String} The cache key.
  38580. */
  38581. getRenderCacheKey( /*renderObject*/ ) {
  38582. return '';
  38583. }
  38584. // textures
  38585. /**
  38586. * Creates a default texture for the given texture that can be used
  38587. * as a placeholder until the actual texture is ready for usage.
  38588. *
  38589. * @param {Texture} texture - The texture to create a default texture for.
  38590. */
  38591. createDefaultTexture( texture ) {
  38592. this.textureUtils.createDefaultTexture( texture );
  38593. }
  38594. /**
  38595. * Defines a texture on the GPU for the given texture object.
  38596. *
  38597. * @param {Texture} texture - The texture.
  38598. * @param {Object} [options={}] - Optional configuration parameter.
  38599. */
  38600. createTexture( texture, options ) {
  38601. this.textureUtils.createTexture( texture, options );
  38602. }
  38603. /**
  38604. * Uploads the updated texture data to the GPU.
  38605. *
  38606. * @param {Texture} texture - The texture.
  38607. * @param {Object} [options={}] - Optional configuration parameter.
  38608. */
  38609. updateTexture( texture, options ) {
  38610. this.textureUtils.updateTexture( texture, options );
  38611. }
  38612. /**
  38613. * Generates mipmaps for the given texture
  38614. *
  38615. * @param {Texture} texture - The texture.
  38616. */
  38617. generateMipmaps( texture ) {
  38618. this.textureUtils.generateMipmaps( texture );
  38619. }
  38620. /**
  38621. * Destroys the GPU data for the given texture object.
  38622. *
  38623. * @param {Texture} texture - The texture.
  38624. */
  38625. destroyTexture( texture ) {
  38626. this.textureUtils.destroyTexture( texture );
  38627. }
  38628. /**
  38629. * Returns texture data as a typed array.
  38630. *
  38631. * @param {Texture} texture - The texture to copy.
  38632. * @param {Number} x - The x coordinate of the copy origin.
  38633. * @param {Number} y - The y coordinate of the copy origin.
  38634. * @param {Number} width - The width of the copy.
  38635. * @param {Number} height - The height of the copy.
  38636. * @param {Number} faceIndex - The face index.
  38637. * @return {TypedArray} The texture data as a typed array.
  38638. */
  38639. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  38640. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  38641. }
  38642. /**
  38643. * This method does nothing since WebGL 2 has no concept of samplers.
  38644. *
  38645. * @param {Texture} texture - The texture to create the sampler for.
  38646. */
  38647. createSampler( /*texture*/ ) {
  38648. //console.warn( 'Abstract class.' );
  38649. }
  38650. /**
  38651. * This method does nothing since WebGL 2 has no concept of samplers.
  38652. *
  38653. * @param {Texture} texture - The texture to destroy the sampler for.
  38654. */
  38655. destroySampler( /*texture*/ ) {}
  38656. // node builder
  38657. /**
  38658. * Returns a node builder for the given render object.
  38659. *
  38660. * @param {RenderObject} object - The render object.
  38661. * @param {Renderer} renderer - The renderer.
  38662. * @return {GLSLNodeBuilder} The node builder.
  38663. */
  38664. createNodeBuilder( object, renderer ) {
  38665. return new GLSLNodeBuilder( object, renderer );
  38666. }
  38667. // program
  38668. /**
  38669. * Creates a shader program from the given programmable stage.
  38670. *
  38671. * @param {ProgrammableStage} program - The programmable stage.
  38672. */
  38673. createProgram( program ) {
  38674. const gl = this.gl;
  38675. const { stage, code } = program;
  38676. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  38677. gl.shaderSource( shader, code );
  38678. gl.compileShader( shader );
  38679. this.set( program, {
  38680. shaderGPU: shader
  38681. } );
  38682. }
  38683. /**
  38684. * Destroys the shader program of the given programmable stage.
  38685. *
  38686. * @param {ProgrammableStage} program - The programmable stage.
  38687. */
  38688. destroyProgram( program ) {
  38689. this.delete( program );
  38690. }
  38691. /**
  38692. * Creates a render pipeline for the given render object.
  38693. *
  38694. * @param {RenderObject} renderObject - The render object.
  38695. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  38696. */
  38697. createRenderPipeline( renderObject, promises ) {
  38698. const gl = this.gl;
  38699. const pipeline = renderObject.pipeline;
  38700. // Program
  38701. const { fragmentProgram, vertexProgram } = pipeline;
  38702. const programGPU = gl.createProgram();
  38703. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  38704. const vertexShader = this.get( vertexProgram ).shaderGPU;
  38705. gl.attachShader( programGPU, fragmentShader );
  38706. gl.attachShader( programGPU, vertexShader );
  38707. gl.linkProgram( programGPU );
  38708. this.set( pipeline, {
  38709. programGPU,
  38710. fragmentShader,
  38711. vertexShader
  38712. } );
  38713. if ( promises !== null && this.parallel ) {
  38714. const p = new Promise( ( resolve /*, reject*/ ) => {
  38715. const parallel = this.parallel;
  38716. const checkStatus = () => {
  38717. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  38718. this._completeCompile( renderObject, pipeline );
  38719. resolve();
  38720. } else {
  38721. requestAnimationFrame( checkStatus );
  38722. }
  38723. };
  38724. checkStatus();
  38725. } );
  38726. promises.push( p );
  38727. return;
  38728. }
  38729. this._completeCompile( renderObject, pipeline );
  38730. }
  38731. /**
  38732. * Formats the source code of error messages.
  38733. *
  38734. * @private
  38735. * @param {String} string - The code.
  38736. * @param {Number} errorLine - The error line.
  38737. * @return {String} The formatted code.
  38738. */
  38739. _handleSource( string, errorLine ) {
  38740. const lines = string.split( '\n' );
  38741. const lines2 = [];
  38742. const from = Math.max( errorLine - 6, 0 );
  38743. const to = Math.min( errorLine + 6, lines.length );
  38744. for ( let i = from; i < to; i ++ ) {
  38745. const line = i + 1;
  38746. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  38747. }
  38748. return lines2.join( '\n' );
  38749. }
  38750. /**
  38751. * Gets the shader compilation errors from the info log.
  38752. *
  38753. * @private
  38754. * @param {WebGL2RenderingContext} gl - The rendering context.
  38755. * @param {WebGLShader} shader - The WebGL shader object.
  38756. * @param {String} type - The shader type.
  38757. * @return {String} The shader errors.
  38758. */
  38759. _getShaderErrors( gl, shader, type ) {
  38760. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  38761. const errors = gl.getShaderInfoLog( shader ).trim();
  38762. if ( status && errors === '' ) return '';
  38763. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  38764. if ( errorMatches ) {
  38765. const errorLine = parseInt( errorMatches[ 1 ] );
  38766. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  38767. } else {
  38768. return errors;
  38769. }
  38770. }
  38771. /**
  38772. * Logs shader compilation errors.
  38773. *
  38774. * @private
  38775. * @param {WebGLProgram} programGPU - The WebGL program.
  38776. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  38777. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  38778. */
  38779. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  38780. if ( this.renderer.debug.checkShaderErrors ) {
  38781. const gl = this.gl;
  38782. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  38783. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  38784. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  38785. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  38786. } else {
  38787. // default error reporting
  38788. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  38789. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  38790. console.error(
  38791. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  38792. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  38793. 'Program Info Log: ' + programLog + '\n' +
  38794. vertexErrors + '\n' +
  38795. fragmentErrors
  38796. );
  38797. }
  38798. } else if ( programLog !== '' ) {
  38799. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  38800. }
  38801. }
  38802. }
  38803. /**
  38804. * Completes the shader program setup for the given render object.
  38805. *
  38806. * @private
  38807. * @param {RenderObject} renderObject - The render object.
  38808. * @param {RenderPipeline} pipeline - The render pipeline.
  38809. */
  38810. _completeCompile( renderObject, pipeline ) {
  38811. const { state, gl } = this;
  38812. const pipelineData = this.get( pipeline );
  38813. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  38814. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  38815. this._logProgramError( programGPU, fragmentShader, vertexShader );
  38816. }
  38817. state.useProgram( programGPU );
  38818. // Bindings
  38819. const bindings = renderObject.getBindings();
  38820. this._setupBindings( bindings, programGPU );
  38821. //
  38822. this.set( pipeline, {
  38823. programGPU
  38824. } );
  38825. }
  38826. /**
  38827. * Creates a compute pipeline for the given compute node.
  38828. *
  38829. * @param {ComputePipeline} computePipeline - The compute pipeline.
  38830. * @param {Array<BindGroup>} bindings - The bindings.
  38831. */
  38832. createComputePipeline( computePipeline, bindings ) {
  38833. const { state, gl } = this;
  38834. // Program
  38835. const fragmentProgram = {
  38836. stage: 'fragment',
  38837. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  38838. };
  38839. this.createProgram( fragmentProgram );
  38840. const { computeProgram } = computePipeline;
  38841. const programGPU = gl.createProgram();
  38842. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  38843. const vertexShader = this.get( computeProgram ).shaderGPU;
  38844. const transforms = computeProgram.transforms;
  38845. const transformVaryingNames = [];
  38846. const transformAttributeNodes = [];
  38847. for ( let i = 0; i < transforms.length; i ++ ) {
  38848. const transform = transforms[ i ];
  38849. transformVaryingNames.push( transform.varyingName );
  38850. transformAttributeNodes.push( transform.attributeNode );
  38851. }
  38852. gl.attachShader( programGPU, fragmentShader );
  38853. gl.attachShader( programGPU, vertexShader );
  38854. gl.transformFeedbackVaryings(
  38855. programGPU,
  38856. transformVaryingNames,
  38857. gl.SEPARATE_ATTRIBS
  38858. );
  38859. gl.linkProgram( programGPU );
  38860. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  38861. this._logProgramError( programGPU, fragmentShader, vertexShader );
  38862. }
  38863. state.useProgram( programGPU );
  38864. // Bindings
  38865. this._setupBindings( bindings, programGPU );
  38866. const attributeNodes = computeProgram.attributes;
  38867. const attributes = [];
  38868. const transformBuffers = [];
  38869. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  38870. const attribute = attributeNodes[ i ].node.attribute;
  38871. attributes.push( attribute );
  38872. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  38873. }
  38874. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  38875. const attribute = transformAttributeNodes[ i ].attribute;
  38876. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  38877. const attributeData = this.get( attribute );
  38878. transformBuffers.push( attributeData );
  38879. }
  38880. //
  38881. this.set( computePipeline, {
  38882. programGPU,
  38883. transformBuffers,
  38884. attributes
  38885. } );
  38886. }
  38887. /**
  38888. * Creates bindings from the given bind group definition.
  38889. *
  38890. * @param {BindGroup} bindGroup - The bind group.
  38891. * @param {Array<BindGroup>} bindings - Array of bind groups.
  38892. * @param {Number} cacheIndex - The cache index.
  38893. * @param {Number} version - The version.
  38894. */
  38895. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  38896. if ( this._knownBindings.has( bindings ) === false ) {
  38897. this._knownBindings.add( bindings );
  38898. let uniformBuffers = 0;
  38899. let textures = 0;
  38900. for ( const bindGroup of bindings ) {
  38901. this.set( bindGroup, {
  38902. textures: textures,
  38903. uniformBuffers: uniformBuffers
  38904. } );
  38905. for ( const binding of bindGroup.bindings ) {
  38906. if ( binding.isUniformBuffer ) uniformBuffers ++;
  38907. if ( binding.isSampledTexture ) textures ++;
  38908. }
  38909. }
  38910. }
  38911. this.updateBindings( bindGroup, bindings );
  38912. }
  38913. /**
  38914. * Updates the given bind group definition.
  38915. *
  38916. * @param {BindGroup} bindGroup - The bind group.
  38917. * @param {Array<BindGroup>} bindings - Array of bind groups.
  38918. * @param {Number} cacheIndex - The cache index.
  38919. * @param {Number} version - The version.
  38920. */
  38921. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  38922. const { gl } = this;
  38923. const bindGroupData = this.get( bindGroup );
  38924. let i = bindGroupData.uniformBuffers;
  38925. let t = bindGroupData.textures;
  38926. for ( const binding of bindGroup.bindings ) {
  38927. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  38928. const data = binding.buffer;
  38929. const bufferGPU = gl.createBuffer();
  38930. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  38931. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  38932. this.set( binding, {
  38933. index: i ++,
  38934. bufferGPU
  38935. } );
  38936. } else if ( binding.isSampledTexture ) {
  38937. const { textureGPU, glTextureType } = this.get( binding.texture );
  38938. this.set( binding, {
  38939. index: t ++,
  38940. textureGPU,
  38941. glTextureType
  38942. } );
  38943. }
  38944. }
  38945. }
  38946. /**
  38947. * Updates a buffer binding.
  38948. *
  38949. * @param {Buffer} binding - The buffer binding to update.
  38950. */
  38951. updateBinding( binding ) {
  38952. const gl = this.gl;
  38953. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  38954. const bindingData = this.get( binding );
  38955. const bufferGPU = bindingData.bufferGPU;
  38956. const data = binding.buffer;
  38957. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  38958. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  38959. }
  38960. }
  38961. // attributes
  38962. /**
  38963. * Creates the buffer of an indexed shader attribute.
  38964. *
  38965. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  38966. */
  38967. createIndexAttribute( attribute ) {
  38968. const gl = this.gl;
  38969. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  38970. }
  38971. /**
  38972. * Creates the buffer of a shader attribute.
  38973. *
  38974. * @param {BufferAttribute} attribute - The buffer attribute.
  38975. */
  38976. createAttribute( attribute ) {
  38977. if ( this.has( attribute ) ) return;
  38978. const gl = this.gl;
  38979. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  38980. }
  38981. /**
  38982. * Creates the buffer of a storage attribute.
  38983. *
  38984. * @param {BufferAttribute} attribute - The buffer attribute.
  38985. */
  38986. createStorageAttribute( attribute ) {
  38987. if ( this.has( attribute ) ) return;
  38988. const gl = this.gl;
  38989. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  38990. }
  38991. /**
  38992. * Updates the buffer of a shader attribute.
  38993. *
  38994. * @param {BufferAttribute} attribute - The buffer attribute to update.
  38995. */
  38996. updateAttribute( attribute ) {
  38997. this.attributeUtils.updateAttribute( attribute );
  38998. }
  38999. /**
  39000. * Destroys the buffer of a shader attribute.
  39001. *
  39002. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  39003. */
  39004. destroyAttribute( attribute ) {
  39005. this.attributeUtils.destroyAttribute( attribute );
  39006. }
  39007. /**
  39008. * Checks if the given feature is supported by the backend.
  39009. *
  39010. * @param {String} name - The feature's name.
  39011. * @return {Boolean} Whether the feature is supported or not.
  39012. */
  39013. hasFeature( name ) {
  39014. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  39015. const extensions = this.extensions;
  39016. for ( let i = 0; i < keysMatching.length; i ++ ) {
  39017. if ( extensions.has( keysMatching[ i ] ) ) return true;
  39018. }
  39019. return false;
  39020. }
  39021. /**
  39022. * Returns the maximum anisotropy texture filtering value.
  39023. *
  39024. * @return {Number} The maximum anisotropy texture filtering value.
  39025. */
  39026. getMaxAnisotropy() {
  39027. return this.capabilities.getMaxAnisotropy();
  39028. }
  39029. /**
  39030. * Copies data of the given source texture to the given destination texture.
  39031. *
  39032. * @param {Texture} srcTexture - The source texture.
  39033. * @param {Texture} dstTexture - The destination texture.
  39034. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  39035. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  39036. * @param {Number} [level=0] - The mip level to copy.
  39037. */
  39038. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  39039. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  39040. }
  39041. /**
  39042. * Copies the current bound framebuffer to the given texture.
  39043. *
  39044. * @param {Texture} texture - The destination texture.
  39045. * @param {RenderContext} renderContext - The render context.
  39046. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  39047. */
  39048. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  39049. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  39050. }
  39051. /**
  39052. * Configures the active framebuffer from the given render context.
  39053. *
  39054. * @private
  39055. * @param {RenderContext} descriptor - The render context.
  39056. */
  39057. _setFramebuffer( descriptor ) {
  39058. const { gl, state } = this;
  39059. let currentFrameBuffer = null;
  39060. if ( descriptor.textures !== null ) {
  39061. const renderTarget = descriptor.renderTarget;
  39062. const renderTargetContextData = this.get( renderTarget );
  39063. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  39064. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  39065. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  39066. const isRenderTargetArray = renderTarget.isRenderTargetArray === true;
  39067. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  39068. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  39069. const cacheKey = getCacheKey( descriptor );
  39070. let fb;
  39071. if ( isCube ) {
  39072. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  39073. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  39074. } else {
  39075. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  39076. fb = renderTargetContextData.framebuffers[ cacheKey ];
  39077. }
  39078. if ( fb === undefined ) {
  39079. fb = gl.createFramebuffer();
  39080. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  39081. const textures = descriptor.textures;
  39082. if ( isCube ) {
  39083. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  39084. const { textureGPU } = this.get( textures[ 0 ] );
  39085. const cubeFace = this.renderer._activeCubeFace;
  39086. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  39087. } else {
  39088. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  39089. for ( let i = 0; i < textures.length; i ++ ) {
  39090. const texture = textures[ i ];
  39091. const textureData = this.get( texture );
  39092. textureData.renderTarget = descriptor.renderTarget;
  39093. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  39094. const attachment = gl.COLOR_ATTACHMENT0 + i;
  39095. if ( isRenderTarget3D || isRenderTargetArray ) {
  39096. const layer = this.renderer._activeCubeFace;
  39097. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, layer );
  39098. } else {
  39099. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  39100. }
  39101. }
  39102. state.drawBuffers( descriptor, fb );
  39103. }
  39104. if ( descriptor.depthTexture !== null ) {
  39105. const textureData = this.get( descriptor.depthTexture );
  39106. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  39107. textureData.renderTarget = descriptor.renderTarget;
  39108. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  39109. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  39110. }
  39111. }
  39112. if ( samples > 0 ) {
  39113. if ( msaaFb === undefined ) {
  39114. const invalidationArray = [];
  39115. msaaFb = gl.createFramebuffer();
  39116. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  39117. const msaaRenderbuffers = [];
  39118. const textures = descriptor.textures;
  39119. for ( let i = 0; i < textures.length; i ++ ) {
  39120. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  39121. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  39122. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  39123. if ( depthBuffer ) {
  39124. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  39125. invalidationArray.push( depthStyle );
  39126. }
  39127. const texture = descriptor.textures[ i ];
  39128. const textureData = this.get( texture );
  39129. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  39130. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  39131. }
  39132. renderTargetContextData.msaaFrameBuffer = msaaFb;
  39133. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  39134. if ( depthRenderbuffer === undefined ) {
  39135. depthRenderbuffer = gl.createRenderbuffer();
  39136. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor );
  39137. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  39138. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  39139. invalidationArray.push( depthStyle );
  39140. }
  39141. renderTargetContextData.invalidationArray = invalidationArray;
  39142. }
  39143. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  39144. } else {
  39145. currentFrameBuffer = fb;
  39146. }
  39147. }
  39148. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  39149. }
  39150. /**
  39151. * Computes the VAO key for the given index and attributes.
  39152. *
  39153. * @private
  39154. * @param {BufferAttribute?} index - The index. `null` for non-indexed geometries.
  39155. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  39156. * @return {String} The VAO key.
  39157. */
  39158. _getVaoKey( index, attributes ) {
  39159. let key = '';
  39160. if ( index !== null ) {
  39161. const indexData = this.get( index );
  39162. key += ':' + indexData.id;
  39163. }
  39164. for ( let i = 0; i < attributes.length; i ++ ) {
  39165. const attributeData = this.get( attributes[ i ] );
  39166. key += ':' + attributeData.id;
  39167. }
  39168. return key;
  39169. }
  39170. /**
  39171. * Creates a VAO from the index and attributes.
  39172. *
  39173. * @private
  39174. * @param {BufferAttribute?} index - The index. `null` for non-indexed geometries.
  39175. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  39176. * @return {Object} The VAO data.
  39177. */
  39178. _createVao( index, attributes ) {
  39179. const { gl } = this;
  39180. const vaoGPU = gl.createVertexArray();
  39181. let key = '';
  39182. let staticVao = true;
  39183. gl.bindVertexArray( vaoGPU );
  39184. if ( index !== null ) {
  39185. const indexData = this.get( index );
  39186. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  39187. key += ':' + indexData.id;
  39188. }
  39189. for ( let i = 0; i < attributes.length; i ++ ) {
  39190. const attribute = attributes[ i ];
  39191. const attributeData = this.get( attribute );
  39192. key += ':' + attributeData.id;
  39193. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  39194. gl.enableVertexAttribArray( i );
  39195. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  39196. let stride, offset;
  39197. if ( attribute.isInterleavedBufferAttribute === true ) {
  39198. stride = attribute.data.stride * attributeData.bytesPerElement;
  39199. offset = attribute.offset * attributeData.bytesPerElement;
  39200. } else {
  39201. stride = 0;
  39202. offset = 0;
  39203. }
  39204. if ( attributeData.isInteger ) {
  39205. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  39206. } else {
  39207. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  39208. }
  39209. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  39210. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  39211. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  39212. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  39213. }
  39214. }
  39215. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  39216. this.vaoCache[ key ] = vaoGPU;
  39217. return { vaoGPU, staticVao };
  39218. }
  39219. /**
  39220. * Creates a tranform feedback from the given transform buffers.
  39221. *
  39222. * @private
  39223. * @param {Array<DualAttributeData>} transformBuffers - The tranform buffers.
  39224. * @return {WebGLTransformFeedback} The tranform feedback.
  39225. */
  39226. _getTransformFeedback( transformBuffers ) {
  39227. let key = '';
  39228. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  39229. key += ':' + transformBuffers[ i ].id;
  39230. }
  39231. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  39232. if ( transformFeedbackGPU !== undefined ) {
  39233. return transformFeedbackGPU;
  39234. }
  39235. const { gl } = this;
  39236. transformFeedbackGPU = gl.createTransformFeedback();
  39237. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  39238. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  39239. const attributeData = transformBuffers[ i ];
  39240. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  39241. }
  39242. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  39243. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  39244. return transformFeedbackGPU;
  39245. }
  39246. /**
  39247. * Setups the given bindings.
  39248. *
  39249. * @private
  39250. * @param {Array<BindGroup>} bindings - The bindings.
  39251. * @param {WebGLProgram} programGPU - The WebGL program.
  39252. */
  39253. _setupBindings( bindings, programGPU ) {
  39254. const gl = this.gl;
  39255. for ( const bindGroup of bindings ) {
  39256. for ( const binding of bindGroup.bindings ) {
  39257. const bindingData = this.get( binding );
  39258. const index = bindingData.index;
  39259. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  39260. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  39261. gl.uniformBlockBinding( programGPU, location, index );
  39262. } else if ( binding.isSampledTexture ) {
  39263. const location = gl.getUniformLocation( programGPU, binding.name );
  39264. gl.uniform1i( location, index );
  39265. }
  39266. }
  39267. }
  39268. }
  39269. /**
  39270. * Binds the given uniforms.
  39271. *
  39272. * @private
  39273. * @param {Array<BindGroup>} bindings - The bindings.
  39274. */
  39275. _bindUniforms( bindings ) {
  39276. const { gl, state } = this;
  39277. for ( const bindGroup of bindings ) {
  39278. for ( const binding of bindGroup.bindings ) {
  39279. const bindingData = this.get( binding );
  39280. const index = bindingData.index;
  39281. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  39282. // TODO USE bindBufferRange to group multiple uniform buffers
  39283. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  39284. } else if ( binding.isSampledTexture ) {
  39285. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  39286. }
  39287. }
  39288. }
  39289. }
  39290. /**
  39291. * Frees internal resources.
  39292. */
  39293. dispose() {
  39294. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  39295. }
  39296. }
  39297. const GPUPrimitiveTopology = {
  39298. PointList: 'point-list',
  39299. LineList: 'line-list',
  39300. LineStrip: 'line-strip',
  39301. TriangleList: 'triangle-list',
  39302. TriangleStrip: 'triangle-strip',
  39303. };
  39304. const GPUCompareFunction = {
  39305. Never: 'never',
  39306. Less: 'less',
  39307. Equal: 'equal',
  39308. LessEqual: 'less-equal',
  39309. Greater: 'greater',
  39310. NotEqual: 'not-equal',
  39311. GreaterEqual: 'greater-equal',
  39312. Always: 'always'
  39313. };
  39314. const GPUStoreOp = {
  39315. Store: 'store',
  39316. Discard: 'discard'
  39317. };
  39318. const GPULoadOp = {
  39319. Load: 'load',
  39320. Clear: 'clear'
  39321. };
  39322. const GPUFrontFace = {
  39323. CCW: 'ccw',
  39324. CW: 'cw'
  39325. };
  39326. const GPUCullMode = {
  39327. None: 'none',
  39328. Front: 'front',
  39329. Back: 'back'
  39330. };
  39331. const GPUIndexFormat = {
  39332. Uint16: 'uint16',
  39333. Uint32: 'uint32'
  39334. };
  39335. const GPUTextureFormat = {
  39336. // 8-bit formats
  39337. R8Unorm: 'r8unorm',
  39338. R8Snorm: 'r8snorm',
  39339. R8Uint: 'r8uint',
  39340. R8Sint: 'r8sint',
  39341. // 16-bit formats
  39342. R16Uint: 'r16uint',
  39343. R16Sint: 'r16sint',
  39344. R16Float: 'r16float',
  39345. RG8Unorm: 'rg8unorm',
  39346. RG8Snorm: 'rg8snorm',
  39347. RG8Uint: 'rg8uint',
  39348. RG8Sint: 'rg8sint',
  39349. // 32-bit formats
  39350. R32Uint: 'r32uint',
  39351. R32Sint: 'r32sint',
  39352. R32Float: 'r32float',
  39353. RG16Uint: 'rg16uint',
  39354. RG16Sint: 'rg16sint',
  39355. RG16Float: 'rg16float',
  39356. RGBA8Unorm: 'rgba8unorm',
  39357. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  39358. RGBA8Snorm: 'rgba8snorm',
  39359. RGBA8Uint: 'rgba8uint',
  39360. RGBA8Sint: 'rgba8sint',
  39361. BGRA8Unorm: 'bgra8unorm',
  39362. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  39363. // Packed 32-bit formats
  39364. RGB9E5UFloat: 'rgb9e5ufloat',
  39365. RGB10A2Unorm: 'rgb10a2unorm',
  39366. RG11B10uFloat: 'rgb10a2unorm',
  39367. // 64-bit formats
  39368. RG32Uint: 'rg32uint',
  39369. RG32Sint: 'rg32sint',
  39370. RG32Float: 'rg32float',
  39371. RGBA16Uint: 'rgba16uint',
  39372. RGBA16Sint: 'rgba16sint',
  39373. RGBA16Float: 'rgba16float',
  39374. // 128-bit formats
  39375. RGBA32Uint: 'rgba32uint',
  39376. RGBA32Sint: 'rgba32sint',
  39377. RGBA32Float: 'rgba32float',
  39378. // Depth and stencil formats
  39379. Stencil8: 'stencil8',
  39380. Depth16Unorm: 'depth16unorm',
  39381. Depth24Plus: 'depth24plus',
  39382. Depth24PlusStencil8: 'depth24plus-stencil8',
  39383. Depth32Float: 'depth32float',
  39384. // 'depth32float-stencil8' extension
  39385. Depth32FloatStencil8: 'depth32float-stencil8',
  39386. // BC compressed formats usable if 'texture-compression-bc' is both
  39387. // supported by the device/user agent and enabled in requestDevice.
  39388. BC1RGBAUnorm: 'bc1-rgba-unorm',
  39389. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  39390. BC2RGBAUnorm: 'bc2-rgba-unorm',
  39391. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  39392. BC3RGBAUnorm: 'bc3-rgba-unorm',
  39393. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  39394. BC4RUnorm: 'bc4-r-unorm',
  39395. BC4RSnorm: 'bc4-r-snorm',
  39396. BC5RGUnorm: 'bc5-rg-unorm',
  39397. BC5RGSnorm: 'bc5-rg-snorm',
  39398. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  39399. BC6HRGBFloat: 'bc6h-rgb-float',
  39400. BC7RGBAUnorm: 'bc7-rgba-unorm',
  39401. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  39402. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  39403. // supported by the device/user agent and enabled in requestDevice.
  39404. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  39405. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  39406. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  39407. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  39408. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  39409. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  39410. EACR11Unorm: 'eac-r11unorm',
  39411. EACR11Snorm: 'eac-r11snorm',
  39412. EACRG11Unorm: 'eac-rg11unorm',
  39413. EACRG11Snorm: 'eac-rg11snorm',
  39414. // ASTC compressed formats usable if 'texture-compression-astc' is both
  39415. // supported by the device/user agent and enabled in requestDevice.
  39416. ASTC4x4Unorm: 'astc-4x4-unorm',
  39417. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  39418. ASTC5x4Unorm: 'astc-5x4-unorm',
  39419. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  39420. ASTC5x5Unorm: 'astc-5x5-unorm',
  39421. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  39422. ASTC6x5Unorm: 'astc-6x5-unorm',
  39423. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  39424. ASTC6x6Unorm: 'astc-6x6-unorm',
  39425. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  39426. ASTC8x5Unorm: 'astc-8x5-unorm',
  39427. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  39428. ASTC8x6Unorm: 'astc-8x6-unorm',
  39429. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  39430. ASTC8x8Unorm: 'astc-8x8-unorm',
  39431. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  39432. ASTC10x5Unorm: 'astc-10x5-unorm',
  39433. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  39434. ASTC10x6Unorm: 'astc-10x6-unorm',
  39435. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  39436. ASTC10x8Unorm: 'astc-10x8-unorm',
  39437. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  39438. ASTC10x10Unorm: 'astc-10x10-unorm',
  39439. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  39440. ASTC12x10Unorm: 'astc-12x10-unorm',
  39441. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  39442. ASTC12x12Unorm: 'astc-12x12-unorm',
  39443. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  39444. };
  39445. const GPUAddressMode = {
  39446. ClampToEdge: 'clamp-to-edge',
  39447. Repeat: 'repeat',
  39448. MirrorRepeat: 'mirror-repeat'
  39449. };
  39450. const GPUFilterMode = {
  39451. Linear: 'linear',
  39452. Nearest: 'nearest'
  39453. };
  39454. const GPUBlendFactor = {
  39455. Zero: 'zero',
  39456. One: 'one',
  39457. Src: 'src',
  39458. OneMinusSrc: 'one-minus-src',
  39459. SrcAlpha: 'src-alpha',
  39460. OneMinusSrcAlpha: 'one-minus-src-alpha',
  39461. Dst: 'dst',
  39462. OneMinusDstColor: 'one-minus-dst',
  39463. DstAlpha: 'dst-alpha',
  39464. OneMinusDstAlpha: 'one-minus-dst-alpha',
  39465. SrcAlphaSaturated: 'src-alpha-saturated',
  39466. Constant: 'constant',
  39467. OneMinusConstant: 'one-minus-constant'
  39468. };
  39469. const GPUBlendOperation = {
  39470. Add: 'add',
  39471. Subtract: 'subtract',
  39472. ReverseSubtract: 'reverse-subtract',
  39473. Min: 'min',
  39474. Max: 'max'
  39475. };
  39476. const GPUColorWriteFlags = {
  39477. None: 0,
  39478. Red: 0x1,
  39479. Green: 0x2,
  39480. Blue: 0x4,
  39481. Alpha: 0x8,
  39482. All: 0xF
  39483. };
  39484. const GPUStencilOperation = {
  39485. Keep: 'keep',
  39486. Zero: 'zero',
  39487. Replace: 'replace',
  39488. Invert: 'invert',
  39489. IncrementClamp: 'increment-clamp',
  39490. DecrementClamp: 'decrement-clamp',
  39491. IncrementWrap: 'increment-wrap',
  39492. DecrementWrap: 'decrement-wrap'
  39493. };
  39494. const GPUBufferBindingType = {
  39495. Uniform: 'uniform',
  39496. Storage: 'storage',
  39497. ReadOnlyStorage: 'read-only-storage'
  39498. };
  39499. const GPUStorageTextureAccess = {
  39500. WriteOnly: 'write-only',
  39501. ReadOnly: 'read-only',
  39502. ReadWrite: 'read-write',
  39503. };
  39504. const GPUTextureSampleType = {
  39505. Float: 'float',
  39506. UnfilterableFloat: 'unfilterable-float',
  39507. Depth: 'depth',
  39508. SInt: 'sint',
  39509. UInt: 'uint'
  39510. };
  39511. const GPUTextureDimension = {
  39512. OneD: '1d',
  39513. TwoD: '2d',
  39514. ThreeD: '3d'
  39515. };
  39516. const GPUTextureViewDimension = {
  39517. OneD: '1d',
  39518. TwoD: '2d',
  39519. TwoDArray: '2d-array',
  39520. Cube: 'cube',
  39521. CubeArray: 'cube-array',
  39522. ThreeD: '3d'
  39523. };
  39524. const GPUTextureAspect = {
  39525. All: 'all',
  39526. StencilOnly: 'stencil-only',
  39527. DepthOnly: 'depth-only'
  39528. };
  39529. const GPUInputStepMode = {
  39530. Vertex: 'vertex',
  39531. Instance: 'instance'
  39532. };
  39533. const GPUFeatureName = {
  39534. DepthClipControl: 'depth-clip-control',
  39535. Depth32FloatStencil8: 'depth32float-stencil8',
  39536. TextureCompressionBC: 'texture-compression-bc',
  39537. TextureCompressionETC2: 'texture-compression-etc2',
  39538. TextureCompressionASTC: 'texture-compression-astc',
  39539. TimestampQuery: 'timestamp-query',
  39540. IndirectFirstInstance: 'indirect-first-instance',
  39541. ShaderF16: 'shader-f16',
  39542. RG11B10UFloat: 'rg11b10ufloat-renderable',
  39543. BGRA8UNormStorage: 'bgra8unorm-storage',
  39544. Float32Filterable: 'float32-filterable',
  39545. ClipDistances: 'clip-distances',
  39546. DualSourceBlending: 'dual-source-blending',
  39547. Subgroups: 'subgroups'
  39548. };
  39549. /**
  39550. * Represents a sampler binding type.
  39551. *
  39552. * @private
  39553. * @augments Binding
  39554. */
  39555. class Sampler extends Binding {
  39556. /**
  39557. * Constructs a new sampler.
  39558. *
  39559. * @param {String} name - The samplers's name.
  39560. * @param {Texture?} texture - The texture this binding is referring to.
  39561. */
  39562. constructor( name, texture ) {
  39563. super( name );
  39564. /**
  39565. * The texture the sampler is referring to.
  39566. *
  39567. * @type {Texture?}
  39568. */
  39569. this.texture = texture;
  39570. /**
  39571. * The binding's version.
  39572. *
  39573. * @type {Number}
  39574. */
  39575. this.version = texture ? texture.version : 0;
  39576. /**
  39577. * This flag can be used for type testing.
  39578. *
  39579. * @type {Boolean}
  39580. * @readonly
  39581. * @default true
  39582. */
  39583. this.isSampler = true;
  39584. }
  39585. }
  39586. /**
  39587. * A special form of sampler binding type.
  39588. * It's texture value is managed by a node object.
  39589. *
  39590. * @private
  39591. * @augments Sampler
  39592. */
  39593. class NodeSampler extends Sampler {
  39594. /**
  39595. * Constructs a new node-based sampler.
  39596. *
  39597. * @param {String} name - The samplers's name.
  39598. * @param {TextureNode} textureNode - The texture node.
  39599. * @param {UniformGroupNode} groupNode - The uniform group node.
  39600. */
  39601. constructor( name, textureNode, groupNode ) {
  39602. super( name, textureNode ? textureNode.value : null );
  39603. /**
  39604. * The texture node.
  39605. *
  39606. * @type {TextureNode}
  39607. */
  39608. this.textureNode = textureNode;
  39609. /**
  39610. * The uniform group node.
  39611. *
  39612. * @type {UniformGroupNode}
  39613. */
  39614. this.groupNode = groupNode;
  39615. }
  39616. /**
  39617. * Updates the texture value of this sampler.
  39618. */
  39619. update() {
  39620. this.texture = this.textureNode.value;
  39621. }
  39622. }
  39623. /**
  39624. * Represents a storage buffer binding type.
  39625. *
  39626. * @private
  39627. * @augments Buffer
  39628. */
  39629. class StorageBuffer extends Buffer {
  39630. /**
  39631. * Constructs a new uniform buffer.
  39632. *
  39633. * @param {String} name - The buffer's name.
  39634. * @param {BufferAttribute} attribute - The buffer attribute.
  39635. */
  39636. constructor( name, attribute ) {
  39637. super( name, attribute ? attribute.array : null );
  39638. /**
  39639. * This flag can be used for type testing.
  39640. *
  39641. * @type {BufferAttribute}
  39642. */
  39643. this.attribute = attribute;
  39644. /**
  39645. * This flag can be used for type testing.
  39646. *
  39647. * @type {Boolean}
  39648. * @readonly
  39649. * @default true
  39650. */
  39651. this.isStorageBuffer = true;
  39652. }
  39653. }
  39654. let _id = 0;
  39655. /**
  39656. * A special form of storage buffer binding type.
  39657. * It's buffer value is managed by a node object.
  39658. *
  39659. * @private
  39660. * @augments StorageBuffer
  39661. */
  39662. class NodeStorageBuffer extends StorageBuffer {
  39663. /**
  39664. * Constructs a new node-based storage buffer.
  39665. *
  39666. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  39667. * @param {UniformGroupNode} groupNode - The uniform group node.
  39668. */
  39669. constructor( nodeUniform, groupNode ) {
  39670. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  39671. /**
  39672. * The node uniform.
  39673. *
  39674. * @type {StorageBufferNode}
  39675. */
  39676. this.nodeUniform = nodeUniform;
  39677. /**
  39678. * The access type.
  39679. *
  39680. * @type {String}
  39681. */
  39682. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  39683. /**
  39684. * The uniform group node.
  39685. *
  39686. * @type {UniformGroupNode}
  39687. */
  39688. this.groupNode = groupNode;
  39689. }
  39690. /**
  39691. * The storage buffer.
  39692. *
  39693. * @type {BufferAttribute}
  39694. */
  39695. get buffer() {
  39696. return this.nodeUniform.value;
  39697. }
  39698. }
  39699. class WebGPUTexturePassUtils extends DataMap {
  39700. constructor( device ) {
  39701. super();
  39702. this.device = device;
  39703. const mipmapVertexSource = `
  39704. struct VarysStruct {
  39705. @builtin( position ) Position: vec4<f32>,
  39706. @location( 0 ) vTex : vec2<f32>
  39707. };
  39708. @vertex
  39709. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  39710. var Varys : VarysStruct;
  39711. var pos = array< vec2<f32>, 4 >(
  39712. vec2<f32>( -1.0, 1.0 ),
  39713. vec2<f32>( 1.0, 1.0 ),
  39714. vec2<f32>( -1.0, -1.0 ),
  39715. vec2<f32>( 1.0, -1.0 )
  39716. );
  39717. var tex = array< vec2<f32>, 4 >(
  39718. vec2<f32>( 0.0, 0.0 ),
  39719. vec2<f32>( 1.0, 0.0 ),
  39720. vec2<f32>( 0.0, 1.0 ),
  39721. vec2<f32>( 1.0, 1.0 )
  39722. );
  39723. Varys.vTex = tex[ vertexIndex ];
  39724. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  39725. return Varys;
  39726. }
  39727. `;
  39728. const mipmapFragmentSource = `
  39729. @group( 0 ) @binding( 0 )
  39730. var imgSampler : sampler;
  39731. @group( 0 ) @binding( 1 )
  39732. var img : texture_2d<f32>;
  39733. @fragment
  39734. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  39735. return textureSample( img, imgSampler, vTex );
  39736. }
  39737. `;
  39738. const flipYFragmentSource = `
  39739. @group( 0 ) @binding( 0 )
  39740. var imgSampler : sampler;
  39741. @group( 0 ) @binding( 1 )
  39742. var img : texture_2d<f32>;
  39743. @fragment
  39744. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  39745. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  39746. }
  39747. `;
  39748. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  39749. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  39750. // We'll need a new pipeline for every texture format used.
  39751. this.transferPipelines = {};
  39752. this.flipYPipelines = {};
  39753. this.mipmapVertexShaderModule = device.createShaderModule( {
  39754. label: 'mipmapVertex',
  39755. code: mipmapVertexSource
  39756. } );
  39757. this.mipmapFragmentShaderModule = device.createShaderModule( {
  39758. label: 'mipmapFragment',
  39759. code: mipmapFragmentSource
  39760. } );
  39761. this.flipYFragmentShaderModule = device.createShaderModule( {
  39762. label: 'flipYFragment',
  39763. code: flipYFragmentSource
  39764. } );
  39765. }
  39766. getTransferPipeline( format ) {
  39767. let pipeline = this.transferPipelines[ format ];
  39768. if ( pipeline === undefined ) {
  39769. pipeline = this.device.createRenderPipeline( {
  39770. label: `mipmap-${ format }`,
  39771. vertex: {
  39772. module: this.mipmapVertexShaderModule,
  39773. entryPoint: 'main'
  39774. },
  39775. fragment: {
  39776. module: this.mipmapFragmentShaderModule,
  39777. entryPoint: 'main',
  39778. targets: [ { format } ]
  39779. },
  39780. primitive: {
  39781. topology: GPUPrimitiveTopology.TriangleStrip,
  39782. stripIndexFormat: GPUIndexFormat.Uint32
  39783. },
  39784. layout: 'auto'
  39785. } );
  39786. this.transferPipelines[ format ] = pipeline;
  39787. }
  39788. return pipeline;
  39789. }
  39790. getFlipYPipeline( format ) {
  39791. let pipeline = this.flipYPipelines[ format ];
  39792. if ( pipeline === undefined ) {
  39793. pipeline = this.device.createRenderPipeline( {
  39794. label: `flipY-${ format }`,
  39795. vertex: {
  39796. module: this.mipmapVertexShaderModule,
  39797. entryPoint: 'main'
  39798. },
  39799. fragment: {
  39800. module: this.flipYFragmentShaderModule,
  39801. entryPoint: 'main',
  39802. targets: [ { format } ]
  39803. },
  39804. primitive: {
  39805. topology: GPUPrimitiveTopology.TriangleStrip,
  39806. stripIndexFormat: GPUIndexFormat.Uint32
  39807. },
  39808. layout: 'auto'
  39809. } );
  39810. this.flipYPipelines[ format ] = pipeline;
  39811. }
  39812. return pipeline;
  39813. }
  39814. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  39815. const format = textureGPUDescriptor.format;
  39816. const { width, height } = textureGPUDescriptor.size;
  39817. const transferPipeline = this.getTransferPipeline( format );
  39818. const flipYPipeline = this.getFlipYPipeline( format );
  39819. const tempTexture = this.device.createTexture( {
  39820. size: { width, height, depthOrArrayLayers: 1 },
  39821. format,
  39822. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  39823. } );
  39824. const srcView = textureGPU.createView( {
  39825. baseMipLevel: 0,
  39826. mipLevelCount: 1,
  39827. dimension: GPUTextureViewDimension.TwoD,
  39828. baseArrayLayer
  39829. } );
  39830. const dstView = tempTexture.createView( {
  39831. baseMipLevel: 0,
  39832. mipLevelCount: 1,
  39833. dimension: GPUTextureViewDimension.TwoD,
  39834. baseArrayLayer: 0
  39835. } );
  39836. const commandEncoder = this.device.createCommandEncoder( {} );
  39837. const pass = ( pipeline, sourceView, destinationView ) => {
  39838. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  39839. const bindGroup = this.device.createBindGroup( {
  39840. layout: bindGroupLayout,
  39841. entries: [ {
  39842. binding: 0,
  39843. resource: this.flipYSampler
  39844. }, {
  39845. binding: 1,
  39846. resource: sourceView
  39847. } ]
  39848. } );
  39849. const passEncoder = commandEncoder.beginRenderPass( {
  39850. colorAttachments: [ {
  39851. view: destinationView,
  39852. loadOp: GPULoadOp.Clear,
  39853. storeOp: GPUStoreOp.Store,
  39854. clearValue: [ 0, 0, 0, 0 ]
  39855. } ]
  39856. } );
  39857. passEncoder.setPipeline( pipeline );
  39858. passEncoder.setBindGroup( 0, bindGroup );
  39859. passEncoder.draw( 4, 1, 0, 0 );
  39860. passEncoder.end();
  39861. };
  39862. pass( transferPipeline, srcView, dstView );
  39863. pass( flipYPipeline, dstView, srcView );
  39864. this.device.queue.submit( [ commandEncoder.finish() ] );
  39865. tempTexture.destroy();
  39866. }
  39867. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  39868. const textureData = this.get( textureGPU );
  39869. if ( textureData.useCount === undefined ) {
  39870. textureData.useCount = 0;
  39871. textureData.layers = [];
  39872. }
  39873. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  39874. const commandEncoder = this.device.createCommandEncoder( {} );
  39875. this._mipmapRunBundles( commandEncoder, passes );
  39876. this.device.queue.submit( [ commandEncoder.finish() ] );
  39877. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  39878. textureData.useCount ++;
  39879. }
  39880. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  39881. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  39882. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  39883. let srcView = textureGPU.createView( {
  39884. baseMipLevel: 0,
  39885. mipLevelCount: 1,
  39886. dimension: GPUTextureViewDimension.TwoD,
  39887. baseArrayLayer
  39888. } );
  39889. const passes = [];
  39890. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  39891. const bindGroup = this.device.createBindGroup( {
  39892. layout: bindGroupLayout,
  39893. entries: [ {
  39894. binding: 0,
  39895. resource: this.mipmapSampler
  39896. }, {
  39897. binding: 1,
  39898. resource: srcView
  39899. } ]
  39900. } );
  39901. const dstView = textureGPU.createView( {
  39902. baseMipLevel: i,
  39903. mipLevelCount: 1,
  39904. dimension: GPUTextureViewDimension.TwoD,
  39905. baseArrayLayer
  39906. } );
  39907. const passDescriptor = {
  39908. colorAttachments: [ {
  39909. view: dstView,
  39910. loadOp: GPULoadOp.Clear,
  39911. storeOp: GPUStoreOp.Store,
  39912. clearValue: [ 0, 0, 0, 0 ]
  39913. } ]
  39914. };
  39915. const passEncoder = this.device.createRenderBundleEncoder( {
  39916. colorFormats: [ textureGPUDescriptor.format ]
  39917. } );
  39918. passEncoder.setPipeline( pipeline );
  39919. passEncoder.setBindGroup( 0, bindGroup );
  39920. passEncoder.draw( 4, 1, 0, 0 );
  39921. passes.push( {
  39922. renderBundles: [ passEncoder.finish() ],
  39923. passDescriptor
  39924. } );
  39925. srcView = dstView;
  39926. }
  39927. return passes;
  39928. }
  39929. _mipmapRunBundles( commandEncoder, passes ) {
  39930. const levels = passes.length;
  39931. for ( let i = 0; i < levels; i ++ ) {
  39932. const pass = passes[ i ];
  39933. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  39934. passEncoder.executeBundles( pass.renderBundles );
  39935. passEncoder.end();
  39936. }
  39937. }
  39938. }
  39939. const _compareToWebGPU = {
  39940. [ NeverCompare ]: 'never',
  39941. [ LessCompare ]: 'less',
  39942. [ EqualCompare ]: 'equal',
  39943. [ LessEqualCompare ]: 'less-equal',
  39944. [ GreaterCompare ]: 'greater',
  39945. [ GreaterEqualCompare ]: 'greater-equal',
  39946. [ AlwaysCompare ]: 'always',
  39947. [ NotEqualCompare ]: 'not-equal'
  39948. };
  39949. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  39950. class WebGPUTextureUtils {
  39951. constructor( backend ) {
  39952. this.backend = backend;
  39953. this._passUtils = null;
  39954. this.defaultTexture = {};
  39955. this.defaultCubeTexture = {};
  39956. this.defaultVideoFrame = null;
  39957. this.colorBuffer = null;
  39958. this.depthTexture = new DepthTexture();
  39959. this.depthTexture.name = 'depthBuffer';
  39960. }
  39961. createSampler( texture ) {
  39962. const backend = this.backend;
  39963. const device = backend.device;
  39964. const textureGPU = backend.get( texture );
  39965. const samplerDescriptorGPU = {
  39966. addressModeU: this._convertAddressMode( texture.wrapS ),
  39967. addressModeV: this._convertAddressMode( texture.wrapT ),
  39968. addressModeW: this._convertAddressMode( texture.wrapR ),
  39969. magFilter: this._convertFilterMode( texture.magFilter ),
  39970. minFilter: this._convertFilterMode( texture.minFilter ),
  39971. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  39972. maxAnisotropy: 1
  39973. };
  39974. // anisotropy can only be used when all filter modes are set to linear.
  39975. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  39976. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  39977. }
  39978. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  39979. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  39980. }
  39981. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  39982. }
  39983. createDefaultTexture( texture ) {
  39984. let textureGPU;
  39985. const format = getFormat( texture );
  39986. if ( texture.isCubeTexture ) {
  39987. textureGPU = this._getDefaultCubeTextureGPU( format );
  39988. } else if ( texture.isVideoTexture ) {
  39989. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  39990. } else {
  39991. textureGPU = this._getDefaultTextureGPU( format );
  39992. }
  39993. this.backend.get( texture ).texture = textureGPU;
  39994. }
  39995. createTexture( texture, options = {} ) {
  39996. const backend = this.backend;
  39997. const textureData = backend.get( texture );
  39998. if ( textureData.initialized ) {
  39999. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  40000. }
  40001. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  40002. if ( options.levels === undefined ) options.levels = 1;
  40003. if ( options.depth === undefined ) options.depth = 1;
  40004. const { width, height, depth, levels } = options;
  40005. if ( texture.isFramebufferTexture ) {
  40006. if ( options.renderTarget ) {
  40007. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  40008. } else {
  40009. options.format = this.backend.utils.getPreferredCanvasFormat();
  40010. }
  40011. }
  40012. const dimension = this._getDimension( texture );
  40013. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  40014. textureData.format = format;
  40015. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  40016. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  40017. if ( texture.isStorageTexture === true ) {
  40018. usage |= GPUTextureUsage.STORAGE_BINDING;
  40019. }
  40020. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  40021. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  40022. }
  40023. const textureDescriptorGPU = {
  40024. label: texture.name,
  40025. size: {
  40026. width: width,
  40027. height: height,
  40028. depthOrArrayLayers: depth,
  40029. },
  40030. mipLevelCount: levels,
  40031. sampleCount: primarySamples,
  40032. dimension: dimension,
  40033. format: format,
  40034. usage: usage
  40035. };
  40036. // texture creation
  40037. if ( texture.isVideoTexture ) {
  40038. const video = texture.source.data;
  40039. const videoFrame = new VideoFrame( video );
  40040. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  40041. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  40042. videoFrame.close();
  40043. textureData.externalTexture = video;
  40044. } else {
  40045. if ( format === undefined ) {
  40046. console.warn( 'WebGPURenderer: Texture format not supported.' );
  40047. return this.createDefaultTexture( texture );
  40048. }
  40049. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  40050. }
  40051. if ( isMSAA ) {
  40052. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  40053. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  40054. msaaTextureDescriptorGPU.sampleCount = samples;
  40055. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  40056. }
  40057. textureData.initialized = true;
  40058. textureData.textureDescriptorGPU = textureDescriptorGPU;
  40059. }
  40060. destroyTexture( texture ) {
  40061. const backend = this.backend;
  40062. const textureData = backend.get( texture );
  40063. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  40064. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  40065. backend.delete( texture );
  40066. }
  40067. destroySampler( texture ) {
  40068. const backend = this.backend;
  40069. const textureData = backend.get( texture );
  40070. delete textureData.sampler;
  40071. }
  40072. generateMipmaps( texture ) {
  40073. const textureData = this.backend.get( texture );
  40074. if ( texture.isCubeTexture ) {
  40075. for ( let i = 0; i < 6; i ++ ) {
  40076. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  40077. }
  40078. } else {
  40079. const depth = texture.image.depth || 1;
  40080. for ( let i = 0; i < depth; i ++ ) {
  40081. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  40082. }
  40083. }
  40084. }
  40085. getColorBuffer() {
  40086. if ( this.colorBuffer ) this.colorBuffer.destroy();
  40087. const backend = this.backend;
  40088. const { width, height } = backend.getDrawingBufferSize();
  40089. this.colorBuffer = backend.device.createTexture( {
  40090. label: 'colorBuffer',
  40091. size: {
  40092. width: width,
  40093. height: height,
  40094. depthOrArrayLayers: 1
  40095. },
  40096. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  40097. format: backend.utils.getPreferredCanvasFormat(),
  40098. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  40099. } );
  40100. return this.colorBuffer;
  40101. }
  40102. getDepthBuffer( depth = true, stencil = false ) {
  40103. const backend = this.backend;
  40104. const { width, height } = backend.getDrawingBufferSize();
  40105. const depthTexture = this.depthTexture;
  40106. const depthTextureGPU = backend.get( depthTexture ).texture;
  40107. let format, type;
  40108. if ( stencil ) {
  40109. format = DepthStencilFormat;
  40110. type = UnsignedInt248Type;
  40111. } else if ( depth ) {
  40112. format = DepthFormat;
  40113. type = UnsignedIntType;
  40114. }
  40115. if ( depthTextureGPU !== undefined ) {
  40116. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  40117. return depthTextureGPU;
  40118. }
  40119. this.destroyTexture( depthTexture );
  40120. }
  40121. depthTexture.name = 'depthBuffer';
  40122. depthTexture.format = format;
  40123. depthTexture.type = type;
  40124. depthTexture.image.width = width;
  40125. depthTexture.image.height = height;
  40126. this.createTexture( depthTexture, { width, height } );
  40127. return backend.get( depthTexture ).texture;
  40128. }
  40129. updateTexture( texture, options ) {
  40130. const textureData = this.backend.get( texture );
  40131. const { textureDescriptorGPU } = textureData;
  40132. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  40133. return;
  40134. // transfer texture data
  40135. if ( texture.isDataTexture ) {
  40136. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  40137. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  40138. for ( let i = 0; i < options.image.depth; i ++ ) {
  40139. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  40140. }
  40141. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  40142. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  40143. } else if ( texture.isCubeTexture ) {
  40144. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  40145. } else if ( texture.isVideoTexture ) {
  40146. const video = texture.source.data;
  40147. textureData.externalTexture = video;
  40148. } else {
  40149. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  40150. }
  40151. //
  40152. textureData.version = texture.version;
  40153. if ( texture.onUpdate ) texture.onUpdate( texture );
  40154. }
  40155. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  40156. const device = this.backend.device;
  40157. const textureData = this.backend.get( texture );
  40158. const textureGPU = textureData.texture;
  40159. const format = textureData.textureDescriptorGPU.format;
  40160. const bytesPerTexel = this._getBytesPerTexel( format );
  40161. let bytesPerRow = width * bytesPerTexel;
  40162. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  40163. const readBuffer = device.createBuffer(
  40164. {
  40165. size: width * height * bytesPerTexel,
  40166. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  40167. }
  40168. );
  40169. const encoder = device.createCommandEncoder();
  40170. encoder.copyTextureToBuffer(
  40171. {
  40172. texture: textureGPU,
  40173. origin: { x, y, z: faceIndex },
  40174. },
  40175. {
  40176. buffer: readBuffer,
  40177. bytesPerRow: bytesPerRow
  40178. },
  40179. {
  40180. width: width,
  40181. height: height
  40182. }
  40183. );
  40184. const typedArrayType = this._getTypedArrayType( format );
  40185. device.queue.submit( [ encoder.finish() ] );
  40186. await readBuffer.mapAsync( GPUMapMode.READ );
  40187. const buffer = readBuffer.getMappedRange();
  40188. return new typedArrayType( buffer );
  40189. }
  40190. _isEnvironmentTexture( texture ) {
  40191. const mapping = texture.mapping;
  40192. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  40193. }
  40194. _getDefaultTextureGPU( format ) {
  40195. let defaultTexture = this.defaultTexture[ format ];
  40196. if ( defaultTexture === undefined ) {
  40197. const texture = new Texture();
  40198. texture.minFilter = NearestFilter;
  40199. texture.magFilter = NearestFilter;
  40200. this.createTexture( texture, { width: 1, height: 1, format } );
  40201. this.defaultTexture[ format ] = defaultTexture = texture;
  40202. }
  40203. return this.backend.get( defaultTexture ).texture;
  40204. }
  40205. _getDefaultCubeTextureGPU( format ) {
  40206. let defaultCubeTexture = this.defaultTexture[ format ];
  40207. if ( defaultCubeTexture === undefined ) {
  40208. const texture = new CubeTexture();
  40209. texture.minFilter = NearestFilter;
  40210. texture.magFilter = NearestFilter;
  40211. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  40212. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  40213. }
  40214. return this.backend.get( defaultCubeTexture ).texture;
  40215. }
  40216. _getDefaultVideoFrame() {
  40217. let defaultVideoFrame = this.defaultVideoFrame;
  40218. if ( defaultVideoFrame === null ) {
  40219. const init = {
  40220. timestamp: 0,
  40221. codedWidth: 1,
  40222. codedHeight: 1,
  40223. format: 'RGBA',
  40224. };
  40225. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  40226. }
  40227. return defaultVideoFrame;
  40228. }
  40229. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  40230. for ( let i = 0; i < 6; i ++ ) {
  40231. const image = images[ i ];
  40232. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  40233. if ( image.isDataTexture ) {
  40234. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  40235. } else {
  40236. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  40237. }
  40238. }
  40239. }
  40240. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  40241. const device = this.backend.device;
  40242. device.queue.copyExternalImageToTexture(
  40243. {
  40244. source: image
  40245. }, {
  40246. texture: textureGPU,
  40247. mipLevel: 0,
  40248. origin: { x: 0, y: 0, z: originDepth }
  40249. }, {
  40250. width: image.width,
  40251. height: image.height,
  40252. depthOrArrayLayers: 1
  40253. }
  40254. );
  40255. if ( flipY === true ) {
  40256. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  40257. }
  40258. }
  40259. _getPassUtils() {
  40260. let passUtils = this._passUtils;
  40261. if ( passUtils === null ) {
  40262. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  40263. }
  40264. return passUtils;
  40265. }
  40266. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  40267. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  40268. }
  40269. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  40270. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  40271. }
  40272. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  40273. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  40274. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  40275. const device = this.backend.device;
  40276. const data = image.data;
  40277. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  40278. const bytesPerRow = image.width * bytesPerTexel;
  40279. device.queue.writeTexture(
  40280. {
  40281. texture: textureGPU,
  40282. mipLevel: 0,
  40283. origin: { x: 0, y: 0, z: originDepth }
  40284. },
  40285. data,
  40286. {
  40287. offset: image.width * image.height * bytesPerTexel * depth,
  40288. bytesPerRow
  40289. },
  40290. {
  40291. width: image.width,
  40292. height: image.height,
  40293. depthOrArrayLayers: 1
  40294. } );
  40295. if ( flipY === true ) {
  40296. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  40297. }
  40298. }
  40299. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  40300. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  40301. const device = this.backend.device;
  40302. const blockData = this._getBlockData( textureDescriptorGPU.format );
  40303. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  40304. for ( let i = 0; i < mipmaps.length; i ++ ) {
  40305. const mipmap = mipmaps[ i ];
  40306. const width = mipmap.width;
  40307. const height = mipmap.height;
  40308. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  40309. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  40310. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  40311. for ( let j = 0; j < depth; j ++ ) {
  40312. device.queue.writeTexture(
  40313. {
  40314. texture: textureGPU,
  40315. mipLevel: i,
  40316. origin: { x: 0, y: 0, z: j }
  40317. },
  40318. mipmap.data,
  40319. {
  40320. offset: j * bytesPerImage,
  40321. bytesPerRow,
  40322. rowsPerImage: Math.ceil( height / blockData.height )
  40323. },
  40324. {
  40325. width: Math.ceil( width / blockData.width ) * blockData.width,
  40326. height: Math.ceil( height / blockData.height ) * blockData.height,
  40327. depthOrArrayLayers: 1
  40328. }
  40329. );
  40330. }
  40331. }
  40332. }
  40333. _getBlockData( format ) {
  40334. // this method is only relevant for compressed texture formats
  40335. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  40336. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  40337. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  40338. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  40339. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  40340. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  40341. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  40342. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  40343. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  40344. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  40345. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  40346. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  40347. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  40348. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  40349. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  40350. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  40351. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  40352. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  40353. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  40354. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  40355. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  40356. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  40357. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  40358. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  40359. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  40360. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  40361. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  40362. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  40363. }
  40364. _convertAddressMode( value ) {
  40365. let addressMode = GPUAddressMode.ClampToEdge;
  40366. if ( value === RepeatWrapping ) {
  40367. addressMode = GPUAddressMode.Repeat;
  40368. } else if ( value === MirroredRepeatWrapping ) {
  40369. addressMode = GPUAddressMode.MirrorRepeat;
  40370. }
  40371. return addressMode;
  40372. }
  40373. _convertFilterMode( value ) {
  40374. let filterMode = GPUFilterMode.Linear;
  40375. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  40376. filterMode = GPUFilterMode.Nearest;
  40377. }
  40378. return filterMode;
  40379. }
  40380. _getBytesPerTexel( format ) {
  40381. // 8-bit formats
  40382. if ( format === GPUTextureFormat.R8Unorm ||
  40383. format === GPUTextureFormat.R8Snorm ||
  40384. format === GPUTextureFormat.R8Uint ||
  40385. format === GPUTextureFormat.R8Sint ) return 1;
  40386. // 16-bit formats
  40387. if ( format === GPUTextureFormat.R16Uint ||
  40388. format === GPUTextureFormat.R16Sint ||
  40389. format === GPUTextureFormat.R16Float ||
  40390. format === GPUTextureFormat.RG8Unorm ||
  40391. format === GPUTextureFormat.RG8Snorm ||
  40392. format === GPUTextureFormat.RG8Uint ||
  40393. format === GPUTextureFormat.RG8Sint ) return 2;
  40394. // 32-bit formats
  40395. if ( format === GPUTextureFormat.R32Uint ||
  40396. format === GPUTextureFormat.R32Sint ||
  40397. format === GPUTextureFormat.R32Float ||
  40398. format === GPUTextureFormat.RG16Uint ||
  40399. format === GPUTextureFormat.RG16Sint ||
  40400. format === GPUTextureFormat.RG16Float ||
  40401. format === GPUTextureFormat.RGBA8Unorm ||
  40402. format === GPUTextureFormat.RGBA8UnormSRGB ||
  40403. format === GPUTextureFormat.RGBA8Snorm ||
  40404. format === GPUTextureFormat.RGBA8Uint ||
  40405. format === GPUTextureFormat.RGBA8Sint ||
  40406. format === GPUTextureFormat.BGRA8Unorm ||
  40407. format === GPUTextureFormat.BGRA8UnormSRGB ||
  40408. // Packed 32-bit formats
  40409. format === GPUTextureFormat.RGB9E5UFloat ||
  40410. format === GPUTextureFormat.RGB10A2Unorm ||
  40411. format === GPUTextureFormat.RG11B10UFloat ||
  40412. format === GPUTextureFormat.Depth32Float ||
  40413. format === GPUTextureFormat.Depth24Plus ||
  40414. format === GPUTextureFormat.Depth24PlusStencil8 ||
  40415. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  40416. // 64-bit formats
  40417. if ( format === GPUTextureFormat.RG32Uint ||
  40418. format === GPUTextureFormat.RG32Sint ||
  40419. format === GPUTextureFormat.RG32Float ||
  40420. format === GPUTextureFormat.RGBA16Uint ||
  40421. format === GPUTextureFormat.RGBA16Sint ||
  40422. format === GPUTextureFormat.RGBA16Float ) return 8;
  40423. // 128-bit formats
  40424. if ( format === GPUTextureFormat.RGBA32Uint ||
  40425. format === GPUTextureFormat.RGBA32Sint ||
  40426. format === GPUTextureFormat.RGBA32Float ) return 16;
  40427. }
  40428. _getTypedArrayType( format ) {
  40429. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  40430. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  40431. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  40432. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  40433. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  40434. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  40435. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  40436. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  40437. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  40438. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  40439. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  40440. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  40441. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  40442. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  40443. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  40444. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  40445. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  40446. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  40447. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  40448. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  40449. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  40450. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  40451. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  40452. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  40453. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  40454. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  40455. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  40456. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  40457. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  40458. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  40459. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  40460. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  40461. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  40462. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  40463. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  40464. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  40465. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  40466. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  40467. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  40468. }
  40469. _getDimension( texture ) {
  40470. let dimension;
  40471. if ( texture.isData3DTexture ) {
  40472. dimension = GPUTextureDimension.ThreeD;
  40473. } else {
  40474. dimension = GPUTextureDimension.TwoD;
  40475. }
  40476. return dimension;
  40477. }
  40478. }
  40479. function getFormat( texture, device = null ) {
  40480. const format = texture.format;
  40481. const type = texture.type;
  40482. const colorSpace = texture.colorSpace;
  40483. let formatGPU;
  40484. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  40485. switch ( format ) {
  40486. case RGBA_S3TC_DXT1_Format:
  40487. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  40488. break;
  40489. case RGBA_S3TC_DXT3_Format:
  40490. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  40491. break;
  40492. case RGBA_S3TC_DXT5_Format:
  40493. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  40494. break;
  40495. case RGB_ETC2_Format:
  40496. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  40497. break;
  40498. case RGBA_ETC2_EAC_Format:
  40499. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  40500. break;
  40501. case RGBA_ASTC_4x4_Format:
  40502. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  40503. break;
  40504. case RGBA_ASTC_5x4_Format:
  40505. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  40506. break;
  40507. case RGBA_ASTC_5x5_Format:
  40508. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  40509. break;
  40510. case RGBA_ASTC_6x5_Format:
  40511. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  40512. break;
  40513. case RGBA_ASTC_6x6_Format:
  40514. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  40515. break;
  40516. case RGBA_ASTC_8x5_Format:
  40517. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  40518. break;
  40519. case RGBA_ASTC_8x6_Format:
  40520. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  40521. break;
  40522. case RGBA_ASTC_8x8_Format:
  40523. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  40524. break;
  40525. case RGBA_ASTC_10x5_Format:
  40526. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  40527. break;
  40528. case RGBA_ASTC_10x6_Format:
  40529. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  40530. break;
  40531. case RGBA_ASTC_10x8_Format:
  40532. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  40533. break;
  40534. case RGBA_ASTC_10x10_Format:
  40535. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  40536. break;
  40537. case RGBA_ASTC_12x10_Format:
  40538. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  40539. break;
  40540. case RGBA_ASTC_12x12_Format:
  40541. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  40542. break;
  40543. case RGBAFormat:
  40544. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  40545. break;
  40546. default:
  40547. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  40548. }
  40549. } else {
  40550. switch ( format ) {
  40551. case RGBAFormat:
  40552. switch ( type ) {
  40553. case ByteType:
  40554. formatGPU = GPUTextureFormat.RGBA8Snorm;
  40555. break;
  40556. case ShortType:
  40557. formatGPU = GPUTextureFormat.RGBA16Sint;
  40558. break;
  40559. case UnsignedShortType:
  40560. formatGPU = GPUTextureFormat.RGBA16Uint;
  40561. break;
  40562. case UnsignedIntType:
  40563. formatGPU = GPUTextureFormat.RGBA32Uint;
  40564. break;
  40565. case IntType:
  40566. formatGPU = GPUTextureFormat.RGBA32Sint;
  40567. break;
  40568. case UnsignedByteType:
  40569. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  40570. break;
  40571. case HalfFloatType:
  40572. formatGPU = GPUTextureFormat.RGBA16Float;
  40573. break;
  40574. case FloatType:
  40575. formatGPU = GPUTextureFormat.RGBA32Float;
  40576. break;
  40577. default:
  40578. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  40579. }
  40580. break;
  40581. case RGBFormat:
  40582. switch ( type ) {
  40583. case UnsignedInt5999Type:
  40584. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  40585. break;
  40586. default:
  40587. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  40588. }
  40589. break;
  40590. case RedFormat:
  40591. switch ( type ) {
  40592. case ByteType:
  40593. formatGPU = GPUTextureFormat.R8Snorm;
  40594. break;
  40595. case ShortType:
  40596. formatGPU = GPUTextureFormat.R16Sint;
  40597. break;
  40598. case UnsignedShortType:
  40599. formatGPU = GPUTextureFormat.R16Uint;
  40600. break;
  40601. case UnsignedIntType:
  40602. formatGPU = GPUTextureFormat.R32Uint;
  40603. break;
  40604. case IntType:
  40605. formatGPU = GPUTextureFormat.R32Sint;
  40606. break;
  40607. case UnsignedByteType:
  40608. formatGPU = GPUTextureFormat.R8Unorm;
  40609. break;
  40610. case HalfFloatType:
  40611. formatGPU = GPUTextureFormat.R16Float;
  40612. break;
  40613. case FloatType:
  40614. formatGPU = GPUTextureFormat.R32Float;
  40615. break;
  40616. default:
  40617. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  40618. }
  40619. break;
  40620. case RGFormat:
  40621. switch ( type ) {
  40622. case ByteType:
  40623. formatGPU = GPUTextureFormat.RG8Snorm;
  40624. break;
  40625. case ShortType:
  40626. formatGPU = GPUTextureFormat.RG16Sint;
  40627. break;
  40628. case UnsignedShortType:
  40629. formatGPU = GPUTextureFormat.RG16Uint;
  40630. break;
  40631. case UnsignedIntType:
  40632. formatGPU = GPUTextureFormat.RG32Uint;
  40633. break;
  40634. case IntType:
  40635. formatGPU = GPUTextureFormat.RG32Sint;
  40636. break;
  40637. case UnsignedByteType:
  40638. formatGPU = GPUTextureFormat.RG8Unorm;
  40639. break;
  40640. case HalfFloatType:
  40641. formatGPU = GPUTextureFormat.RG16Float;
  40642. break;
  40643. case FloatType:
  40644. formatGPU = GPUTextureFormat.RG32Float;
  40645. break;
  40646. default:
  40647. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  40648. }
  40649. break;
  40650. case DepthFormat:
  40651. switch ( type ) {
  40652. case UnsignedShortType:
  40653. formatGPU = GPUTextureFormat.Depth16Unorm;
  40654. break;
  40655. case UnsignedIntType:
  40656. formatGPU = GPUTextureFormat.Depth24Plus;
  40657. break;
  40658. case FloatType:
  40659. formatGPU = GPUTextureFormat.Depth32Float;
  40660. break;
  40661. default:
  40662. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  40663. }
  40664. break;
  40665. case DepthStencilFormat:
  40666. switch ( type ) {
  40667. case UnsignedInt248Type:
  40668. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  40669. break;
  40670. case FloatType:
  40671. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  40672. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  40673. }
  40674. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  40675. break;
  40676. default:
  40677. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  40678. }
  40679. break;
  40680. case RedIntegerFormat:
  40681. switch ( type ) {
  40682. case IntType:
  40683. formatGPU = GPUTextureFormat.R32Sint;
  40684. break;
  40685. case UnsignedIntType:
  40686. formatGPU = GPUTextureFormat.R32Uint;
  40687. break;
  40688. default:
  40689. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  40690. }
  40691. break;
  40692. case RGIntegerFormat:
  40693. switch ( type ) {
  40694. case IntType:
  40695. formatGPU = GPUTextureFormat.RG32Sint;
  40696. break;
  40697. case UnsignedIntType:
  40698. formatGPU = GPUTextureFormat.RG32Uint;
  40699. break;
  40700. default:
  40701. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  40702. }
  40703. break;
  40704. case RGBAIntegerFormat:
  40705. switch ( type ) {
  40706. case IntType:
  40707. formatGPU = GPUTextureFormat.RGBA32Sint;
  40708. break;
  40709. case UnsignedIntType:
  40710. formatGPU = GPUTextureFormat.RGBA32Uint;
  40711. break;
  40712. default:
  40713. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  40714. }
  40715. break;
  40716. default:
  40717. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  40718. }
  40719. }
  40720. return formatGPU;
  40721. }
  40722. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  40723. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  40724. const wgslTypeLib$1 = {
  40725. 'f32': 'float',
  40726. 'i32': 'int',
  40727. 'u32': 'uint',
  40728. 'bool': 'bool',
  40729. 'vec2<f32>': 'vec2',
  40730. 'vec2<i32>': 'ivec2',
  40731. 'vec2<u32>': 'uvec2',
  40732. 'vec2<bool>': 'bvec2',
  40733. 'vec2f': 'vec2',
  40734. 'vec2i': 'ivec2',
  40735. 'vec2u': 'uvec2',
  40736. 'vec2b': 'bvec2',
  40737. 'vec3<f32>': 'vec3',
  40738. 'vec3<i32>': 'ivec3',
  40739. 'vec3<u32>': 'uvec3',
  40740. 'vec3<bool>': 'bvec3',
  40741. 'vec3f': 'vec3',
  40742. 'vec3i': 'ivec3',
  40743. 'vec3u': 'uvec3',
  40744. 'vec3b': 'bvec3',
  40745. 'vec4<f32>': 'vec4',
  40746. 'vec4<i32>': 'ivec4',
  40747. 'vec4<u32>': 'uvec4',
  40748. 'vec4<bool>': 'bvec4',
  40749. 'vec4f': 'vec4',
  40750. 'vec4i': 'ivec4',
  40751. 'vec4u': 'uvec4',
  40752. 'vec4b': 'bvec4',
  40753. 'mat2x2<f32>': 'mat2',
  40754. 'mat2x2f': 'mat2',
  40755. 'mat3x3<f32>': 'mat3',
  40756. 'mat3x3f': 'mat3',
  40757. 'mat4x4<f32>': 'mat4',
  40758. 'mat4x4f': 'mat4',
  40759. 'sampler': 'sampler',
  40760. 'texture_1d': 'texture',
  40761. 'texture_2d': 'texture',
  40762. 'texture_2d_array': 'texture',
  40763. 'texture_multisampled_2d': 'cubeTexture',
  40764. 'texture_depth_2d': 'depthTexture',
  40765. 'texture_depth_multisampled_2d': 'depthTexture',
  40766. 'texture_3d': 'texture3D',
  40767. 'texture_cube': 'cubeTexture',
  40768. 'texture_cube_array': 'cubeTexture',
  40769. 'texture_storage_1d': 'storageTexture',
  40770. 'texture_storage_2d': 'storageTexture',
  40771. 'texture_storage_2d_array': 'storageTexture',
  40772. 'texture_storage_3d': 'storageTexture'
  40773. };
  40774. const parse = ( source ) => {
  40775. source = source.trim();
  40776. const declaration = source.match( declarationRegexp );
  40777. if ( declaration !== null && declaration.length === 4 ) {
  40778. const inputsCode = declaration[ 2 ];
  40779. const propsMatches = [];
  40780. let match = null;
  40781. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  40782. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  40783. }
  40784. // Process matches to correctly pair names and types
  40785. const inputs = [];
  40786. for ( let i = 0; i < propsMatches.length; i ++ ) {
  40787. const { name, type } = propsMatches[ i ];
  40788. let resolvedType = type;
  40789. if ( resolvedType.startsWith( 'ptr' ) ) {
  40790. resolvedType = 'pointer';
  40791. } else {
  40792. if ( resolvedType.startsWith( 'texture' ) ) {
  40793. resolvedType = type.split( '<' )[ 0 ];
  40794. }
  40795. resolvedType = wgslTypeLib$1[ resolvedType ];
  40796. }
  40797. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  40798. }
  40799. const blockCode = source.substring( declaration[ 0 ].length );
  40800. const outputType = declaration[ 3 ] || 'void';
  40801. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  40802. const type = wgslTypeLib$1[ outputType ] || outputType;
  40803. return {
  40804. type,
  40805. inputs,
  40806. name,
  40807. inputsCode,
  40808. blockCode,
  40809. outputType
  40810. };
  40811. } else {
  40812. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  40813. }
  40814. };
  40815. /**
  40816. * This class represents a WSL node function.
  40817. *
  40818. * @augments NodeFunction
  40819. */
  40820. class WGSLNodeFunction extends NodeFunction {
  40821. /**
  40822. * Constructs a new WGSL node function.
  40823. *
  40824. * @param {String} source - The WGSL source.
  40825. */
  40826. constructor( source ) {
  40827. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  40828. super( type, inputs, name );
  40829. this.inputsCode = inputsCode;
  40830. this.blockCode = blockCode;
  40831. this.outputType = outputType;
  40832. }
  40833. /**
  40834. * This method returns the WGSL code of the node function.
  40835. *
  40836. * @param {String} [name=this.name] - The function's name.
  40837. * @return {String} The shader code.
  40838. */
  40839. getCode( name = this.name ) {
  40840. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  40841. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  40842. }
  40843. }
  40844. /**
  40845. * A WGSL node parser.
  40846. *
  40847. * @augments NodeParser
  40848. */
  40849. class WGSLNodeParser extends NodeParser {
  40850. /**
  40851. * The method parses the given WGSL code an returns a node function.
  40852. *
  40853. * @param {String} source - The WGSL code.
  40854. * @return {WGSLNodeFunction} A node function.
  40855. */
  40856. parseFunction( source ) {
  40857. return new WGSLNodeFunction( source );
  40858. }
  40859. }
  40860. // GPUShaderStage is not defined in browsers not supporting WebGPU
  40861. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  40862. const accessNames = {
  40863. [ NodeAccess.READ_ONLY ]: 'read',
  40864. [ NodeAccess.WRITE_ONLY ]: 'write',
  40865. [ NodeAccess.READ_WRITE ]: 'read_write'
  40866. };
  40867. const wrapNames = {
  40868. [ RepeatWrapping ]: 'repeat',
  40869. [ ClampToEdgeWrapping ]: 'clamp',
  40870. [ MirroredRepeatWrapping ]: 'mirror'
  40871. };
  40872. const gpuShaderStageLib = {
  40873. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  40874. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  40875. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  40876. };
  40877. const supports = {
  40878. instance: true,
  40879. swizzleAssign: false,
  40880. storageBuffer: true
  40881. };
  40882. const wgslFnOpLib = {
  40883. '^^': 'tsl_xor'
  40884. };
  40885. const wgslTypeLib = {
  40886. float: 'f32',
  40887. int: 'i32',
  40888. uint: 'u32',
  40889. bool: 'bool',
  40890. color: 'vec3<f32>',
  40891. vec2: 'vec2<f32>',
  40892. ivec2: 'vec2<i32>',
  40893. uvec2: 'vec2<u32>',
  40894. bvec2: 'vec2<bool>',
  40895. vec3: 'vec3<f32>',
  40896. ivec3: 'vec3<i32>',
  40897. uvec3: 'vec3<u32>',
  40898. bvec3: 'vec3<bool>',
  40899. vec4: 'vec4<f32>',
  40900. ivec4: 'vec4<i32>',
  40901. uvec4: 'vec4<u32>',
  40902. bvec4: 'vec4<bool>',
  40903. mat2: 'mat2x2<f32>',
  40904. mat3: 'mat3x3<f32>',
  40905. mat4: 'mat4x4<f32>'
  40906. };
  40907. const wgslCodeCache = {};
  40908. const wgslPolyfill = {
  40909. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  40910. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  40911. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  40912. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  40913. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  40914. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  40915. 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 ); }' ),
  40916. 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 ); }' ),
  40917. 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 ); }' ),
  40918. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  40919. 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 ); }' ),
  40920. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  40921. biquadraticTexture: new CodeNode( /* wgsl */`
  40922. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  40923. let res = vec2f( iRes );
  40924. let uvScaled = coord * res;
  40925. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  40926. // https://www.shadertoy.com/view/WtyXRy
  40927. let uv = uvWrapping - 0.5;
  40928. let iuv = floor( uv );
  40929. let f = fract( uv );
  40930. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  40931. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  40932. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  40933. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  40934. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  40935. }
  40936. ` )
  40937. };
  40938. const wgslMethods = {
  40939. dFdx: 'dpdx',
  40940. dFdy: '- dpdy',
  40941. mod_float: 'tsl_mod_float',
  40942. mod_vec2: 'tsl_mod_vec2',
  40943. mod_vec3: 'tsl_mod_vec3',
  40944. mod_vec4: 'tsl_mod_vec4',
  40945. equals_bool: 'tsl_equals_bool',
  40946. equals_bvec2: 'tsl_equals_bvec2',
  40947. equals_bvec3: 'tsl_equals_bvec3',
  40948. equals_bvec4: 'tsl_equals_bvec4',
  40949. inversesqrt: 'inverseSqrt',
  40950. bitcast: 'bitcast<f32>'
  40951. };
  40952. // WebGPU issue: does not support pow() with negative base on Windows
  40953. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  40954. 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 ); }' );
  40955. 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 ] );
  40956. 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 ] );
  40957. 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 ] );
  40958. wgslMethods.pow_float = 'tsl_pow_float';
  40959. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  40960. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  40961. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  40962. }
  40963. //
  40964. let diagnostics = '';
  40965. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  40966. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  40967. }
  40968. //
  40969. class WGSLNodeBuilder extends NodeBuilder {
  40970. constructor( object, renderer ) {
  40971. super( object, renderer, new WGSLNodeParser() );
  40972. this.uniformGroups = {};
  40973. this.builtins = {};
  40974. this.directives = {};
  40975. this.scopedArrays = new Map();
  40976. }
  40977. needsToWorkingColorSpace( texture ) {
  40978. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  40979. }
  40980. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  40981. if ( shaderStage === 'fragment' ) {
  40982. if ( depthSnippet ) {
  40983. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  40984. } else {
  40985. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  40986. }
  40987. } else if ( this.isFilteredTexture( texture ) ) {
  40988. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  40989. } else {
  40990. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0' );
  40991. }
  40992. }
  40993. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  40994. if ( shaderStage === 'fragment' ) {
  40995. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  40996. } else {
  40997. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  40998. }
  40999. }
  41000. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  41001. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false ) {
  41002. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  41003. } else if ( this.isFilteredTexture( texture ) ) {
  41004. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  41005. } else {
  41006. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  41007. }
  41008. }
  41009. generateWrapFunction( texture ) {
  41010. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${texture.isData3DTexture ? '3d' : '2d'}T`;
  41011. let nodeCode = wgslCodeCache[ functionName ];
  41012. if ( nodeCode === undefined ) {
  41013. const includes = [];
  41014. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  41015. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  41016. let code = `fn ${functionName}( coord : ${coordType} ) -> ${coordType} {\n\n\treturn ${coordType}(\n`;
  41017. const addWrapSnippet = ( wrap, axis ) => {
  41018. if ( wrap === RepeatWrapping ) {
  41019. includes.push( wgslPolyfill.repeatWrapping_float );
  41020. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  41021. } else if ( wrap === ClampToEdgeWrapping ) {
  41022. includes.push( wgslPolyfill.clampWrapping_float );
  41023. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  41024. } else if ( wrap === MirroredRepeatWrapping ) {
  41025. includes.push( wgslPolyfill.mirrorWrapping_float );
  41026. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  41027. } else {
  41028. code += `\t\tcoord.${ axis }`;
  41029. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  41030. }
  41031. };
  41032. addWrapSnippet( texture.wrapS, 'x' );
  41033. code += ',\n';
  41034. addWrapSnippet( texture.wrapT, 'y' );
  41035. if ( texture.isData3DTexture ) {
  41036. code += ',\n';
  41037. addWrapSnippet( texture.wrapR, 'z' );
  41038. }
  41039. code += '\n\t);\n\n}\n';
  41040. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  41041. }
  41042. nodeCode.build( this );
  41043. return functionName;
  41044. }
  41045. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  41046. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  41047. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  41048. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  41049. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  41050. let textureDimensionsParams;
  41051. let dimensionType;
  41052. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  41053. const isMultisampled = primarySamples > 1;
  41054. if ( texture.isData3DTexture ) {
  41055. dimensionType = 'vec3<u32>';
  41056. } else {
  41057. // Regular 2D textures, depth textures, etc.
  41058. dimensionType = 'vec2<u32>';
  41059. }
  41060. // Build parameters string based on texture type and multisampling
  41061. if ( isMultisampled || texture.isVideoTexture || texture.isStorageTexture ) {
  41062. textureDimensionsParams = textureProperty;
  41063. } else {
  41064. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  41065. }
  41066. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  41067. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  41068. if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  41069. textureData.arrayLayerCount = new VarNode(
  41070. new ExpressionNode(
  41071. `textureNumLayers(${textureProperty})`,
  41072. 'u32'
  41073. )
  41074. );
  41075. }
  41076. // For cube textures, we know it's always 6 faces
  41077. if ( texture.isTextureCube ) {
  41078. textureData.cubeFaceCount = new VarNode(
  41079. new ExpressionNode( '6u', 'u32' )
  41080. );
  41081. }
  41082. }
  41083. return textureDimensionNode.build( this );
  41084. }
  41085. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  41086. this._include( 'biquadraticTexture' );
  41087. const wrapFunction = this.generateWrapFunction( texture );
  41088. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  41089. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  41090. }
  41091. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  41092. const wrapFunction = this.generateWrapFunction( texture );
  41093. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  41094. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  41095. const coordSnippet = `${vecType}<u32>(${wrapFunction}(${uvSnippet}) * ${vecType}<f32>(${textureDimension}))`;
  41096. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  41097. }
  41098. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  41099. if ( texture.isVideoTexture === true || texture.isStorageTexture === true ) {
  41100. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  41101. } else if ( depthSnippet ) {
  41102. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  41103. } else {
  41104. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  41105. }
  41106. }
  41107. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  41108. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  41109. }
  41110. isSampleCompare( texture ) {
  41111. return texture.isDepthTexture === true && texture.compareFunction !== null;
  41112. }
  41113. isUnfilterable( texture ) {
  41114. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  41115. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  41116. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  41117. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  41118. }
  41119. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  41120. let snippet = null;
  41121. if ( texture.isVideoTexture === true ) {
  41122. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  41123. } else if ( this.isUnfilterable( texture ) ) {
  41124. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  41125. } else {
  41126. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  41127. }
  41128. return snippet;
  41129. }
  41130. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  41131. if ( shaderStage === 'fragment' ) {
  41132. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  41133. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  41134. } else {
  41135. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  41136. }
  41137. }
  41138. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  41139. if ( shaderStage === 'fragment' ) {
  41140. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  41141. } else {
  41142. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  41143. }
  41144. }
  41145. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  41146. let snippet = null;
  41147. if ( texture.isVideoTexture === true ) {
  41148. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  41149. } else {
  41150. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  41151. }
  41152. return snippet;
  41153. }
  41154. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  41155. if ( shaderStage === 'fragment' ) {
  41156. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  41157. } else {
  41158. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  41159. }
  41160. }
  41161. getPropertyName( node, shaderStage = this.shaderStage ) {
  41162. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  41163. if ( shaderStage === 'vertex' ) {
  41164. return `varyings.${ node.name }`;
  41165. }
  41166. } else if ( node.isNodeUniform === true ) {
  41167. const name = node.name;
  41168. const type = node.type;
  41169. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  41170. return name;
  41171. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  41172. return `NodeBuffer_${ node.id }.${name}`;
  41173. } else {
  41174. return node.groupNode.name + '.' + name;
  41175. }
  41176. }
  41177. return super.getPropertyName( node );
  41178. }
  41179. getOutputStructName() {
  41180. return 'output';
  41181. }
  41182. _getUniformGroupCount( shaderStage ) {
  41183. return Object.keys( this.uniforms[ shaderStage ] ).length;
  41184. }
  41185. getFunctionOperator( op ) {
  41186. const fnOp = wgslFnOpLib[ op ];
  41187. if ( fnOp !== undefined ) {
  41188. this._include( fnOp );
  41189. return fnOp;
  41190. }
  41191. return null;
  41192. }
  41193. getNodeAccess( node, shaderStage ) {
  41194. if ( shaderStage !== 'compute' )
  41195. return NodeAccess.READ_ONLY;
  41196. return node.access;
  41197. }
  41198. getStorageAccess( node, shaderStage ) {
  41199. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  41200. }
  41201. getUniformFromNode( node, type, shaderStage, name = null ) {
  41202. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  41203. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  41204. if ( nodeData.uniformGPU === undefined ) {
  41205. let uniformGPU;
  41206. const group = node.groupNode;
  41207. const groupName = group.name;
  41208. const bindings = this.getBindGroupArray( groupName, shaderStage );
  41209. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  41210. let texture = null;
  41211. const access = this.getNodeAccess( node, shaderStage );
  41212. if ( type === 'texture' || type === 'storageTexture' ) {
  41213. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  41214. } else if ( type === 'cubeTexture' ) {
  41215. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  41216. } else if ( type === 'texture3D' ) {
  41217. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  41218. }
  41219. texture.store = node.isStorageTextureNode === true;
  41220. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  41221. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  41222. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  41223. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  41224. bindings.push( sampler, texture );
  41225. uniformGPU = [ sampler, texture ];
  41226. } else {
  41227. bindings.push( texture );
  41228. uniformGPU = [ texture ];
  41229. }
  41230. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  41231. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  41232. const buffer = new bufferClass( node, group );
  41233. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  41234. bindings.push( buffer );
  41235. uniformGPU = buffer;
  41236. } else {
  41237. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  41238. let uniformsGroup = uniformsStage[ groupName ];
  41239. if ( uniformsGroup === undefined ) {
  41240. uniformsGroup = new NodeUniformsGroup( groupName, group );
  41241. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  41242. uniformsStage[ groupName ] = uniformsGroup;
  41243. bindings.push( uniformsGroup );
  41244. }
  41245. uniformGPU = this.getNodeUniform( uniformNode, type );
  41246. uniformsGroup.addUniform( uniformGPU );
  41247. }
  41248. nodeData.uniformGPU = uniformGPU;
  41249. }
  41250. return uniformNode;
  41251. }
  41252. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  41253. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  41254. if ( map.has( name ) === false ) {
  41255. map.set( name, {
  41256. name,
  41257. property,
  41258. type
  41259. } );
  41260. }
  41261. return property;
  41262. }
  41263. hasBuiltin( name, shaderStage = this.shaderStage ) {
  41264. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  41265. }
  41266. getVertexIndex() {
  41267. if ( this.shaderStage === 'vertex' ) {
  41268. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  41269. }
  41270. return 'vertexIndex';
  41271. }
  41272. buildFunctionCode( shaderNode ) {
  41273. const layout = shaderNode.layout;
  41274. const flowData = this.flowShaderNode( shaderNode );
  41275. const parameters = [];
  41276. for ( const input of layout.inputs ) {
  41277. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  41278. }
  41279. //
  41280. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  41281. ${ flowData.vars }
  41282. ${ flowData.code }
  41283. `;
  41284. if ( flowData.result ) {
  41285. code += `\treturn ${ flowData.result };\n`;
  41286. }
  41287. code += '\n}\n';
  41288. //
  41289. return code;
  41290. }
  41291. getInstanceIndex() {
  41292. if ( this.shaderStage === 'vertex' ) {
  41293. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  41294. }
  41295. return 'instanceIndex';
  41296. }
  41297. getInvocationLocalIndex() {
  41298. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  41299. }
  41300. getSubgroupSize() {
  41301. this.enableSubGroups();
  41302. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  41303. }
  41304. getInvocationSubgroupIndex() {
  41305. this.enableSubGroups();
  41306. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  41307. }
  41308. getSubgroupIndex() {
  41309. this.enableSubGroups();
  41310. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  41311. }
  41312. getDrawIndex() {
  41313. return null;
  41314. }
  41315. getFrontFacing() {
  41316. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  41317. }
  41318. getFragCoord() {
  41319. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  41320. }
  41321. getFragDepth() {
  41322. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  41323. }
  41324. getClipDistance() {
  41325. return 'varyings.hw_clip_distances';
  41326. }
  41327. isFlipY() {
  41328. return false;
  41329. }
  41330. enableDirective( name, shaderStage = this.shaderStage ) {
  41331. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  41332. stage.add( name );
  41333. }
  41334. getDirectives( shaderStage ) {
  41335. const snippets = [];
  41336. const directives = this.directives[ shaderStage ];
  41337. if ( directives !== undefined ) {
  41338. for ( const directive of directives ) {
  41339. snippets.push( `enable ${directive};` );
  41340. }
  41341. }
  41342. return snippets.join( '\n' );
  41343. }
  41344. enableSubGroups() {
  41345. this.enableDirective( 'subgroups' );
  41346. }
  41347. enableSubgroupsF16() {
  41348. this.enableDirective( 'subgroups-f16' );
  41349. }
  41350. enableClipDistances() {
  41351. this.enableDirective( 'clip_distances' );
  41352. }
  41353. enableShaderF16() {
  41354. this.enableDirective( 'f16' );
  41355. }
  41356. enableDualSourceBlending() {
  41357. this.enableDirective( 'dual_source_blending' );
  41358. }
  41359. enableHardwareClipping( planeCount ) {
  41360. this.enableClipDistances();
  41361. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  41362. }
  41363. getBuiltins( shaderStage ) {
  41364. const snippets = [];
  41365. const builtins = this.builtins[ shaderStage ];
  41366. if ( builtins !== undefined ) {
  41367. for ( const { name, property, type } of builtins.values() ) {
  41368. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  41369. }
  41370. }
  41371. return snippets.join( ',\n\t' );
  41372. }
  41373. getScopedArray( name, scope, bufferType, bufferCount ) {
  41374. if ( this.scopedArrays.has( name ) === false ) {
  41375. this.scopedArrays.set( name, {
  41376. name,
  41377. scope,
  41378. bufferType,
  41379. bufferCount
  41380. } );
  41381. }
  41382. return name;
  41383. }
  41384. getScopedArrays( shaderStage ) {
  41385. if ( shaderStage !== 'compute' ) {
  41386. return;
  41387. }
  41388. const snippets = [];
  41389. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  41390. const type = this.getType( bufferType );
  41391. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  41392. }
  41393. return snippets.join( '\n' );
  41394. }
  41395. getAttributes( shaderStage ) {
  41396. const snippets = [];
  41397. if ( shaderStage === 'compute' ) {
  41398. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  41399. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  41400. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  41401. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  41402. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  41403. this.enableDirective( 'subgroups', shaderStage );
  41404. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  41405. }
  41406. }
  41407. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  41408. const builtins = this.getBuiltins( 'attribute' );
  41409. if ( builtins ) snippets.push( builtins );
  41410. const attributes = this.getAttributesArray();
  41411. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  41412. const attribute = attributes[ index ];
  41413. const name = attribute.name;
  41414. const type = this.getType( attribute.type );
  41415. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  41416. }
  41417. }
  41418. return snippets.join( ',\n\t' );
  41419. }
  41420. getStructMembers( struct ) {
  41421. const snippets = [];
  41422. const members = struct.getMemberTypes();
  41423. for ( let i = 0; i < members.length; i ++ ) {
  41424. const member = members[ i ];
  41425. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  41426. }
  41427. const builtins = this.getBuiltins( 'output' );
  41428. if ( builtins ) snippets.push( '\t' + builtins );
  41429. return snippets.join( ',\n' );
  41430. }
  41431. getStructs( shaderStage ) {
  41432. const snippets = [];
  41433. const structs = this.structs[ shaderStage ];
  41434. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  41435. const struct = structs[ index ];
  41436. const name = struct.name;
  41437. let snippet = `\struct ${ name } {\n`;
  41438. snippet += this.getStructMembers( struct );
  41439. snippet += '\n}';
  41440. snippets.push( snippet );
  41441. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  41442. }
  41443. return snippets.join( '\n\n' );
  41444. }
  41445. getVar( type, name ) {
  41446. return `var ${ name } : ${ this.getType( type ) }`;
  41447. }
  41448. getVars( shaderStage ) {
  41449. const snippets = [];
  41450. const vars = this.vars[ shaderStage ];
  41451. if ( vars !== undefined ) {
  41452. for ( const variable of vars ) {
  41453. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  41454. }
  41455. }
  41456. return `\n${ snippets.join( '\n' ) }\n`;
  41457. }
  41458. getVaryings( shaderStage ) {
  41459. const snippets = [];
  41460. if ( shaderStage === 'vertex' ) {
  41461. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  41462. }
  41463. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  41464. const varyings = this.varyings;
  41465. const vars = this.vars[ shaderStage ];
  41466. for ( let index = 0; index < varyings.length; index ++ ) {
  41467. const varying = varyings[ index ];
  41468. if ( varying.needsInterpolation ) {
  41469. let attributesSnippet = `@location( ${index} )`;
  41470. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  41471. attributesSnippet += ' @interpolate( flat )';
  41472. }
  41473. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  41474. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  41475. vars.push( varying );
  41476. }
  41477. }
  41478. }
  41479. const builtins = this.getBuiltins( shaderStage );
  41480. if ( builtins ) snippets.push( builtins );
  41481. const code = snippets.join( ',\n\t' );
  41482. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  41483. }
  41484. getUniforms( shaderStage ) {
  41485. const uniforms = this.uniforms[ shaderStage ];
  41486. const bindingSnippets = [];
  41487. const bufferSnippets = [];
  41488. const structSnippets = [];
  41489. const uniformGroups = {};
  41490. for ( const uniform of uniforms ) {
  41491. const groupName = uniform.groupNode.name;
  41492. const uniformIndexes = this.bindingsIndexes[ groupName ];
  41493. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  41494. const texture = uniform.node.value;
  41495. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  41496. if ( this.isSampleCompare( texture ) ) {
  41497. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  41498. } else {
  41499. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  41500. }
  41501. }
  41502. let textureType;
  41503. let multisampled = '';
  41504. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  41505. if ( primarySamples > 1 ) {
  41506. multisampled = '_multisampled';
  41507. }
  41508. if ( texture.isCubeTexture === true ) {
  41509. textureType = 'texture_cube<f32>';
  41510. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  41511. textureType = 'texture_2d_array<f32>';
  41512. } else if ( texture.isDepthTexture === true ) {
  41513. textureType = `texture_depth${multisampled}_2d`;
  41514. } else if ( texture.isVideoTexture === true ) {
  41515. textureType = 'texture_external';
  41516. } else if ( texture.isData3DTexture === true ) {
  41517. textureType = 'texture_3d<f32>';
  41518. } else if ( uniform.node.isStorageTextureNode === true ) {
  41519. const format = getFormat( texture );
  41520. const access = this.getStorageAccess( uniform.node, shaderStage );
  41521. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  41522. } else {
  41523. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  41524. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  41525. }
  41526. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  41527. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  41528. const bufferNode = uniform.node;
  41529. const bufferType = this.getType( bufferNode.bufferType );
  41530. const bufferCount = bufferNode.bufferCount;
  41531. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  41532. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${bufferType}>` : `${bufferType}`;
  41533. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >\n`;
  41534. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  41535. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  41536. } else {
  41537. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  41538. const groupName = uniform.groupNode.name;
  41539. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  41540. index: uniformIndexes.binding ++,
  41541. id: uniformIndexes.group,
  41542. snippets: []
  41543. } );
  41544. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  41545. }
  41546. }
  41547. for ( const name in uniformGroups ) {
  41548. const group = uniformGroups[ name ];
  41549. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  41550. }
  41551. let code = bindingSnippets.join( '\n' );
  41552. code += bufferSnippets.join( '\n' );
  41553. code += structSnippets.join( '\n' );
  41554. return code;
  41555. }
  41556. buildCode() {
  41557. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  41558. this.sortBindingGroups();
  41559. for ( const shaderStage in shadersData ) {
  41560. const stageData = shadersData[ shaderStage ];
  41561. stageData.uniforms = this.getUniforms( shaderStage );
  41562. stageData.attributes = this.getAttributes( shaderStage );
  41563. stageData.varyings = this.getVaryings( shaderStage );
  41564. stageData.structs = this.getStructs( shaderStage );
  41565. stageData.vars = this.getVars( shaderStage );
  41566. stageData.codes = this.getCodes( shaderStage );
  41567. stageData.directives = this.getDirectives( shaderStage );
  41568. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  41569. //
  41570. let flow = '// code\n\n';
  41571. flow += this.flowCode[ shaderStage ];
  41572. const flowNodes = this.flowNodes[ shaderStage ];
  41573. const mainNode = flowNodes[ flowNodes.length - 1 ];
  41574. const outputNode = mainNode.outputNode;
  41575. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  41576. for ( const node of flowNodes ) {
  41577. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  41578. const slotName = node.name;
  41579. if ( slotName ) {
  41580. if ( flow.length > 0 ) flow += '\n';
  41581. flow += `\t// flow -> ${ slotName }\n\t`;
  41582. }
  41583. flow += `${ flowSlotData.code }\n\t`;
  41584. if ( node === mainNode && shaderStage !== 'compute' ) {
  41585. flow += '// result\n\n\t';
  41586. if ( shaderStage === 'vertex' ) {
  41587. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  41588. } else if ( shaderStage === 'fragment' ) {
  41589. if ( isOutputStruct ) {
  41590. stageData.returnType = outputNode.nodeType;
  41591. flow += `return ${ flowSlotData.result };`;
  41592. } else {
  41593. let structSnippet = '\t@location(0) color: vec4<f32>';
  41594. const builtins = this.getBuiltins( 'output' );
  41595. if ( builtins ) structSnippet += ',\n\t' + builtins;
  41596. stageData.returnType = 'OutputStruct';
  41597. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  41598. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  41599. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  41600. }
  41601. }
  41602. }
  41603. }
  41604. stageData.flow = flow;
  41605. }
  41606. if ( this.material !== null ) {
  41607. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  41608. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  41609. } else {
  41610. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  41611. }
  41612. }
  41613. getMethod( method, output = null ) {
  41614. let wgslMethod;
  41615. if ( output !== null ) {
  41616. wgslMethod = this._getWGSLMethod( method + '_' + output );
  41617. }
  41618. if ( wgslMethod === undefined ) {
  41619. wgslMethod = this._getWGSLMethod( method );
  41620. }
  41621. return wgslMethod || method;
  41622. }
  41623. getType( type ) {
  41624. return wgslTypeLib[ type ] || type;
  41625. }
  41626. isAvailable( name ) {
  41627. let result = supports[ name ];
  41628. if ( result === undefined ) {
  41629. if ( name === 'float32Filterable' ) {
  41630. result = this.renderer.hasFeature( 'float32-filterable' );
  41631. } else if ( name === 'clipDistance' ) {
  41632. result = this.renderer.hasFeature( 'clip-distances' );
  41633. }
  41634. supports[ name ] = result;
  41635. }
  41636. return result;
  41637. }
  41638. _getWGSLMethod( method ) {
  41639. if ( wgslPolyfill[ method ] !== undefined ) {
  41640. this._include( method );
  41641. }
  41642. return wgslMethods[ method ];
  41643. }
  41644. _include( name ) {
  41645. const codeNode = wgslPolyfill[ name ];
  41646. codeNode.build( this );
  41647. if ( this.currentFunctionNode !== null ) {
  41648. this.currentFunctionNode.includes.push( codeNode );
  41649. }
  41650. return codeNode;
  41651. }
  41652. _getWGSLVertexCode( shaderData ) {
  41653. return `${ this.getSignature() }
  41654. // directives
  41655. ${shaderData.directives}
  41656. // uniforms
  41657. ${shaderData.uniforms}
  41658. // varyings
  41659. ${shaderData.varyings}
  41660. var<private> varyings : VaryingsStruct;
  41661. // codes
  41662. ${shaderData.codes}
  41663. @vertex
  41664. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  41665. // vars
  41666. ${shaderData.vars}
  41667. // flow
  41668. ${shaderData.flow}
  41669. return varyings;
  41670. }
  41671. `;
  41672. }
  41673. _getWGSLFragmentCode( shaderData ) {
  41674. return `${ this.getSignature() }
  41675. // global
  41676. ${ diagnostics }
  41677. // uniforms
  41678. ${shaderData.uniforms}
  41679. // structs
  41680. ${shaderData.structs}
  41681. // codes
  41682. ${shaderData.codes}
  41683. @fragment
  41684. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  41685. // vars
  41686. ${shaderData.vars}
  41687. // flow
  41688. ${shaderData.flow}
  41689. }
  41690. `;
  41691. }
  41692. _getWGSLComputeCode( shaderData, workgroupSize ) {
  41693. return `${ this.getSignature() }
  41694. // directives
  41695. ${shaderData.directives}
  41696. // system
  41697. var<private> instanceIndex : u32;
  41698. // locals
  41699. ${shaderData.scopedArrays}
  41700. // uniforms
  41701. ${shaderData.uniforms}
  41702. // codes
  41703. ${shaderData.codes}
  41704. @compute @workgroup_size( ${workgroupSize} )
  41705. fn main( ${shaderData.attributes} ) {
  41706. // system
  41707. instanceIndex = id.x + id.y * numWorkgroups.x * u32(${workgroupSize}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  41708. // vars
  41709. ${shaderData.vars}
  41710. // flow
  41711. ${shaderData.flow}
  41712. }
  41713. `;
  41714. }
  41715. _getWGSLStruct( name, vars ) {
  41716. return `
  41717. struct ${name} {
  41718. ${vars}
  41719. };`;
  41720. }
  41721. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  41722. const structName = name + 'Struct';
  41723. const structSnippet = this._getWGSLStruct( structName, vars );
  41724. return `${structSnippet}
  41725. @binding( ${binding} ) @group( ${group} )
  41726. var<${access}> ${name} : ${structName};`;
  41727. }
  41728. }
  41729. class WebGPUUtils {
  41730. constructor( backend ) {
  41731. this.backend = backend;
  41732. }
  41733. getCurrentDepthStencilFormat( renderContext ) {
  41734. let format;
  41735. if ( renderContext.depthTexture !== null ) {
  41736. format = this.getTextureFormatGPU( renderContext.depthTexture );
  41737. } else if ( renderContext.depth && renderContext.stencil ) {
  41738. format = GPUTextureFormat.Depth24PlusStencil8;
  41739. } else if ( renderContext.depth ) {
  41740. format = GPUTextureFormat.Depth24Plus;
  41741. }
  41742. return format;
  41743. }
  41744. getTextureFormatGPU( texture ) {
  41745. return this.backend.get( texture ).format;
  41746. }
  41747. getTextureSampleData( texture ) {
  41748. let samples;
  41749. if ( texture.isFramebufferTexture ) {
  41750. samples = 1;
  41751. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  41752. const renderer = this.backend.renderer;
  41753. const renderTarget = renderer.getRenderTarget();
  41754. samples = renderTarget ? renderTarget.samples : renderer.samples;
  41755. } else if ( texture.renderTarget ) {
  41756. samples = texture.renderTarget.samples;
  41757. }
  41758. samples = samples || 1;
  41759. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  41760. const primarySamples = isMSAA ? 1 : samples;
  41761. return { samples, primarySamples, isMSAA };
  41762. }
  41763. getCurrentColorFormat( renderContext ) {
  41764. let format;
  41765. if ( renderContext.textures !== null ) {
  41766. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  41767. } else {
  41768. format = this.getPreferredCanvasFormat(); // default context format
  41769. }
  41770. return format;
  41771. }
  41772. getCurrentColorSpace( renderContext ) {
  41773. if ( renderContext.textures !== null ) {
  41774. return renderContext.textures[ 0 ].colorSpace;
  41775. }
  41776. return this.backend.renderer.outputColorSpace;
  41777. }
  41778. getPrimitiveTopology( object, material ) {
  41779. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  41780. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  41781. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  41782. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  41783. }
  41784. getSampleCount( sampleCount ) {
  41785. let count = 1;
  41786. if ( sampleCount > 1 ) {
  41787. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  41788. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  41789. if ( count === 2 ) {
  41790. count = 4;
  41791. }
  41792. }
  41793. return count;
  41794. }
  41795. getSampleCountRenderContext( renderContext ) {
  41796. if ( renderContext.textures !== null ) {
  41797. return this.getSampleCount( renderContext.sampleCount );
  41798. }
  41799. return this.getSampleCount( this.backend.renderer.samples );
  41800. }
  41801. getPreferredCanvasFormat() {
  41802. // TODO: Remove this check when Quest 34.5 is out
  41803. // https://github.com/mrdoob/three.js/pull/29221/files#r1731833949
  41804. if ( navigator.userAgent.includes( 'Quest' ) ) {
  41805. return GPUTextureFormat.BGRA8Unorm;
  41806. } else {
  41807. return navigator.gpu.getPreferredCanvasFormat();
  41808. }
  41809. }
  41810. }
  41811. const typedArraysToVertexFormatPrefix = new Map( [
  41812. [ Int8Array, [ 'sint8', 'snorm8' ]],
  41813. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  41814. [ Int16Array, [ 'sint16', 'snorm16' ]],
  41815. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  41816. [ Int32Array, [ 'sint32', 'snorm32' ]],
  41817. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  41818. [ Float32Array, [ 'float32', ]],
  41819. ] );
  41820. const typedAttributeToVertexFormatPrefix = new Map( [
  41821. [ Float16BufferAttribute, [ 'float16', ]],
  41822. ] );
  41823. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  41824. [ Int32Array, 'sint32' ],
  41825. [ Int16Array, 'sint32' ], // patch for INT16
  41826. [ Uint32Array, 'uint32' ],
  41827. [ Uint16Array, 'uint32' ], // patch for UINT16
  41828. [ Float32Array, 'float32' ]
  41829. ] );
  41830. class WebGPUAttributeUtils {
  41831. constructor( backend ) {
  41832. this.backend = backend;
  41833. }
  41834. createAttribute( attribute, usage ) {
  41835. const bufferAttribute = this._getBufferAttribute( attribute );
  41836. const backend = this.backend;
  41837. const bufferData = backend.get( bufferAttribute );
  41838. let buffer = bufferData.buffer;
  41839. if ( buffer === undefined ) {
  41840. const device = backend.device;
  41841. let array = bufferAttribute.array;
  41842. // patch for INT16 and UINT16
  41843. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  41844. const tempArray = new Uint32Array( array.length );
  41845. for ( let i = 0; i < array.length; i ++ ) {
  41846. tempArray[ i ] = array[ i ];
  41847. }
  41848. array = tempArray;
  41849. }
  41850. bufferAttribute.array = array;
  41851. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  41852. array = new array.constructor( bufferAttribute.count * 4 );
  41853. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  41854. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  41855. }
  41856. // Update BufferAttribute
  41857. bufferAttribute.itemSize = 4;
  41858. bufferAttribute.array = array;
  41859. }
  41860. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  41861. buffer = device.createBuffer( {
  41862. label: bufferAttribute.name,
  41863. size: size,
  41864. usage: usage,
  41865. mappedAtCreation: true
  41866. } );
  41867. new array.constructor( buffer.getMappedRange() ).set( array );
  41868. buffer.unmap();
  41869. bufferData.buffer = buffer;
  41870. }
  41871. }
  41872. updateAttribute( attribute ) {
  41873. const bufferAttribute = this._getBufferAttribute( attribute );
  41874. const backend = this.backend;
  41875. const device = backend.device;
  41876. const buffer = backend.get( bufferAttribute ).buffer;
  41877. const array = bufferAttribute.array;
  41878. const isTypedArray = this._isTypedArray( array );
  41879. const updateRanges = bufferAttribute.updateRanges;
  41880. if ( updateRanges.length === 0 ) {
  41881. // Not using update ranges
  41882. device.queue.writeBuffer(
  41883. buffer,
  41884. 0,
  41885. array,
  41886. 0
  41887. );
  41888. } else {
  41889. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  41890. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  41891. const range = updateRanges[ i ];
  41892. const dataOffset = range.start * byteOffsetFactor;
  41893. const size = range.count * byteOffsetFactor;
  41894. device.queue.writeBuffer(
  41895. buffer,
  41896. 0,
  41897. array,
  41898. dataOffset,
  41899. size
  41900. );
  41901. }
  41902. bufferAttribute.clearUpdateRanges();
  41903. }
  41904. }
  41905. createShaderVertexBuffers( renderObject ) {
  41906. const attributes = renderObject.getAttributes();
  41907. const vertexBuffers = new Map();
  41908. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  41909. const geometryAttribute = attributes[ slot ];
  41910. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  41911. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  41912. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  41913. if ( vertexBufferLayout === undefined ) {
  41914. let arrayStride, stepMode;
  41915. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  41916. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  41917. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  41918. } else {
  41919. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  41920. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  41921. }
  41922. // patch for INT16 and UINT16
  41923. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  41924. arrayStride = 4;
  41925. }
  41926. vertexBufferLayout = {
  41927. arrayStride,
  41928. attributes: [],
  41929. stepMode
  41930. };
  41931. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  41932. }
  41933. const format = this._getVertexFormat( geometryAttribute );
  41934. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  41935. vertexBufferLayout.attributes.push( {
  41936. shaderLocation: slot,
  41937. offset,
  41938. format
  41939. } );
  41940. }
  41941. return Array.from( vertexBuffers.values() );
  41942. }
  41943. destroyAttribute( attribute ) {
  41944. const backend = this.backend;
  41945. const data = backend.get( this._getBufferAttribute( attribute ) );
  41946. data.buffer.destroy();
  41947. backend.delete( attribute );
  41948. }
  41949. async getArrayBufferAsync( attribute ) {
  41950. const backend = this.backend;
  41951. const device = backend.device;
  41952. const data = backend.get( this._getBufferAttribute( attribute ) );
  41953. const bufferGPU = data.buffer;
  41954. const size = bufferGPU.size;
  41955. const readBufferGPU = device.createBuffer( {
  41956. label: `${ attribute.name }_readback`,
  41957. size,
  41958. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  41959. } );
  41960. const cmdEncoder = device.createCommandEncoder( {
  41961. label: `readback_encoder_${ attribute.name }`
  41962. } );
  41963. cmdEncoder.copyBufferToBuffer(
  41964. bufferGPU,
  41965. 0,
  41966. readBufferGPU,
  41967. 0,
  41968. size
  41969. );
  41970. const gpuCommands = cmdEncoder.finish();
  41971. device.queue.submit( [ gpuCommands ] );
  41972. await readBufferGPU.mapAsync( GPUMapMode.READ );
  41973. const arrayBuffer = readBufferGPU.getMappedRange();
  41974. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  41975. readBufferGPU.unmap();
  41976. return dstBuffer.buffer;
  41977. }
  41978. _getVertexFormat( geometryAttribute ) {
  41979. const { itemSize, normalized } = geometryAttribute;
  41980. const ArrayType = geometryAttribute.array.constructor;
  41981. const AttributeType = geometryAttribute.constructor;
  41982. let format;
  41983. if ( itemSize === 1 ) {
  41984. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  41985. } else {
  41986. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  41987. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  41988. if ( prefix ) {
  41989. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  41990. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  41991. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  41992. if ( paddedItemSize % 1 ) {
  41993. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  41994. }
  41995. format = `${prefix}x${paddedItemSize}`;
  41996. }
  41997. }
  41998. if ( ! format ) {
  41999. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  42000. }
  42001. return format;
  42002. }
  42003. _isTypedArray( array ) {
  42004. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  42005. }
  42006. _getBufferAttribute( attribute ) {
  42007. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  42008. return attribute;
  42009. }
  42010. }
  42011. class WebGPUBindingUtils {
  42012. constructor( backend ) {
  42013. this.backend = backend;
  42014. this.bindGroupLayoutCache = new WeakMap();
  42015. }
  42016. createBindingsLayout( bindGroup ) {
  42017. const backend = this.backend;
  42018. const device = backend.device;
  42019. const entries = [];
  42020. let index = 0;
  42021. for ( const binding of bindGroup.bindings ) {
  42022. const bindingGPU = {
  42023. binding: index ++,
  42024. visibility: binding.visibility
  42025. };
  42026. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  42027. const buffer = {}; // GPUBufferBindingLayout
  42028. if ( binding.isStorageBuffer ) {
  42029. if ( binding.visibility & 4 ) {
  42030. // compute
  42031. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  42032. buffer.type = GPUBufferBindingType.Storage;
  42033. } else {
  42034. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  42035. }
  42036. } else {
  42037. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  42038. }
  42039. }
  42040. bindingGPU.buffer = buffer;
  42041. } else if ( binding.isSampler ) {
  42042. const sampler = {}; // GPUSamplerBindingLayout
  42043. if ( binding.texture.isDepthTexture ) {
  42044. if ( binding.texture.compareFunction !== null ) {
  42045. sampler.type = 'comparison';
  42046. }
  42047. }
  42048. bindingGPU.sampler = sampler;
  42049. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  42050. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  42051. } else if ( binding.isSampledTexture && binding.store ) {
  42052. const storageTexture = {}; // GPUStorageTextureBindingLayout
  42053. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  42054. const access = binding.access;
  42055. if ( access === NodeAccess.READ_WRITE ) {
  42056. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  42057. } else if ( access === NodeAccess.WRITE_ONLY ) {
  42058. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  42059. } else {
  42060. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  42061. }
  42062. bindingGPU.storageTexture = storageTexture;
  42063. } else if ( binding.isSampledTexture ) {
  42064. const texture = {}; // GPUTextureBindingLayout
  42065. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  42066. if ( primarySamples > 1 ) {
  42067. texture.multisampled = true;
  42068. if ( ! binding.texture.isDepthTexture ) {
  42069. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  42070. }
  42071. }
  42072. if ( binding.texture.isDepthTexture ) {
  42073. texture.sampleType = GPUTextureSampleType.Depth;
  42074. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  42075. const type = binding.texture.type;
  42076. if ( type === IntType ) {
  42077. texture.sampleType = GPUTextureSampleType.SInt;
  42078. } else if ( type === UnsignedIntType ) {
  42079. texture.sampleType = GPUTextureSampleType.UInt;
  42080. } else if ( type === FloatType ) {
  42081. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  42082. texture.sampleType = GPUTextureSampleType.Float;
  42083. } else {
  42084. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  42085. }
  42086. }
  42087. }
  42088. if ( binding.isSampledCubeTexture ) {
  42089. texture.viewDimension = GPUTextureViewDimension.Cube;
  42090. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  42091. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  42092. } else if ( binding.isSampledTexture3D ) {
  42093. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  42094. }
  42095. bindingGPU.texture = texture;
  42096. } else {
  42097. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  42098. }
  42099. entries.push( bindingGPU );
  42100. }
  42101. return device.createBindGroupLayout( { entries } );
  42102. }
  42103. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  42104. const { backend, bindGroupLayoutCache } = this;
  42105. const bindingsData = backend.get( bindGroup );
  42106. // setup (static) binding layout and (dynamic) binding group
  42107. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  42108. if ( bindLayoutGPU === undefined ) {
  42109. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  42110. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  42111. }
  42112. let bindGroupGPU;
  42113. if ( cacheIndex > 0 ) {
  42114. if ( bindingsData.groups === undefined ) {
  42115. bindingsData.groups = [];
  42116. bindingsData.versions = [];
  42117. }
  42118. if ( bindingsData.versions[ cacheIndex ] === version ) {
  42119. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  42120. }
  42121. }
  42122. if ( bindGroupGPU === undefined ) {
  42123. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  42124. if ( cacheIndex > 0 ) {
  42125. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  42126. bindingsData.versions[ cacheIndex ] = version;
  42127. }
  42128. }
  42129. bindingsData.group = bindGroupGPU;
  42130. bindingsData.layout = bindLayoutGPU;
  42131. }
  42132. updateBinding( binding ) {
  42133. const backend = this.backend;
  42134. const device = backend.device;
  42135. const buffer = binding.buffer;
  42136. const bufferGPU = backend.get( binding ).buffer;
  42137. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  42138. }
  42139. createBindGroup( bindGroup, layoutGPU ) {
  42140. const backend = this.backend;
  42141. const device = backend.device;
  42142. let bindingPoint = 0;
  42143. const entriesGPU = [];
  42144. for ( const binding of bindGroup.bindings ) {
  42145. if ( binding.isUniformBuffer ) {
  42146. const bindingData = backend.get( binding );
  42147. if ( bindingData.buffer === undefined ) {
  42148. const byteLength = binding.byteLength;
  42149. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  42150. const bufferGPU = device.createBuffer( {
  42151. label: 'bindingBuffer_' + binding.name,
  42152. size: byteLength,
  42153. usage: usage
  42154. } );
  42155. bindingData.buffer = bufferGPU;
  42156. }
  42157. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  42158. } else if ( binding.isStorageBuffer ) {
  42159. const bindingData = backend.get( binding );
  42160. if ( bindingData.buffer === undefined ) {
  42161. const attribute = binding.attribute;
  42162. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  42163. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  42164. bindingData.buffer = backend.get( attribute ).buffer;
  42165. }
  42166. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  42167. } else if ( binding.isSampler ) {
  42168. const textureGPU = backend.get( binding.texture );
  42169. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  42170. } else if ( binding.isSampledTexture ) {
  42171. const textureData = backend.get( binding.texture );
  42172. let resourceGPU;
  42173. if ( textureData.externalTexture !== undefined ) {
  42174. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  42175. } else {
  42176. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  42177. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  42178. resourceGPU = textureData[ propertyName ];
  42179. if ( resourceGPU === undefined ) {
  42180. const aspectGPU = GPUTextureAspect.All;
  42181. let dimensionViewGPU;
  42182. if ( binding.isSampledCubeTexture ) {
  42183. dimensionViewGPU = GPUTextureViewDimension.Cube;
  42184. } else if ( binding.isSampledTexture3D ) {
  42185. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  42186. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  42187. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  42188. } else {
  42189. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  42190. }
  42191. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  42192. }
  42193. }
  42194. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  42195. }
  42196. bindingPoint ++;
  42197. }
  42198. return device.createBindGroup( {
  42199. label: 'bindGroup_' + bindGroup.name,
  42200. layout: layoutGPU,
  42201. entries: entriesGPU
  42202. } );
  42203. }
  42204. }
  42205. class WebGPUPipelineUtils {
  42206. constructor( backend ) {
  42207. this.backend = backend;
  42208. }
  42209. _getSampleCount( renderObjectContext ) {
  42210. return this.backend.utils.getSampleCountRenderContext( renderObjectContext );
  42211. }
  42212. createRenderPipeline( renderObject, promises ) {
  42213. const { object, material, geometry, pipeline } = renderObject;
  42214. const { vertexProgram, fragmentProgram } = pipeline;
  42215. const backend = this.backend;
  42216. const device = backend.device;
  42217. const utils = backend.utils;
  42218. const pipelineData = backend.get( pipeline );
  42219. // bind group layouts
  42220. const bindGroupLayouts = [];
  42221. for ( const bindGroup of renderObject.getBindings() ) {
  42222. const bindingsData = backend.get( bindGroup );
  42223. bindGroupLayouts.push( bindingsData.layout );
  42224. }
  42225. // vertex buffers
  42226. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  42227. // blending
  42228. let blending;
  42229. if ( material.transparent === true && material.blending !== NoBlending ) {
  42230. blending = this._getBlending( material );
  42231. }
  42232. // stencil
  42233. let stencilFront = {};
  42234. if ( material.stencilWrite === true ) {
  42235. stencilFront = {
  42236. compare: this._getStencilCompare( material ),
  42237. failOp: this._getStencilOperation( material.stencilFail ),
  42238. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  42239. passOp: this._getStencilOperation( material.stencilZPass )
  42240. };
  42241. }
  42242. const colorWriteMask = this._getColorWriteMask( material );
  42243. const targets = [];
  42244. if ( renderObject.context.textures !== null ) {
  42245. const textures = renderObject.context.textures;
  42246. for ( let i = 0; i < textures.length; i ++ ) {
  42247. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  42248. targets.push( {
  42249. format: colorFormat,
  42250. blend: blending,
  42251. writeMask: colorWriteMask
  42252. } );
  42253. }
  42254. } else {
  42255. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  42256. targets.push( {
  42257. format: colorFormat,
  42258. blend: blending,
  42259. writeMask: colorWriteMask
  42260. } );
  42261. }
  42262. const vertexModule = backend.get( vertexProgram ).module;
  42263. const fragmentModule = backend.get( fragmentProgram ).module;
  42264. const primitiveState = this._getPrimitiveState( object, geometry, material );
  42265. const depthCompare = this._getDepthCompare( material );
  42266. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  42267. const sampleCount = this._getSampleCount( renderObject.context );
  42268. const pipelineDescriptor = {
  42269. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  42270. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  42271. fragment: Object.assign( {}, fragmentModule, { targets } ),
  42272. primitive: primitiveState,
  42273. multisample: {
  42274. count: sampleCount,
  42275. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  42276. },
  42277. layout: device.createPipelineLayout( {
  42278. bindGroupLayouts
  42279. } )
  42280. };
  42281. const depthStencil = {};
  42282. const renderDepth = renderObject.context.depth;
  42283. const renderStencil = renderObject.context.stencil;
  42284. if ( renderDepth === true || renderStencil === true ) {
  42285. if ( renderDepth === true ) {
  42286. depthStencil.format = depthStencilFormat;
  42287. depthStencil.depthWriteEnabled = material.depthWrite;
  42288. depthStencil.depthCompare = depthCompare;
  42289. }
  42290. if ( renderStencil === true ) {
  42291. depthStencil.stencilFront = stencilFront;
  42292. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  42293. depthStencil.stencilReadMask = material.stencilFuncMask;
  42294. depthStencil.stencilWriteMask = material.stencilWriteMask;
  42295. }
  42296. pipelineDescriptor.depthStencil = depthStencil;
  42297. }
  42298. if ( promises === null ) {
  42299. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  42300. } else {
  42301. const p = new Promise( ( resolve /*, reject*/ ) => {
  42302. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  42303. pipelineData.pipeline = pipeline;
  42304. resolve();
  42305. } );
  42306. } );
  42307. promises.push( p );
  42308. }
  42309. }
  42310. createBundleEncoder( renderContext ) {
  42311. const backend = this.backend;
  42312. const { utils, device } = backend;
  42313. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  42314. const colorFormat = utils.getCurrentColorFormat( renderContext );
  42315. const sampleCount = this._getSampleCount( renderContext );
  42316. const descriptor = {
  42317. label: 'renderBundleEncoder',
  42318. colorFormats: [ colorFormat ],
  42319. depthStencilFormat,
  42320. sampleCount
  42321. };
  42322. return device.createRenderBundleEncoder( descriptor );
  42323. }
  42324. createComputePipeline( pipeline, bindings ) {
  42325. const backend = this.backend;
  42326. const device = backend.device;
  42327. const computeProgram = backend.get( pipeline.computeProgram ).module;
  42328. const pipelineGPU = backend.get( pipeline );
  42329. // bind group layouts
  42330. const bindGroupLayouts = [];
  42331. for ( const bindingsGroup of bindings ) {
  42332. const bindingsData = backend.get( bindingsGroup );
  42333. bindGroupLayouts.push( bindingsData.layout );
  42334. }
  42335. pipelineGPU.pipeline = device.createComputePipeline( {
  42336. compute: computeProgram,
  42337. layout: device.createPipelineLayout( {
  42338. bindGroupLayouts
  42339. } )
  42340. } );
  42341. }
  42342. _getBlending( material ) {
  42343. let color, alpha;
  42344. const blending = material.blending;
  42345. const blendSrc = material.blendSrc;
  42346. const blendDst = material.blendDst;
  42347. const blendEquation = material.blendEquation;
  42348. if ( blending === CustomBlending ) {
  42349. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  42350. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  42351. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  42352. color = {
  42353. srcFactor: this._getBlendFactor( blendSrc ),
  42354. dstFactor: this._getBlendFactor( blendDst ),
  42355. operation: this._getBlendOperation( blendEquation )
  42356. };
  42357. alpha = {
  42358. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  42359. dstFactor: this._getBlendFactor( blendDstAlpha ),
  42360. operation: this._getBlendOperation( blendEquationAlpha )
  42361. };
  42362. } else {
  42363. const premultipliedAlpha = material.premultipliedAlpha;
  42364. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  42365. color = {
  42366. srcFactor: srcRGB,
  42367. dstFactor: dstRGB,
  42368. operation: GPUBlendOperation.Add
  42369. };
  42370. alpha = {
  42371. srcFactor: srcAlpha,
  42372. dstFactor: dstAlpha,
  42373. operation: GPUBlendOperation.Add
  42374. };
  42375. };
  42376. if ( premultipliedAlpha ) {
  42377. switch ( blending ) {
  42378. case NormalBlending:
  42379. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  42380. break;
  42381. case AdditiveBlending:
  42382. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  42383. break;
  42384. case SubtractiveBlending:
  42385. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  42386. break;
  42387. case MultiplyBlending:
  42388. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  42389. break;
  42390. }
  42391. } else {
  42392. switch ( blending ) {
  42393. case NormalBlending:
  42394. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  42395. break;
  42396. case AdditiveBlending:
  42397. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  42398. break;
  42399. case SubtractiveBlending:
  42400. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  42401. break;
  42402. case MultiplyBlending:
  42403. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  42404. break;
  42405. }
  42406. }
  42407. }
  42408. if ( color !== undefined && alpha !== undefined ) {
  42409. return { color, alpha };
  42410. } else {
  42411. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  42412. }
  42413. }
  42414. _getBlendFactor( blend ) {
  42415. let blendFactor;
  42416. switch ( blend ) {
  42417. case ZeroFactor:
  42418. blendFactor = GPUBlendFactor.Zero;
  42419. break;
  42420. case OneFactor:
  42421. blendFactor = GPUBlendFactor.One;
  42422. break;
  42423. case SrcColorFactor:
  42424. blendFactor = GPUBlendFactor.Src;
  42425. break;
  42426. case OneMinusSrcColorFactor:
  42427. blendFactor = GPUBlendFactor.OneMinusSrc;
  42428. break;
  42429. case SrcAlphaFactor:
  42430. blendFactor = GPUBlendFactor.SrcAlpha;
  42431. break;
  42432. case OneMinusSrcAlphaFactor:
  42433. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  42434. break;
  42435. case DstColorFactor:
  42436. blendFactor = GPUBlendFactor.Dst;
  42437. break;
  42438. case OneMinusDstColorFactor:
  42439. blendFactor = GPUBlendFactor.OneMinusDstColor;
  42440. break;
  42441. case DstAlphaFactor:
  42442. blendFactor = GPUBlendFactor.DstAlpha;
  42443. break;
  42444. case OneMinusDstAlphaFactor:
  42445. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  42446. break;
  42447. case SrcAlphaSaturateFactor:
  42448. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  42449. break;
  42450. case BlendColorFactor:
  42451. blendFactor = GPUBlendFactor.Constant;
  42452. break;
  42453. case OneMinusBlendColorFactor:
  42454. blendFactor = GPUBlendFactor.OneMinusConstant;
  42455. break;
  42456. default:
  42457. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  42458. }
  42459. return blendFactor;
  42460. }
  42461. _getStencilCompare( material ) {
  42462. let stencilCompare;
  42463. const stencilFunc = material.stencilFunc;
  42464. switch ( stencilFunc ) {
  42465. case NeverStencilFunc:
  42466. stencilCompare = GPUCompareFunction.Never;
  42467. break;
  42468. case AlwaysStencilFunc:
  42469. stencilCompare = GPUCompareFunction.Always;
  42470. break;
  42471. case LessStencilFunc:
  42472. stencilCompare = GPUCompareFunction.Less;
  42473. break;
  42474. case LessEqualStencilFunc:
  42475. stencilCompare = GPUCompareFunction.LessEqual;
  42476. break;
  42477. case EqualStencilFunc:
  42478. stencilCompare = GPUCompareFunction.Equal;
  42479. break;
  42480. case GreaterEqualStencilFunc:
  42481. stencilCompare = GPUCompareFunction.GreaterEqual;
  42482. break;
  42483. case GreaterStencilFunc:
  42484. stencilCompare = GPUCompareFunction.Greater;
  42485. break;
  42486. case NotEqualStencilFunc:
  42487. stencilCompare = GPUCompareFunction.NotEqual;
  42488. break;
  42489. default:
  42490. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  42491. }
  42492. return stencilCompare;
  42493. }
  42494. _getStencilOperation( op ) {
  42495. let stencilOperation;
  42496. switch ( op ) {
  42497. case KeepStencilOp:
  42498. stencilOperation = GPUStencilOperation.Keep;
  42499. break;
  42500. case ZeroStencilOp:
  42501. stencilOperation = GPUStencilOperation.Zero;
  42502. break;
  42503. case ReplaceStencilOp:
  42504. stencilOperation = GPUStencilOperation.Replace;
  42505. break;
  42506. case InvertStencilOp:
  42507. stencilOperation = GPUStencilOperation.Invert;
  42508. break;
  42509. case IncrementStencilOp:
  42510. stencilOperation = GPUStencilOperation.IncrementClamp;
  42511. break;
  42512. case DecrementStencilOp:
  42513. stencilOperation = GPUStencilOperation.DecrementClamp;
  42514. break;
  42515. case IncrementWrapStencilOp:
  42516. stencilOperation = GPUStencilOperation.IncrementWrap;
  42517. break;
  42518. case DecrementWrapStencilOp:
  42519. stencilOperation = GPUStencilOperation.DecrementWrap;
  42520. break;
  42521. default:
  42522. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  42523. }
  42524. return stencilOperation;
  42525. }
  42526. _getBlendOperation( blendEquation ) {
  42527. let blendOperation;
  42528. switch ( blendEquation ) {
  42529. case AddEquation:
  42530. blendOperation = GPUBlendOperation.Add;
  42531. break;
  42532. case SubtractEquation:
  42533. blendOperation = GPUBlendOperation.Subtract;
  42534. break;
  42535. case ReverseSubtractEquation:
  42536. blendOperation = GPUBlendOperation.ReverseSubtract;
  42537. break;
  42538. case MinEquation:
  42539. blendOperation = GPUBlendOperation.Min;
  42540. break;
  42541. case MaxEquation:
  42542. blendOperation = GPUBlendOperation.Max;
  42543. break;
  42544. default:
  42545. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  42546. }
  42547. return blendOperation;
  42548. }
  42549. _getPrimitiveState( object, geometry, material ) {
  42550. const descriptor = {};
  42551. const utils = this.backend.utils;
  42552. descriptor.topology = utils.getPrimitiveTopology( object, material );
  42553. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  42554. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  42555. }
  42556. switch ( material.side ) {
  42557. case FrontSide:
  42558. descriptor.frontFace = GPUFrontFace.CCW;
  42559. descriptor.cullMode = GPUCullMode.Back;
  42560. break;
  42561. case BackSide:
  42562. descriptor.frontFace = GPUFrontFace.CCW;
  42563. descriptor.cullMode = GPUCullMode.Front;
  42564. break;
  42565. case DoubleSide:
  42566. descriptor.frontFace = GPUFrontFace.CCW;
  42567. descriptor.cullMode = GPUCullMode.None;
  42568. break;
  42569. default:
  42570. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  42571. break;
  42572. }
  42573. return descriptor;
  42574. }
  42575. _getColorWriteMask( material ) {
  42576. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  42577. }
  42578. _getDepthCompare( material ) {
  42579. let depthCompare;
  42580. if ( material.depthTest === false ) {
  42581. depthCompare = GPUCompareFunction.Always;
  42582. } else {
  42583. const depthFunc = material.depthFunc;
  42584. switch ( depthFunc ) {
  42585. case NeverDepth:
  42586. depthCompare = GPUCompareFunction.Never;
  42587. break;
  42588. case AlwaysDepth:
  42589. depthCompare = GPUCompareFunction.Always;
  42590. break;
  42591. case LessDepth:
  42592. depthCompare = GPUCompareFunction.Less;
  42593. break;
  42594. case LessEqualDepth:
  42595. depthCompare = GPUCompareFunction.LessEqual;
  42596. break;
  42597. case EqualDepth:
  42598. depthCompare = GPUCompareFunction.Equal;
  42599. break;
  42600. case GreaterEqualDepth:
  42601. depthCompare = GPUCompareFunction.GreaterEqual;
  42602. break;
  42603. case GreaterDepth:
  42604. depthCompare = GPUCompareFunction.Greater;
  42605. break;
  42606. case NotEqualDepth:
  42607. depthCompare = GPUCompareFunction.NotEqual;
  42608. break;
  42609. default:
  42610. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  42611. }
  42612. }
  42613. return depthCompare;
  42614. }
  42615. }
  42616. /*// debugger tools
  42617. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  42618. //*/
  42619. /**
  42620. * A backend implementation targeting WebGPU.
  42621. *
  42622. * @private
  42623. * @augments Backend
  42624. */
  42625. class WebGPUBackend extends Backend {
  42626. /**
  42627. * Constructs a new WebGPU backend.
  42628. *
  42629. * @param {Object} parameters - The configuration parameter.
  42630. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  42631. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  42632. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  42633. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  42634. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  42635. * @param {Number} [parameters.samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  42636. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses it WebGL 2 backend no matter if WebGPU is supported or not.
  42637. * @param {Boolean} [parameters.trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  42638. * @param {String?} [parameters.powerPreference=null] - The power preference.
  42639. * @param {String?} [parameters.requiredLimits={}] - Specifies the limits that are required by the device request.
  42640. * The request will fail if the adapter cannot provide these limits.
  42641. */
  42642. constructor( parameters = {} ) {
  42643. super( parameters );
  42644. /**
  42645. * This flag can be used for type testing.
  42646. *
  42647. * @type {Boolean}
  42648. * @readonly
  42649. * @default true
  42650. */
  42651. this.isWebGPUBackend = true;
  42652. // some parameters require default values other than "undefined"
  42653. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  42654. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  42655. /**
  42656. * Whether to track timestamps with a Timestamp Query API or not.
  42657. *
  42658. * @type {Boolean}
  42659. * @default false
  42660. */
  42661. this.trackTimestamp = ( parameters.trackTimestamp === true );
  42662. /**
  42663. * A reference to the device.
  42664. *
  42665. * @type {GPUDevice?}
  42666. * @default null
  42667. */
  42668. this.device = null;
  42669. /**
  42670. * A reference to the context.
  42671. *
  42672. * @type {GPUCanvasContext?}
  42673. * @default null
  42674. */
  42675. this.context = null;
  42676. /**
  42677. * A reference to the color attachment of the default framebuffer.
  42678. *
  42679. * @type {GPUTexture?}
  42680. * @default null
  42681. */
  42682. this.colorBuffer = null;
  42683. /**
  42684. * A reference to the default render pass descriptor.
  42685. *
  42686. * @type {Object?}
  42687. * @default null
  42688. */
  42689. this.defaultRenderPassdescriptor = null;
  42690. /**
  42691. * A reference to a backend module holding common utility functions.
  42692. *
  42693. * @type {WebGPUUtils}
  42694. */
  42695. this.utils = new WebGPUUtils( this );
  42696. /**
  42697. * A reference to a backend module holding shader attribute-related
  42698. * utility functions.
  42699. *
  42700. * @type {WebGPUAttributeUtils}
  42701. */
  42702. this.attributeUtils = new WebGPUAttributeUtils( this );
  42703. /**
  42704. * A reference to a backend module holding shader binding-related
  42705. * utility functions.
  42706. *
  42707. * @type {WebGPUBindingUtils}
  42708. */
  42709. this.bindingUtils = new WebGPUBindingUtils( this );
  42710. /**
  42711. * A reference to a backend module holding shader pipeline-related
  42712. * utility functions.
  42713. *
  42714. * @type {WebGPUPipelineUtils}
  42715. */
  42716. this.pipelineUtils = new WebGPUPipelineUtils( this );
  42717. /**
  42718. * A reference to a backend module holding shader texture-related
  42719. * utility functions.
  42720. *
  42721. * @type {WebGPUTextureUtils}
  42722. */
  42723. this.textureUtils = new WebGPUTextureUtils( this );
  42724. /**
  42725. * A map that manages the resolve buffers for occlusion queries.
  42726. *
  42727. * @type {Map<Number,GPUBuffer>}
  42728. */
  42729. this.occludedResolveCache = new Map();
  42730. }
  42731. /**
  42732. * Initializes the backend so it is ready for usage.
  42733. *
  42734. * @async
  42735. * @param {Renderer} renderer - The renderer.
  42736. * @return {Promise} A Promise that resolves when the backend has been initialized.
  42737. */
  42738. async init( renderer ) {
  42739. await super.init( renderer );
  42740. //
  42741. const parameters = this.parameters;
  42742. // create the device if it is not passed with parameters
  42743. let device;
  42744. if ( parameters.device === undefined ) {
  42745. const adapterOptions = {
  42746. powerPreference: parameters.powerPreference
  42747. };
  42748. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  42749. if ( adapter === null ) {
  42750. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  42751. }
  42752. // feature support
  42753. const features = Object.values( GPUFeatureName );
  42754. const supportedFeatures = [];
  42755. for ( const name of features ) {
  42756. if ( adapter.features.has( name ) ) {
  42757. supportedFeatures.push( name );
  42758. }
  42759. }
  42760. const deviceDescriptor = {
  42761. requiredFeatures: supportedFeatures,
  42762. requiredLimits: parameters.requiredLimits
  42763. };
  42764. device = await adapter.requestDevice( deviceDescriptor );
  42765. } else {
  42766. device = parameters.device;
  42767. }
  42768. device.lost.then( ( info ) => {
  42769. const deviceLossInfo = {
  42770. api: 'WebGPU',
  42771. message: info.message || 'Unknown reason',
  42772. reason: info.reason || null,
  42773. originalEvent: info
  42774. };
  42775. renderer.onDeviceLost( deviceLossInfo );
  42776. } );
  42777. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  42778. this.device = device;
  42779. this.context = context;
  42780. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  42781. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  42782. this.context.configure( {
  42783. device: this.device,
  42784. format: this.utils.getPreferredCanvasFormat(),
  42785. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  42786. alphaMode: alphaMode
  42787. } );
  42788. this.updateSize();
  42789. }
  42790. /**
  42791. * The coordinate system of the backend.
  42792. *
  42793. * @type {Number}
  42794. * @readonly
  42795. */
  42796. get coordinateSystem() {
  42797. return WebGPUCoordinateSystem;
  42798. }
  42799. /**
  42800. * Transfers buffer data from a storage buffer attribute
  42801. * from the GPU to the CPU in context of compute shaders.
  42802. *
  42803. * @async
  42804. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  42805. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  42806. */
  42807. async getArrayBufferAsync( attribute ) {
  42808. return await this.attributeUtils.getArrayBufferAsync( attribute );
  42809. }
  42810. /**
  42811. * Returns the backend's rendering context.
  42812. *
  42813. * @return {GPUCanvasContext} The rendering context.
  42814. */
  42815. getContext() {
  42816. return this.context;
  42817. }
  42818. /**
  42819. * Returns the default render pass descriptor.
  42820. *
  42821. * In WebGPU, the default framebuffer must be configured
  42822. * like custom fraemebuffers so the backend needs a render
  42823. * pass descriptor even when rendering directly to screen.
  42824. *
  42825. * @private
  42826. * @return {Object} The render pass descriptor.
  42827. */
  42828. _getDefaultRenderPassDescriptor() {
  42829. let descriptor = this.defaultRenderPassdescriptor;
  42830. if ( descriptor === null ) {
  42831. const renderer = this.renderer;
  42832. descriptor = {
  42833. colorAttachments: [ {
  42834. view: null
  42835. } ],
  42836. };
  42837. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  42838. descriptor.depthStencilAttachment = {
  42839. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  42840. };
  42841. }
  42842. const colorAttachment = descriptor.colorAttachments[ 0 ];
  42843. if ( this.renderer.samples > 0 ) {
  42844. colorAttachment.view = this.colorBuffer.createView();
  42845. } else {
  42846. colorAttachment.resolveTarget = undefined;
  42847. }
  42848. this.defaultRenderPassdescriptor = descriptor;
  42849. }
  42850. const colorAttachment = descriptor.colorAttachments[ 0 ];
  42851. if ( this.renderer.samples > 0 ) {
  42852. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  42853. } else {
  42854. colorAttachment.view = this.context.getCurrentTexture().createView();
  42855. }
  42856. return descriptor;
  42857. }
  42858. /**
  42859. * Returns the render pass descriptor for the given render context.
  42860. *
  42861. * @private
  42862. * @param {RenderContext} renderContext - The render context.
  42863. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  42864. * @return {Object} The render pass descriptor.
  42865. */
  42866. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  42867. const renderTarget = renderContext.renderTarget;
  42868. const renderTargetData = this.get( renderTarget );
  42869. let descriptors = renderTargetData.descriptors;
  42870. if ( descriptors === undefined ||
  42871. renderTargetData.width !== renderTarget.width ||
  42872. renderTargetData.height !== renderTarget.height ||
  42873. renderTargetData.dimensions !== renderTarget.dimensions ||
  42874. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  42875. renderTargetData.activeCubeFace !== renderContext.activeCubeFace ||
  42876. renderTargetData.samples !== renderTarget.samples ||
  42877. renderTargetData.loadOp !== colorAttachmentsConfig.loadOp
  42878. ) {
  42879. descriptors = {};
  42880. renderTargetData.descriptors = descriptors;
  42881. // dispose
  42882. const onDispose = () => {
  42883. renderTarget.removeEventListener( 'dispose', onDispose );
  42884. this.delete( renderTarget );
  42885. };
  42886. renderTarget.addEventListener( 'dispose', onDispose );
  42887. }
  42888. const cacheKey = renderContext.getCacheKey();
  42889. let descriptor = descriptors[ cacheKey ];
  42890. if ( descriptor === undefined ) {
  42891. const textures = renderContext.textures;
  42892. const colorAttachments = [];
  42893. let sliceIndex;
  42894. for ( let i = 0; i < textures.length; i ++ ) {
  42895. const textureData = this.get( textures[ i ] );
  42896. const viewDescriptor = {
  42897. label: `colorAttachment_${ i }`,
  42898. baseMipLevel: renderContext.activeMipmapLevel,
  42899. mipLevelCount: 1,
  42900. baseArrayLayer: renderContext.activeCubeFace,
  42901. arrayLayerCount: 1,
  42902. dimension: GPUTextureViewDimension.TwoD
  42903. };
  42904. if ( renderTarget.isRenderTarget3D ) {
  42905. sliceIndex = renderContext.activeCubeFace;
  42906. viewDescriptor.baseArrayLayer = 0;
  42907. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  42908. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  42909. } else if ( renderTarget.isRenderTargetArray ) {
  42910. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  42911. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  42912. }
  42913. const textureView = textureData.texture.createView( viewDescriptor );
  42914. let view, resolveTarget;
  42915. if ( textureData.msaaTexture !== undefined ) {
  42916. view = textureData.msaaTexture.createView();
  42917. resolveTarget = textureView;
  42918. } else {
  42919. view = textureView;
  42920. resolveTarget = undefined;
  42921. }
  42922. colorAttachments.push( {
  42923. view,
  42924. depthSlice: sliceIndex,
  42925. resolveTarget,
  42926. loadOp: GPULoadOp.Load,
  42927. storeOp: GPUStoreOp.Store,
  42928. ...colorAttachmentsConfig
  42929. } );
  42930. }
  42931. descriptor = {
  42932. colorAttachments,
  42933. };
  42934. if ( renderContext.depth ) {
  42935. const depthTextureData = this.get( renderContext.depthTexture );
  42936. const depthStencilAttachment = {
  42937. view: depthTextureData.texture.createView()
  42938. };
  42939. descriptor.depthStencilAttachment = depthStencilAttachment;
  42940. }
  42941. descriptors[ cacheKey ] = descriptor;
  42942. renderTargetData.width = renderTarget.width;
  42943. renderTargetData.height = renderTarget.height;
  42944. renderTargetData.samples = renderTarget.samples;
  42945. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  42946. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  42947. renderTargetData.dimensions = renderTarget.dimensions;
  42948. renderTargetData.depthSlice = sliceIndex;
  42949. renderTargetData.loadOp = colorAttachments[ 0 ].loadOp;
  42950. }
  42951. return descriptor;
  42952. }
  42953. /**
  42954. * This method is executed at the beginning of a render call and prepares
  42955. * the WebGPU state for upcoming render calls
  42956. *
  42957. * @param {RenderContext} renderContext - The render context.
  42958. */
  42959. beginRender( renderContext ) {
  42960. const renderContextData = this.get( renderContext );
  42961. const device = this.device;
  42962. const occlusionQueryCount = renderContext.occlusionQueryCount;
  42963. let occlusionQuerySet;
  42964. if ( occlusionQueryCount > 0 ) {
  42965. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  42966. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  42967. // Get a reference to the array of objects with queries. The renderContextData property
  42968. // can be changed by another render pass before the buffer.mapAsyc() completes.
  42969. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  42970. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  42971. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  42972. //
  42973. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  42974. renderContextData.occlusionQuerySet = occlusionQuerySet;
  42975. renderContextData.occlusionQueryIndex = 0;
  42976. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  42977. renderContextData.lastOcclusionObject = null;
  42978. }
  42979. let descriptor;
  42980. if ( renderContext.textures === null ) {
  42981. descriptor = this._getDefaultRenderPassDescriptor();
  42982. } else {
  42983. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  42984. }
  42985. this.initTimestampQuery( renderContext, descriptor );
  42986. descriptor.occlusionQuerySet = occlusionQuerySet;
  42987. const depthStencilAttachment = descriptor.depthStencilAttachment;
  42988. if ( renderContext.textures !== null ) {
  42989. const colorAttachments = descriptor.colorAttachments;
  42990. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  42991. const colorAttachment = colorAttachments[ i ];
  42992. if ( renderContext.clearColor ) {
  42993. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  42994. colorAttachment.loadOp = GPULoadOp.Clear;
  42995. colorAttachment.storeOp = GPUStoreOp.Store;
  42996. } else {
  42997. colorAttachment.loadOp = GPULoadOp.Load;
  42998. colorAttachment.storeOp = GPUStoreOp.Store;
  42999. }
  43000. }
  43001. } else {
  43002. const colorAttachment = descriptor.colorAttachments[ 0 ];
  43003. if ( renderContext.clearColor ) {
  43004. colorAttachment.clearValue = renderContext.clearColorValue;
  43005. colorAttachment.loadOp = GPULoadOp.Clear;
  43006. colorAttachment.storeOp = GPUStoreOp.Store;
  43007. } else {
  43008. colorAttachment.loadOp = GPULoadOp.Load;
  43009. colorAttachment.storeOp = GPUStoreOp.Store;
  43010. }
  43011. }
  43012. //
  43013. if ( renderContext.depth ) {
  43014. if ( renderContext.clearDepth ) {
  43015. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  43016. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  43017. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  43018. } else {
  43019. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  43020. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  43021. }
  43022. }
  43023. if ( renderContext.stencil ) {
  43024. if ( renderContext.clearStencil ) {
  43025. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  43026. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  43027. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  43028. } else {
  43029. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  43030. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  43031. }
  43032. }
  43033. //
  43034. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  43035. const currentPass = encoder.beginRenderPass( descriptor );
  43036. //
  43037. renderContextData.descriptor = descriptor;
  43038. renderContextData.encoder = encoder;
  43039. renderContextData.currentPass = currentPass;
  43040. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  43041. renderContextData.renderBundles = [];
  43042. //
  43043. if ( renderContext.viewport ) {
  43044. this.updateViewport( renderContext );
  43045. }
  43046. if ( renderContext.scissor ) {
  43047. const { x, y, width, height } = renderContext.scissorValue;
  43048. currentPass.setScissorRect( x, y, width, height );
  43049. }
  43050. }
  43051. /**
  43052. * This method is executed at the end of a render call and finalizes work
  43053. * after draw calls.
  43054. *
  43055. * @param {RenderContext} renderContext - The render context.
  43056. */
  43057. finishRender( renderContext ) {
  43058. const renderContextData = this.get( renderContext );
  43059. const occlusionQueryCount = renderContext.occlusionQueryCount;
  43060. if ( renderContextData.renderBundles.length > 0 ) {
  43061. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  43062. }
  43063. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  43064. renderContextData.currentPass.endOcclusionQuery();
  43065. }
  43066. renderContextData.currentPass.end();
  43067. if ( occlusionQueryCount > 0 ) {
  43068. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  43069. //
  43070. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  43071. if ( queryResolveBuffer === undefined ) {
  43072. queryResolveBuffer = this.device.createBuffer(
  43073. {
  43074. size: bufferSize,
  43075. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  43076. }
  43077. );
  43078. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  43079. }
  43080. //
  43081. const readBuffer = this.device.createBuffer(
  43082. {
  43083. size: bufferSize,
  43084. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  43085. }
  43086. );
  43087. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  43088. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  43089. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  43090. renderContextData.occlusionQueryBuffer = readBuffer;
  43091. //
  43092. this.resolveOccludedAsync( renderContext );
  43093. }
  43094. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  43095. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  43096. //
  43097. if ( renderContext.textures !== null ) {
  43098. const textures = renderContext.textures;
  43099. for ( let i = 0; i < textures.length; i ++ ) {
  43100. const texture = textures[ i ];
  43101. if ( texture.generateMipmaps === true ) {
  43102. this.textureUtils.generateMipmaps( texture );
  43103. }
  43104. }
  43105. }
  43106. }
  43107. /**
  43108. * Returns `true` if the given 3D object is fully occluded by other
  43109. * 3D objects in the scene.
  43110. *
  43111. * @param {RenderContext} renderContext - The render context.
  43112. * @param {Object3D} object - The 3D object to test.
  43113. * @return {Boolean} Whether the 3D object is fully occluded or not.
  43114. */
  43115. isOccluded( renderContext, object ) {
  43116. const renderContextData = this.get( renderContext );
  43117. return renderContextData.occluded && renderContextData.occluded.has( object );
  43118. }
  43119. /**
  43120. * This method processes the result of occlusion queries and writes it
  43121. * into render context data.
  43122. *
  43123. * @async
  43124. * @param {RenderContext} renderContext - The render context.
  43125. */
  43126. async resolveOccludedAsync( renderContext ) {
  43127. const renderContextData = this.get( renderContext );
  43128. // handle occlusion query results
  43129. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  43130. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  43131. const occluded = new WeakSet();
  43132. renderContextData.currentOcclusionQueryObjects = null;
  43133. renderContextData.currentOcclusionQueryBuffer = null;
  43134. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  43135. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  43136. const results = new BigUint64Array( buffer );
  43137. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  43138. if ( results[ i ] !== BigInt( 0 ) ) {
  43139. occluded.add( currentOcclusionQueryObjects[ i ] );
  43140. }
  43141. }
  43142. currentOcclusionQueryBuffer.destroy();
  43143. renderContextData.occluded = occluded;
  43144. }
  43145. }
  43146. /**
  43147. * Updates the viewport with the values from the given render context.
  43148. *
  43149. * @param {RenderContext} renderContext - The render context.
  43150. */
  43151. updateViewport( renderContext ) {
  43152. const { currentPass } = this.get( renderContext );
  43153. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  43154. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  43155. }
  43156. /**
  43157. * Performs a clear operation.
  43158. *
  43159. * @param {Boolean} color - Whether the color buffer should be cleared or not.
  43160. * @param {Boolean} depth - Whether the depth buffer should be cleared or not.
  43161. * @param {Boolean} stencil - Whether the stencil buffer should be cleared or not.
  43162. * @param {RenderContext?} [renderTargetContext=null] - The render context of the current set render target.
  43163. */
  43164. clear( color, depth, stencil, renderTargetContext = null ) {
  43165. const device = this.device;
  43166. const renderer = this.renderer;
  43167. let colorAttachments = [];
  43168. let depthStencilAttachment;
  43169. let clearValue;
  43170. let supportsDepth;
  43171. let supportsStencil;
  43172. if ( color ) {
  43173. const clearColor = this.getClearColor();
  43174. if ( this.renderer.alpha === true ) {
  43175. // premultiply alpha
  43176. const a = clearColor.a;
  43177. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  43178. } else {
  43179. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  43180. }
  43181. }
  43182. if ( renderTargetContext === null ) {
  43183. supportsDepth = renderer.depth;
  43184. supportsStencil = renderer.stencil;
  43185. const descriptor = this._getDefaultRenderPassDescriptor();
  43186. if ( color ) {
  43187. colorAttachments = descriptor.colorAttachments;
  43188. const colorAttachment = colorAttachments[ 0 ];
  43189. colorAttachment.clearValue = clearValue;
  43190. colorAttachment.loadOp = GPULoadOp.Clear;
  43191. colorAttachment.storeOp = GPUStoreOp.Store;
  43192. }
  43193. if ( supportsDepth || supportsStencil ) {
  43194. depthStencilAttachment = descriptor.depthStencilAttachment;
  43195. }
  43196. } else {
  43197. supportsDepth = renderTargetContext.depth;
  43198. supportsStencil = renderTargetContext.stencil;
  43199. if ( color ) {
  43200. const descriptor = this._getRenderPassDescriptor( renderTargetContext, { loadOp: GPULoadOp.Clear } );
  43201. colorAttachments = descriptor.colorAttachments;
  43202. }
  43203. if ( supportsDepth || supportsStencil ) {
  43204. const depthTextureData = this.get( renderTargetContext.depthTexture );
  43205. depthStencilAttachment = {
  43206. view: depthTextureData.texture.createView()
  43207. };
  43208. }
  43209. }
  43210. //
  43211. if ( supportsDepth ) {
  43212. if ( depth ) {
  43213. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  43214. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  43215. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  43216. } else {
  43217. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  43218. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  43219. }
  43220. }
  43221. //
  43222. if ( supportsStencil ) {
  43223. if ( stencil ) {
  43224. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  43225. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  43226. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  43227. } else {
  43228. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  43229. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  43230. }
  43231. }
  43232. //
  43233. const encoder = device.createCommandEncoder( {} );
  43234. const currentPass = encoder.beginRenderPass( {
  43235. colorAttachments,
  43236. depthStencilAttachment
  43237. } );
  43238. currentPass.end();
  43239. device.queue.submit( [ encoder.finish() ] );
  43240. }
  43241. // compute
  43242. /**
  43243. * This method is executed at the beginning of a compute call and
  43244. * prepares the state for upcoming compute tasks.
  43245. *
  43246. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  43247. */
  43248. beginCompute( computeGroup ) {
  43249. const groupGPU = this.get( computeGroup );
  43250. const descriptor = {};
  43251. this.initTimestampQuery( computeGroup, descriptor );
  43252. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  43253. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  43254. }
  43255. /**
  43256. * Executes a compute command for the given compute node.
  43257. *
  43258. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  43259. * @param {Node} computeNode - The compute node.
  43260. * @param {Array<BindGroup>} bindings - The bindings.
  43261. * @param {ComputePipeline} pipeline - The compute pipeline.
  43262. */
  43263. compute( computeGroup, computeNode, bindings, pipeline ) {
  43264. const { passEncoderGPU } = this.get( computeGroup );
  43265. // pipeline
  43266. const pipelineGPU = this.get( pipeline ).pipeline;
  43267. passEncoderGPU.setPipeline( pipelineGPU );
  43268. // bind groups
  43269. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  43270. const bindGroup = bindings[ i ];
  43271. const bindingsData = this.get( bindGroup );
  43272. passEncoderGPU.setBindGroup( i, bindingsData.group );
  43273. }
  43274. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  43275. const computeNodeData = this.get( computeNode );
  43276. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  43277. const { dispatchSize } = computeNodeData;
  43278. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  43279. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  43280. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  43281. } else {
  43282. dispatchSize.x = computeNode.dispatchCount;
  43283. }
  43284. passEncoderGPU.dispatchWorkgroups(
  43285. dispatchSize.x,
  43286. dispatchSize.y,
  43287. dispatchSize.z
  43288. );
  43289. }
  43290. /**
  43291. * This method is executed at the end of a compute call and
  43292. * finalizes work after compute tasks.
  43293. *
  43294. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  43295. */
  43296. finishCompute( computeGroup ) {
  43297. const groupData = this.get( computeGroup );
  43298. groupData.passEncoderGPU.end();
  43299. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  43300. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  43301. }
  43302. /**
  43303. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  43304. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  43305. *
  43306. * @async
  43307. * @return {Promise} A Promise that resolves when synchronization has been finished.
  43308. */
  43309. async waitForGPU() {
  43310. await this.device.queue.onSubmittedWorkDone();
  43311. }
  43312. // render object
  43313. /**
  43314. * Executes a draw command for the given render object.
  43315. *
  43316. * @param {RenderObject} renderObject - The render object to draw.
  43317. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  43318. */
  43319. draw( renderObject, info ) {
  43320. const { object, context, pipeline } = renderObject;
  43321. const bindings = renderObject.getBindings();
  43322. const renderContextData = this.get( context );
  43323. const pipelineGPU = this.get( pipeline ).pipeline;
  43324. const currentSets = renderContextData.currentSets;
  43325. const passEncoderGPU = renderContextData.currentPass;
  43326. const drawParams = renderObject.getDrawParameters();
  43327. if ( drawParams === null ) return;
  43328. // pipeline
  43329. if ( currentSets.pipeline !== pipelineGPU ) {
  43330. passEncoderGPU.setPipeline( pipelineGPU );
  43331. currentSets.pipeline = pipelineGPU;
  43332. }
  43333. // bind groups
  43334. const currentBindingGroups = currentSets.bindingGroups;
  43335. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  43336. const bindGroup = bindings[ i ];
  43337. const bindingsData = this.get( bindGroup );
  43338. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  43339. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  43340. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  43341. }
  43342. }
  43343. // attributes
  43344. const index = renderObject.getIndex();
  43345. const hasIndex = ( index !== null );
  43346. // index
  43347. if ( hasIndex === true ) {
  43348. if ( currentSets.index !== index ) {
  43349. const buffer = this.get( index ).buffer;
  43350. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  43351. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  43352. currentSets.index = index;
  43353. }
  43354. }
  43355. // vertex buffers
  43356. const vertexBuffers = renderObject.getVertexBuffers();
  43357. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  43358. const vertexBuffer = vertexBuffers[ i ];
  43359. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  43360. const buffer = this.get( vertexBuffer ).buffer;
  43361. passEncoderGPU.setVertexBuffer( i, buffer );
  43362. currentSets.attributes[ i ] = vertexBuffer;
  43363. }
  43364. }
  43365. // occlusion queries - handle multiple consecutive draw calls for an object
  43366. if ( renderContextData.occlusionQuerySet !== undefined ) {
  43367. const lastObject = renderContextData.lastOcclusionObject;
  43368. if ( lastObject !== object ) {
  43369. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  43370. passEncoderGPU.endOcclusionQuery();
  43371. renderContextData.occlusionQueryIndex ++;
  43372. }
  43373. if ( object.occlusionTest === true ) {
  43374. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  43375. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  43376. }
  43377. renderContextData.lastOcclusionObject = object;
  43378. }
  43379. }
  43380. // draw
  43381. if ( object.isBatchedMesh === true ) {
  43382. const starts = object._multiDrawStarts;
  43383. const counts = object._multiDrawCounts;
  43384. const drawCount = object._multiDrawCount;
  43385. const drawInstances = object._multiDrawInstances;
  43386. for ( let i = 0; i < drawCount; i ++ ) {
  43387. const count = drawInstances ? drawInstances[ i ] : 1;
  43388. const firstInstance = count > 1 ? 0 : i;
  43389. if ( hasIndex === true ) {
  43390. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  43391. } else {
  43392. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  43393. }
  43394. }
  43395. } else if ( hasIndex === true ) {
  43396. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  43397. const indirect = renderObject.getIndirect();
  43398. if ( indirect !== null ) {
  43399. const buffer = this.get( indirect ).buffer;
  43400. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  43401. } else {
  43402. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  43403. }
  43404. info.update( object, indexCount, instanceCount );
  43405. } else {
  43406. const { vertexCount, instanceCount, firstVertex } = drawParams;
  43407. const indirect = renderObject.getIndirect();
  43408. if ( indirect !== null ) {
  43409. const buffer = this.get( indirect ).buffer;
  43410. passEncoderGPU.drawIndirect( buffer, 0 );
  43411. } else {
  43412. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  43413. }
  43414. info.update( object, vertexCount, instanceCount );
  43415. }
  43416. }
  43417. // cache key
  43418. /**
  43419. * Returns `true` if the render pipeline requires an update.
  43420. *
  43421. * @param {RenderObject} renderObject - The render object.
  43422. * @return {Boolean} Whether the render pipeline requires an update or not.
  43423. */
  43424. needsRenderUpdate( renderObject ) {
  43425. const data = this.get( renderObject );
  43426. const { object, material } = renderObject;
  43427. const utils = this.utils;
  43428. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  43429. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  43430. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  43431. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  43432. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  43433. let needsUpdate = false;
  43434. if ( data.material !== material || data.materialVersion !== material.version ||
  43435. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  43436. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  43437. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  43438. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  43439. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  43440. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  43441. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  43442. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  43443. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  43444. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  43445. data.primitiveTopology !== primitiveTopology ||
  43446. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  43447. ) {
  43448. data.material = material; data.materialVersion = material.version;
  43449. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  43450. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  43451. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  43452. data.colorWrite = material.colorWrite;
  43453. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  43454. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  43455. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  43456. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  43457. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  43458. data.sampleCount = sampleCount;
  43459. data.colorSpace = colorSpace;
  43460. data.colorFormat = colorFormat;
  43461. data.depthStencilFormat = depthStencilFormat;
  43462. data.primitiveTopology = primitiveTopology;
  43463. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  43464. needsUpdate = true;
  43465. }
  43466. return needsUpdate;
  43467. }
  43468. /**
  43469. * Returns a cache key that is used to identify render pipelines.
  43470. *
  43471. * @param {RenderObject} renderObject - The render object.
  43472. * @return {String} The cache key.
  43473. */
  43474. getRenderCacheKey( renderObject ) {
  43475. const { object, material } = renderObject;
  43476. const utils = this.utils;
  43477. const renderContext = renderObject.context;
  43478. return [
  43479. material.transparent, material.blending, material.premultipliedAlpha,
  43480. material.blendSrc, material.blendDst, material.blendEquation,
  43481. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  43482. material.colorWrite,
  43483. material.depthWrite, material.depthTest, material.depthFunc,
  43484. material.stencilWrite, material.stencilFunc,
  43485. material.stencilFail, material.stencilZFail, material.stencilZPass,
  43486. material.stencilFuncMask, material.stencilWriteMask,
  43487. material.side,
  43488. utils.getSampleCountRenderContext( renderContext ),
  43489. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  43490. utils.getPrimitiveTopology( object, material ),
  43491. renderObject.getGeometryCacheKey(),
  43492. renderObject.clippingContextCacheKey
  43493. ].join();
  43494. }
  43495. // textures
  43496. /**
  43497. * Creates a sampler for the given texture.
  43498. *
  43499. * @param {Texture} texture - The texture to create the sampler for.
  43500. */
  43501. createSampler( texture ) {
  43502. this.textureUtils.createSampler( texture );
  43503. }
  43504. /**
  43505. * Destroys the sampler for the given texture.
  43506. *
  43507. * @param {Texture} texture - The texture to destroy the sampler for.
  43508. */
  43509. destroySampler( texture ) {
  43510. this.textureUtils.destroySampler( texture );
  43511. }
  43512. /**
  43513. * Creates a default texture for the given texture that can be used
  43514. * as a placeholder until the actual texture is ready for usage.
  43515. *
  43516. * @param {Texture} texture - The texture to create a default texture for.
  43517. */
  43518. createDefaultTexture( texture ) {
  43519. this.textureUtils.createDefaultTexture( texture );
  43520. }
  43521. /**
  43522. * Defines a texture on the GPU for the given texture object.
  43523. *
  43524. * @param {Texture} texture - The texture.
  43525. * @param {Object} [options={}] - Optional configuration parameter.
  43526. */
  43527. createTexture( texture, options ) {
  43528. this.textureUtils.createTexture( texture, options );
  43529. }
  43530. /**
  43531. * Uploads the updated texture data to the GPU.
  43532. *
  43533. * @param {Texture} texture - The texture.
  43534. * @param {Object} [options={}] - Optional configuration parameter.
  43535. */
  43536. updateTexture( texture, options ) {
  43537. this.textureUtils.updateTexture( texture, options );
  43538. }
  43539. /**
  43540. * Generates mipmaps for the given texture
  43541. *
  43542. * @param {Texture} texture - The texture.
  43543. */
  43544. generateMipmaps( texture ) {
  43545. this.textureUtils.generateMipmaps( texture );
  43546. }
  43547. /**
  43548. * Destroys the GPU data for the given texture object.
  43549. *
  43550. * @param {Texture} texture - The texture.
  43551. */
  43552. destroyTexture( texture ) {
  43553. this.textureUtils.destroyTexture( texture );
  43554. }
  43555. /**
  43556. * Returns texture data as a typed array.
  43557. *
  43558. * @param {Texture} texture - The texture to copy.
  43559. * @param {Number} x - The x coordinate of the copy origin.
  43560. * @param {Number} y - The y coordinate of the copy origin.
  43561. * @param {Number} width - The width of the copy.
  43562. * @param {Number} height - The height of the copy.
  43563. * @param {Number} faceIndex - The face index.
  43564. * @return {TypedArray} The texture data as a typed array.
  43565. */
  43566. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  43567. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  43568. }
  43569. /**
  43570. * Inits a time stamp query for the given render context.
  43571. *
  43572. * @param {RenderContext} renderContext - The render context.
  43573. * @param {Object} descriptor - The query descriptor.
  43574. */
  43575. initTimestampQuery( renderContext, descriptor ) {
  43576. if ( ! this.trackTimestamp ) return;
  43577. const renderContextData = this.get( renderContext );
  43578. if ( ! renderContextData.timeStampQuerySet ) {
  43579. const type = renderContext.isComputeNode ? 'compute' : 'render';
  43580. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2, label: `timestamp_${type}_${renderContext.id}` } );
  43581. const timestampWrites = {
  43582. querySet: timeStampQuerySet,
  43583. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  43584. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  43585. };
  43586. Object.assign( descriptor, { timestampWrites } );
  43587. renderContextData.timeStampQuerySet = timeStampQuerySet;
  43588. }
  43589. }
  43590. /**
  43591. * Prepares the timestamp buffer.
  43592. *
  43593. * @param {RenderContext} renderContext - The render context.
  43594. * @param {GPUCommandEncoder} encoder - The command encoder.
  43595. */
  43596. prepareTimestampBuffer( renderContext, encoder ) {
  43597. if ( ! this.trackTimestamp ) return;
  43598. const renderContextData = this.get( renderContext );
  43599. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  43600. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  43601. renderContextData.currentTimestampQueryBuffers = {
  43602. resolveBuffer: this.device.createBuffer( {
  43603. label: 'timestamp resolve buffer',
  43604. size: size,
  43605. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  43606. } ),
  43607. resultBuffer: this.device.createBuffer( {
  43608. label: 'timestamp result buffer',
  43609. size: size,
  43610. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  43611. } )
  43612. };
  43613. }
  43614. const { resolveBuffer, resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  43615. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  43616. if ( resultBuffer.mapState === 'unmapped' ) {
  43617. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  43618. }
  43619. }
  43620. /**
  43621. * Resolves the time stamp for the given render context and type.
  43622. *
  43623. * @async
  43624. * @param {RenderContext} renderContext - The render context.
  43625. * @param {String} type - The render context.
  43626. * @return {Promise} A Promise that resolves when the time stamp has been computed.
  43627. */
  43628. async resolveTimestampAsync( renderContext, type = 'render' ) {
  43629. if ( ! this.trackTimestamp ) return;
  43630. const renderContextData = this.get( renderContext );
  43631. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  43632. const { resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  43633. if ( resultBuffer.mapState === 'unmapped' ) {
  43634. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  43635. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  43636. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  43637. this.renderer.info.updateTimestamp( type, duration );
  43638. resultBuffer.unmap();
  43639. } );
  43640. }
  43641. }
  43642. // node builder
  43643. /**
  43644. * Returns a node builder for the given render object.
  43645. *
  43646. * @param {RenderObject} object - The render object.
  43647. * @param {Renderer} renderer - The renderer.
  43648. * @return {WGSLNodeBuilder} The node builder.
  43649. */
  43650. createNodeBuilder( object, renderer ) {
  43651. return new WGSLNodeBuilder( object, renderer );
  43652. }
  43653. // program
  43654. /**
  43655. * Creates a shader program from the given programmable stage.
  43656. *
  43657. * @param {ProgrammableStage} program - The programmable stage.
  43658. */
  43659. createProgram( program ) {
  43660. const programGPU = this.get( program );
  43661. programGPU.module = {
  43662. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  43663. entryPoint: 'main'
  43664. };
  43665. }
  43666. /**
  43667. * Destroys the shader program of the given programmable stage.
  43668. *
  43669. * @param {ProgrammableStage} program - The programmable stage.
  43670. */
  43671. destroyProgram( program ) {
  43672. this.delete( program );
  43673. }
  43674. // pipelines
  43675. /**
  43676. * Creates a render pipeline for the given render object.
  43677. *
  43678. * @param {RenderObject} renderObject - The render object.
  43679. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  43680. */
  43681. createRenderPipeline( renderObject, promises ) {
  43682. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  43683. }
  43684. /**
  43685. * Creates a compute pipeline for the given compute node.
  43686. *
  43687. * @param {ComputePipeline} computePipeline - The compute pipeline.
  43688. * @param {Array<BindGroup>} bindings - The bindings.
  43689. */
  43690. createComputePipeline( computePipeline, bindings ) {
  43691. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  43692. }
  43693. /**
  43694. * Prepares the state for encoding render bundles.
  43695. *
  43696. * @param {RenderContext} renderContext - The render context.
  43697. */
  43698. beginBundle( renderContext ) {
  43699. const renderContextData = this.get( renderContext );
  43700. renderContextData._currentPass = renderContextData.currentPass;
  43701. renderContextData._currentSets = renderContextData.currentSets;
  43702. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  43703. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  43704. }
  43705. /**
  43706. * After processing render bundles this method finalizes related work.
  43707. *
  43708. * @param {RenderContext} renderContext - The render context.
  43709. * @param {RenderBundle} bundle - The render bundle.
  43710. */
  43711. finishBundle( renderContext, bundle ) {
  43712. const renderContextData = this.get( renderContext );
  43713. const bundleEncoder = renderContextData.currentPass;
  43714. const bundleGPU = bundleEncoder.finish();
  43715. this.get( bundle ).bundleGPU = bundleGPU;
  43716. // restore render pass state
  43717. renderContextData.currentSets = renderContextData._currentSets;
  43718. renderContextData.currentPass = renderContextData._currentPass;
  43719. }
  43720. /**
  43721. * Adds a render bundle to the render context data.
  43722. *
  43723. * @param {RenderContext} renderContext - The render context.
  43724. * @param {RenderBundle} bundle - The render bundle to add.
  43725. */
  43726. addBundle( renderContext, bundle ) {
  43727. const renderContextData = this.get( renderContext );
  43728. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  43729. }
  43730. // bindings
  43731. /**
  43732. * Creates bindings from the given bind group definition.
  43733. *
  43734. * @param {BindGroup} bindGroup - The bind group.
  43735. * @param {Array<BindGroup>} bindings - Array of bind groups.
  43736. * @param {Number} cacheIndex - The cache index.
  43737. * @param {Number} version - The version.
  43738. */
  43739. createBindings( bindGroup, bindings, cacheIndex, version ) {
  43740. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  43741. }
  43742. /**
  43743. * Updates the given bind group definition.
  43744. *
  43745. * @param {BindGroup} bindGroup - The bind group.
  43746. * @param {Array<BindGroup>} bindings - Array of bind groups.
  43747. * @param {Number} cacheIndex - The cache index.
  43748. * @param {Number} version - The version.
  43749. */
  43750. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  43751. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  43752. }
  43753. /**
  43754. * Updates a buffer binding.
  43755. *
  43756. * @param {Buffer} binding - The buffer binding to update.
  43757. */
  43758. updateBinding( binding ) {
  43759. this.bindingUtils.updateBinding( binding );
  43760. }
  43761. // attributes
  43762. /**
  43763. * Creates the buffer of an indexed shader attribute.
  43764. *
  43765. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  43766. */
  43767. createIndexAttribute( attribute ) {
  43768. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  43769. }
  43770. /**
  43771. * Creates the buffer of a shader attribute.
  43772. *
  43773. * @param {BufferAttribute} attribute - The buffer attribute.
  43774. */
  43775. createAttribute( attribute ) {
  43776. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  43777. }
  43778. /**
  43779. * Creates the buffer of a storage attribute.
  43780. *
  43781. * @param {BufferAttribute} attribute - The buffer attribute.
  43782. */
  43783. createStorageAttribute( attribute ) {
  43784. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  43785. }
  43786. /**
  43787. * Creates the buffer of an indirect storage attribute.
  43788. *
  43789. * @param {BufferAttribute} attribute - The buffer attribute.
  43790. */
  43791. createIndirectStorageAttribute( attribute ) {
  43792. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  43793. }
  43794. /**
  43795. * Updates the buffer of a shader attribute.
  43796. *
  43797. * @param {BufferAttribute} attribute - The buffer attribute to update.
  43798. */
  43799. updateAttribute( attribute ) {
  43800. this.attributeUtils.updateAttribute( attribute );
  43801. }
  43802. /**
  43803. * Destroys the buffer of a shader attribute.
  43804. *
  43805. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  43806. */
  43807. destroyAttribute( attribute ) {
  43808. this.attributeUtils.destroyAttribute( attribute );
  43809. }
  43810. // canvas
  43811. /**
  43812. * Triggers an update of the default render pass descriptor.
  43813. */
  43814. updateSize() {
  43815. this.colorBuffer = this.textureUtils.getColorBuffer();
  43816. this.defaultRenderPassdescriptor = null;
  43817. }
  43818. // utils public
  43819. /**
  43820. * Returns the maximum anisotropy texture filtering value.
  43821. *
  43822. * @return {Number} The maximum anisotropy texture filtering value.
  43823. */
  43824. getMaxAnisotropy() {
  43825. return 16;
  43826. }
  43827. /**
  43828. * Checks if the given feature is supported by the backend.
  43829. *
  43830. * @param {String} name - The feature's name.
  43831. * @return {Boolean} Whether the feature is supported or not.
  43832. */
  43833. hasFeature( name ) {
  43834. return this.device.features.has( name );
  43835. }
  43836. /**
  43837. * Copies data of the given source texture to the given destination texture.
  43838. *
  43839. * @param {Texture} srcTexture - The source texture.
  43840. * @param {Texture} dstTexture - The destination texture.
  43841. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  43842. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  43843. * @param {Number} [level=0] - The mip level to copy.
  43844. */
  43845. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  43846. let dstX = 0;
  43847. let dstY = 0;
  43848. let dstLayer = 0;
  43849. let srcX = 0;
  43850. let srcY = 0;
  43851. let srcLayer = 0;
  43852. let srcWidth = srcTexture.image.width;
  43853. let srcHeight = srcTexture.image.height;
  43854. if ( srcRegion !== null ) {
  43855. srcX = srcRegion.x;
  43856. srcY = srcRegion.y;
  43857. srcLayer = srcRegion.z || 0;
  43858. srcWidth = srcRegion.width;
  43859. srcHeight = srcRegion.height;
  43860. }
  43861. if ( dstPosition !== null ) {
  43862. dstX = dstPosition.x;
  43863. dstY = dstPosition.y;
  43864. dstLayer = dstPosition.z || 0;
  43865. }
  43866. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  43867. const sourceGPU = this.get( srcTexture ).texture;
  43868. const destinationGPU = this.get( dstTexture ).texture;
  43869. encoder.copyTextureToTexture(
  43870. {
  43871. texture: sourceGPU,
  43872. mipLevel: level,
  43873. origin: { x: srcX, y: srcY, z: srcLayer }
  43874. },
  43875. {
  43876. texture: destinationGPU,
  43877. mipLevel: level,
  43878. origin: { x: dstX, y: dstY, z: dstLayer }
  43879. },
  43880. [
  43881. srcWidth,
  43882. srcHeight,
  43883. 1
  43884. ]
  43885. );
  43886. this.device.queue.submit( [ encoder.finish() ] );
  43887. }
  43888. /**
  43889. * Copies the current bound framebuffer to the given texture.
  43890. *
  43891. * @param {Texture} texture - The destination texture.
  43892. * @param {RenderContext} renderContext - The render context.
  43893. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  43894. */
  43895. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  43896. const renderContextData = this.get( renderContext );
  43897. let sourceGPU = null;
  43898. if ( renderContext.renderTarget ) {
  43899. if ( texture.isDepthTexture ) {
  43900. sourceGPU = this.get( renderContext.depthTexture ).texture;
  43901. } else {
  43902. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  43903. }
  43904. } else {
  43905. if ( texture.isDepthTexture ) {
  43906. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  43907. } else {
  43908. sourceGPU = this.context.getCurrentTexture();
  43909. }
  43910. }
  43911. const destinationGPU = this.get( texture ).texture;
  43912. if ( sourceGPU.format !== destinationGPU.format ) {
  43913. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  43914. return;
  43915. }
  43916. let encoder;
  43917. if ( renderContextData.currentPass ) {
  43918. renderContextData.currentPass.end();
  43919. encoder = renderContextData.encoder;
  43920. } else {
  43921. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  43922. }
  43923. encoder.copyTextureToTexture(
  43924. {
  43925. texture: sourceGPU,
  43926. origin: [ rectangle.x, rectangle.y, 0 ],
  43927. },
  43928. {
  43929. texture: destinationGPU
  43930. },
  43931. [
  43932. rectangle.z,
  43933. rectangle.w
  43934. ]
  43935. );
  43936. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  43937. if ( renderContextData.currentPass ) {
  43938. const { descriptor } = renderContextData;
  43939. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  43940. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  43941. }
  43942. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  43943. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  43944. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  43945. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  43946. if ( renderContext.viewport ) {
  43947. this.updateViewport( renderContext );
  43948. }
  43949. if ( renderContext.scissor ) {
  43950. const { x, y, width, height } = renderContext.scissorValue;
  43951. renderContextData.currentPass.setScissorRect( x, y, width, height );
  43952. }
  43953. } else {
  43954. this.device.queue.submit( [ encoder.finish() ] );
  43955. }
  43956. }
  43957. }
  43958. class IESSpotLight extends SpotLight {
  43959. constructor( color, intensity, distance, angle, penumbra, decay ) {
  43960. super( color, intensity, distance, angle, penumbra, decay );
  43961. this.iesMap = null;
  43962. }
  43963. copy( source, recursive ) {
  43964. super.copy( source, recursive );
  43965. this.iesMap = source.iesMap;
  43966. return this;
  43967. }
  43968. }
  43969. /**
  43970. * This version of a node library represents the standard version
  43971. * used in {@link WebGPURenderer}. It maps lights, tone mapping
  43972. * techniques and materials to node-based implementations.
  43973. *
  43974. * @private
  43975. * @augments NodeLibrary
  43976. */
  43977. class StandardNodeLibrary extends NodeLibrary {
  43978. /**
  43979. * Constructs a new standard node library.
  43980. */
  43981. constructor() {
  43982. super();
  43983. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  43984. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  43985. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  43986. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  43987. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  43988. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  43989. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  43990. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  43991. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  43992. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  43993. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  43994. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  43995. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  43996. this.addLight( PointLightNode, PointLight );
  43997. this.addLight( DirectionalLightNode, DirectionalLight );
  43998. this.addLight( RectAreaLightNode, RectAreaLight );
  43999. this.addLight( SpotLightNode, SpotLight );
  44000. this.addLight( AmbientLightNode, AmbientLight );
  44001. this.addLight( HemisphereLightNode, HemisphereLight );
  44002. this.addLight( LightProbeNode, LightProbe );
  44003. this.addLight( IESSpotLightNode, IESSpotLight );
  44004. this.addToneMapping( linearToneMapping, LinearToneMapping );
  44005. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  44006. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  44007. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  44008. this.addToneMapping( agxToneMapping, AgXToneMapping );
  44009. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  44010. }
  44011. }
  44012. /*
  44013. const debugHandler = {
  44014. get: function ( target, name ) {
  44015. // Add |update
  44016. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  44017. return target[ name ];
  44018. }
  44019. };
  44020. */
  44021. /**
  44022. * This renderer is the new alternative of `WebGLRenderer`. `WebGPURenderer` has the ability
  44023. * to target different backends. By default, the renderer tries to use a WebGPU backend if the
  44024. * browser supports WebGPU. If not, `WebGPURenderer` falls backs to a WebGL 2 backend.
  44025. *
  44026. * @augments module:Renderer~Renderer
  44027. */
  44028. class WebGPURenderer extends Renderer {
  44029. /**
  44030. * Constructs a new WebGPU renderer.
  44031. *
  44032. * @param {Object} parameters - The configuration parameter.
  44033. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  44034. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  44035. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  44036. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  44037. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  44038. * @param {Number} [parameters.samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0
  44039. * to overwrite the default.
  44040. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses it
  44041. * WebGL 2 backend no matter if WebGPU is supported or not.
  44042. */
  44043. constructor( parameters = {} ) {
  44044. let BackendClass;
  44045. if ( parameters.forceWebGL ) {
  44046. BackendClass = WebGLBackend;
  44047. } else {
  44048. BackendClass = WebGPUBackend;
  44049. parameters.getFallback = () => {
  44050. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  44051. return new WebGLBackend( parameters );
  44052. };
  44053. }
  44054. const backend = new BackendClass( parameters );
  44055. //super( new Proxy( backend, debugHandler ) );
  44056. super( backend, parameters );
  44057. /**
  44058. * The generic default value is overwritten with the
  44059. * standard node library for type mapping.
  44060. *
  44061. * @type {StandardNodeLibrary}
  44062. */
  44063. this.library = new StandardNodeLibrary();
  44064. /**
  44065. * This flag can be used for type testing.
  44066. *
  44067. * @type {Boolean}
  44068. * @readonly
  44069. * @default true
  44070. */
  44071. this.isWebGPURenderer = true;
  44072. }
  44073. }
  44074. /**
  44075. * A specialized group which eanbles applications access to the
  44076. * Render Bundle API of WebGPU. The group with all its descendant nodes
  44077. * are considered as one render bundle and processed as such by
  44078. * the renderer.
  44079. *
  44080. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  44081. * With a WebGL backend, the group can technically be rendered but without
  44082. * any performance improvements.
  44083. *
  44084. * @augments Group
  44085. */
  44086. class BundleGroup extends Group {
  44087. /**
  44088. * Constructs a new bundle group.
  44089. */
  44090. constructor() {
  44091. super();
  44092. /**
  44093. * This flag can be used for type testing.
  44094. *
  44095. * @type {Boolean}
  44096. * @readonly
  44097. * @default true
  44098. */
  44099. this.isBundleGroup = true;
  44100. /**
  44101. * This property is only relevant for detecting types
  44102. * during serialization/deserialization. It should always
  44103. * match the class name.
  44104. *
  44105. * @type {String}
  44106. * @readonly
  44107. * @default 'BundleGroup'
  44108. */
  44109. this.type = 'BundleGroup';
  44110. /**
  44111. * Whether the bundle is static or not. When set to `true`, the structure
  44112. * is assumed to be static and does not change. E.g. no new objects are
  44113. * added to the group
  44114. *
  44115. * If a change is required, an update can still be forced by setting the
  44116. * `needsUpdate` flag to `true`.
  44117. *
  44118. * @type {Boolean}
  44119. * @default true
  44120. */
  44121. this.static = true;
  44122. /**
  44123. * The bundle group's version.
  44124. *
  44125. * @type {Number}
  44126. * @readonly
  44127. * @default 0
  44128. */
  44129. this.version = 0;
  44130. }
  44131. /**
  44132. * Set this property to `true` when the bundle group has changed.
  44133. *
  44134. * @type {Boolean}
  44135. * @default false
  44136. * @param {Boolean} value
  44137. */
  44138. set needsUpdate( value ) {
  44139. if ( value === true ) this.version ++;
  44140. }
  44141. }
  44142. const _material = /*@__PURE__*/ new NodeMaterial();
  44143. const _quadMesh = /*@__PURE__*/ new QuadMesh( _material );
  44144. /**
  44145. * This module is responsible to manage the post processing setups in apps.
  44146. * You usually create a single instance of this class and use it to define
  44147. * the output of your post processing effect chain.
  44148. * ```js
  44149. * const postProcessing = new PostProcessing( renderer );
  44150. *
  44151. * const scenePass = pass( scene, camera );
  44152. *
  44153. * postProcessing.outputNode = scenePass;
  44154. * ```
  44155. */
  44156. class PostProcessing {
  44157. /**
  44158. * Constructs a new post processing management module.
  44159. *
  44160. * @param {Renderer} renderer - A reference to the renderer.
  44161. * @param {Node<vec4>} outputNode - An optional output node.
  44162. */
  44163. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  44164. /**
  44165. * A reference to the renderer.
  44166. *
  44167. * @type {Renderer}
  44168. */
  44169. this.renderer = renderer;
  44170. /**
  44171. * A node which defines the final output of the post
  44172. * processing. This is usually the last node in a chain
  44173. * of effect nodes.
  44174. *
  44175. * @type {Node<vec4>}
  44176. */
  44177. this.outputNode = outputNode;
  44178. /**
  44179. * Whether the default output tone mapping and color
  44180. * space transformation should be enabled or not.
  44181. *
  44182. * It is enabled by default by it must be disabled when
  44183. * effects must be executed after tone mapping and color
  44184. * space conversion. A typical example is FXAA which
  44185. * requires sRGB input.
  44186. *
  44187. * When set to `false`, the app must control the output
  44188. * transformation with `RenderOutputNode`.
  44189. *
  44190. * ```js
  44191. * const outputPass = renderOutput( scenePass );
  44192. * ```
  44193. *
  44194. * @type {Boolean}
  44195. */
  44196. this.outputColorTransform = true;
  44197. /**
  44198. * Must be set to `true` when the output node changes.
  44199. *
  44200. * @type {Node<vec4>}
  44201. */
  44202. this.needsUpdate = true;
  44203. _material.name = 'PostProcessing';
  44204. }
  44205. /**
  44206. * When `PostProcessing` is used to apply post processing effects,
  44207. * the application must use this version of `render()` inside
  44208. * its animation loop (not the one from the renderer).
  44209. */
  44210. render() {
  44211. this._update();
  44212. const renderer = this.renderer;
  44213. const toneMapping = renderer.toneMapping;
  44214. const outputColorSpace = renderer.outputColorSpace;
  44215. renderer.toneMapping = NoToneMapping;
  44216. renderer.outputColorSpace = LinearSRGBColorSpace;
  44217. //
  44218. _quadMesh.render( renderer );
  44219. //
  44220. renderer.toneMapping = toneMapping;
  44221. renderer.outputColorSpace = outputColorSpace;
  44222. }
  44223. /**
  44224. * Updates the state of the module.
  44225. *
  44226. * @private
  44227. */
  44228. _update() {
  44229. if ( this.needsUpdate === true ) {
  44230. const renderer = this.renderer;
  44231. const toneMapping = renderer.toneMapping;
  44232. const outputColorSpace = renderer.outputColorSpace;
  44233. _quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  44234. _quadMesh.material.needsUpdate = true;
  44235. this.needsUpdate = false;
  44236. }
  44237. }
  44238. /**
  44239. * When `PostProcessing` is used to apply post processing effects,
  44240. * the application must use this version of `renderAsync()` inside
  44241. * its animation loop (not the one from the renderer).
  44242. *
  44243. * @async
  44244. * @return {Promise} A Promise that resolves when the render has been finished.
  44245. */
  44246. async renderAsync() {
  44247. this._update();
  44248. const renderer = this.renderer;
  44249. const toneMapping = renderer.toneMapping;
  44250. const outputColorSpace = renderer.outputColorSpace;
  44251. renderer.toneMapping = NoToneMapping;
  44252. renderer.outputColorSpace = LinearSRGBColorSpace;
  44253. //
  44254. await _quadMesh.renderAsync( renderer );
  44255. //
  44256. renderer.toneMapping = toneMapping;
  44257. renderer.outputColorSpace = outputColorSpace;
  44258. }
  44259. }
  44260. /**
  44261. * This special type of texture is intended for compute shaders.
  44262. * It can be used to compute the data of a texture with a compute shader.
  44263. *
  44264. * Note: This type of texture can only be used with `WebGPURenderer`
  44265. * and a WebGPU backend.
  44266. *
  44267. * @augments Texture
  44268. */
  44269. class StorageTexture extends Texture {
  44270. /**
  44271. * Constructs a new storage texture.
  44272. *
  44273. * @param {Number} [width=1] - The storage texture's width.
  44274. * @param {Number} [height=1] - The storage texture's height.
  44275. */
  44276. constructor( width = 1, height = 1 ) {
  44277. super();
  44278. /**
  44279. * The image object which just represents the texture's dimension.
  44280. *
  44281. * @type {{width: Number, height:Number}}
  44282. */
  44283. this.image = { width, height };
  44284. /**
  44285. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  44286. *
  44287. * @type {Number}
  44288. */
  44289. this.magFilter = LinearFilter;
  44290. /**
  44291. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  44292. *
  44293. * @type {Number}
  44294. */
  44295. this.minFilter = LinearFilter;
  44296. /**
  44297. * This flag can be used for type testing.
  44298. *
  44299. * @type {Boolean}
  44300. * @readonly
  44301. * @default true
  44302. */
  44303. this.isStorageTexture = true;
  44304. }
  44305. }
  44306. /**
  44307. * This special type of buffer attribute is intended for compute shaders.
  44308. * It can be used to encode draw parameters for indirect draw calls.
  44309. *
  44310. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  44311. * and a WebGPU backend.
  44312. *
  44313. * @augments StorageBufferAttribute
  44314. */
  44315. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  44316. /**
  44317. * Constructs a new storage buffer attribute.
  44318. *
  44319. * @param {Number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  44320. * The subsequent parameter is then obsolete.
  44321. * @param {Number} itemSize - The item size.
  44322. */
  44323. constructor( count, itemSize ) {
  44324. super( count, itemSize, Uint32Array );
  44325. /**
  44326. * This flag can be used for type testing.
  44327. *
  44328. * @type {Boolean}
  44329. * @readonly
  44330. * @default true
  44331. */
  44332. this.isIndirectStorageBufferAttribute = true;
  44333. }
  44334. }
  44335. /**
  44336. * A loader for loading node objects in the three.js JSON Object/Scene format.
  44337. *
  44338. * @augments Loader
  44339. */
  44340. class NodeLoader extends Loader {
  44341. /**
  44342. * Constructs a new node loader.
  44343. *
  44344. * @param {LoadingManager?} manager - A reference to a loading manager.
  44345. */
  44346. constructor( manager ) {
  44347. super( manager );
  44348. /**
  44349. * Represents a dictionary of textures.
  44350. *
  44351. * @type {Object<String,Texture>}
  44352. */
  44353. this.textures = {};
  44354. /**
  44355. * Represents a dictionary of node types.
  44356. *
  44357. * @type {Object<String,Node.constructor>}
  44358. */
  44359. this.nodes = {};
  44360. }
  44361. /**
  44362. * Loads the node definitions from the given URL.
  44363. *
  44364. * @param {String} url - The path/URL of the file to be loaded.
  44365. * @param {Function} onLoad - Will be called when load completes.
  44366. * @param {Function} onProgress - Will be called while load progresses.
  44367. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  44368. */
  44369. load( url, onLoad, onProgress, onError ) {
  44370. const loader = new FileLoader( this.manager );
  44371. loader.setPath( this.path );
  44372. loader.setRequestHeader( this.requestHeader );
  44373. loader.setWithCredentials( this.withCredentials );
  44374. loader.load( url, ( text ) => {
  44375. try {
  44376. onLoad( this.parse( JSON.parse( text ) ) );
  44377. } catch ( e ) {
  44378. if ( onError ) {
  44379. onError( e );
  44380. } else {
  44381. console.error( e );
  44382. }
  44383. this.manager.itemError( url );
  44384. }
  44385. }, onProgress, onError );
  44386. }
  44387. /**
  44388. * Parse the node dependencies for the loaded node.
  44389. *
  44390. * @param {Object} json - The JSON definition
  44391. * @return {Object<String,Node>} A dictionary with node dependencies.
  44392. */
  44393. parseNodes( json ) {
  44394. const nodes = {};
  44395. if ( json !== undefined ) {
  44396. for ( const nodeJSON of json ) {
  44397. const { uuid, type } = nodeJSON;
  44398. nodes[ uuid ] = this.createNodeFromType( type );
  44399. nodes[ uuid ].uuid = uuid;
  44400. }
  44401. const meta = { nodes, textures: this.textures };
  44402. for ( const nodeJSON of json ) {
  44403. nodeJSON.meta = meta;
  44404. const node = nodes[ nodeJSON.uuid ];
  44405. node.deserialize( nodeJSON );
  44406. delete nodeJSON.meta;
  44407. }
  44408. }
  44409. return nodes;
  44410. }
  44411. /**
  44412. * Parses the node from the given JSON.
  44413. *
  44414. * @param {Object} json - The JSON definition
  44415. * @return {Node} The parsed node.
  44416. */
  44417. parse( json ) {
  44418. const node = this.createNodeFromType( json.type );
  44419. node.uuid = json.uuid;
  44420. const nodes = this.parseNodes( json.nodes );
  44421. const meta = { nodes, textures: this.textures };
  44422. json.meta = meta;
  44423. node.deserialize( json );
  44424. delete json.meta;
  44425. return node;
  44426. }
  44427. /**
  44428. * Defines the dictionary of textures.
  44429. *
  44430. * @param {Object<String,Texture>} value - The texture library defines as `<uuid,texture>`.
  44431. * @return {NodeLoader} A reference to this loader.
  44432. */
  44433. setTextures( value ) {
  44434. this.textures = value;
  44435. return this;
  44436. }
  44437. /**
  44438. * Defines the dictionary of node types.
  44439. *
  44440. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  44441. * @return {NodeLoader} A reference to this loader.
  44442. */
  44443. setNodes( value ) {
  44444. this.nodes = value;
  44445. return this;
  44446. }
  44447. /**
  44448. * Creates a node object from the given type.
  44449. *
  44450. * @param {String} type - The node type.
  44451. * @return {Node} The created node instance.
  44452. */
  44453. createNodeFromType( type ) {
  44454. if ( this.nodes[ type ] === undefined ) {
  44455. console.error( 'THREE.NodeLoader: Node type not found:', type );
  44456. return float();
  44457. }
  44458. return nodeObject( new this.nodes[ type ]() );
  44459. }
  44460. }
  44461. /**
  44462. * A special type of material loader for loading node materials.
  44463. *
  44464. * @augments MaterialLoader
  44465. */
  44466. class NodeMaterialLoader extends MaterialLoader {
  44467. /**
  44468. * Constructs a new node material loader.
  44469. *
  44470. * @param {LoadingManager?} manager - A reference to a loading manager.
  44471. */
  44472. constructor( manager ) {
  44473. super( manager );
  44474. /**
  44475. * Represents a dictionary of node types.
  44476. *
  44477. * @type {Object<String,Node.constructor>}
  44478. */
  44479. this.nodes = {};
  44480. /**
  44481. * Represents a dictionary of node material types.
  44482. *
  44483. * @type {Object<String,NodeMaterial.constructor>}
  44484. */
  44485. this.nodeMaterials = {};
  44486. }
  44487. /**
  44488. * Parses the node material from the given JSON.
  44489. *
  44490. * @param {Object} json - The JSON definition
  44491. * @return {NodeMaterial}. The parsed material.
  44492. */
  44493. parse( json ) {
  44494. const material = super.parse( json );
  44495. const nodes = this.nodes;
  44496. const inputNodes = json.inputNodes;
  44497. for ( const property in inputNodes ) {
  44498. const uuid = inputNodes[ property ];
  44499. material[ property ] = nodes[ uuid ];
  44500. }
  44501. return material;
  44502. }
  44503. /**
  44504. * Defines the dictionary of node types.
  44505. *
  44506. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  44507. * @return {NodeLoader} A reference to this loader.
  44508. */
  44509. setNodes( value ) {
  44510. this.nodes = value;
  44511. return this;
  44512. }
  44513. /**
  44514. * Defines the dictionary of node material types.
  44515. *
  44516. * @param {Object<String,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  44517. * @return {NodeLoader} A reference to this loader.
  44518. */
  44519. setNodeMaterials( value ) {
  44520. this.nodeMaterials = value;
  44521. return this;
  44522. }
  44523. /**
  44524. * Creates a node material from the given type.
  44525. *
  44526. * @param {String} type - The node material type.
  44527. * @return {Node} The created node material instance.
  44528. */
  44529. createMaterialFromType( type ) {
  44530. const materialClass = this.nodeMaterials[ type ];
  44531. if ( materialClass !== undefined ) {
  44532. return new materialClass();
  44533. }
  44534. return super.createMaterialFromType( type );
  44535. }
  44536. }
  44537. /**
  44538. * A special type of object loader for loading 3D objects using
  44539. * node materials.
  44540. *
  44541. * @augments ObjectLoader
  44542. */
  44543. class NodeObjectLoader extends ObjectLoader {
  44544. /**
  44545. * Constructs a new node object loader.
  44546. *
  44547. * @param {LoadingManager?} manager - A reference to a loading manager.
  44548. */
  44549. constructor( manager ) {
  44550. super( manager );
  44551. /**
  44552. * Represents a dictionary of node types.
  44553. *
  44554. * @type {Object<String,Node.constructor>}
  44555. */
  44556. this.nodes = {};
  44557. /**
  44558. * Represents a dictionary of node material types.
  44559. *
  44560. * @type {Object<String,NodeMaterial.constructor>}
  44561. */
  44562. this.nodeMaterials = {};
  44563. /**
  44564. * A reference for holdng the `nodes` JSON property.
  44565. *
  44566. * @private
  44567. * @type {Object?}
  44568. */
  44569. this._nodesJSON = null;
  44570. }
  44571. /**
  44572. * Defines the dictionary of node types.
  44573. *
  44574. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  44575. * @return {NodeLoader} A reference to this loader.
  44576. */
  44577. setNodes( value ) {
  44578. this.nodes = value;
  44579. return this;
  44580. }
  44581. /**
  44582. * Defines the dictionary of node material types.
  44583. *
  44584. * @param {Object<String,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  44585. * @return {NodeLoader} A reference to this loader.
  44586. */
  44587. setNodeMaterials( value ) {
  44588. this.nodeMaterials = value;
  44589. return this;
  44590. }
  44591. /**
  44592. * Parses the node objects from the given JSON.
  44593. *
  44594. * @param {Object} json - The JSON definition
  44595. * @param {Function} onLoad - The onLoad callback function.
  44596. * @return {Object3D}. The parsed 3D object.
  44597. */
  44598. parse( json, onLoad ) {
  44599. this._nodesJSON = json.nodes;
  44600. const data = super.parse( json, onLoad );
  44601. this._nodesJSON = null; // dispose
  44602. return data;
  44603. }
  44604. /**
  44605. * Parses the node objects from the given JSON and textures.
  44606. *
  44607. * @param {Object} json - The JSON definition
  44608. * @param {Object<String,Texture>} textures - The texture library.
  44609. * @return {Object<String,Node>}. The parsed nodes.
  44610. */
  44611. parseNodes( json, textures ) {
  44612. if ( json !== undefined ) {
  44613. const loader = new NodeLoader();
  44614. loader.setNodes( this.nodes );
  44615. loader.setTextures( textures );
  44616. return loader.parseNodes( json );
  44617. }
  44618. return {};
  44619. }
  44620. /**
  44621. * Parses the node objects from the given JSON and textures.
  44622. *
  44623. * @param {Object} json - The JSON definition
  44624. * @param {Object<String,Texture>} textures - The texture library.
  44625. * @return {Object<String,NodeMaterial>}. The parsed materials.
  44626. */
  44627. parseMaterials( json, textures ) {
  44628. const materials = {};
  44629. if ( json !== undefined ) {
  44630. const nodes = this.parseNodes( this._nodesJSON, textures );
  44631. const loader = new NodeMaterialLoader();
  44632. loader.setTextures( textures );
  44633. loader.setNodes( nodes );
  44634. loader.setNodeMaterials( this.nodeMaterials );
  44635. for ( let i = 0, l = json.length; i < l; i ++ ) {
  44636. const data = json[ i ];
  44637. materials[ data.uuid ] = loader.parse( data );
  44638. }
  44639. }
  44640. return materials;
  44641. }
  44642. }
  44643. /**
  44644. * In earlier three.js versions, clipping was defined globally
  44645. * on the renderer or on material level. This special version of
  44646. * `THREE.Group` allows to encode the clipping state into the scene
  44647. * graph. Meaning if you create an instance of this group, all
  44648. * descendant 3D objects will be affected by the respective clipping
  44649. * planes.
  44650. *
  44651. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  44652. *
  44653. * @augments Group
  44654. */
  44655. class ClippingGroup extends Group {
  44656. /**
  44657. * Constructs a new clipping group.
  44658. */
  44659. constructor() {
  44660. super();
  44661. /**
  44662. * This flag can be used for type testing.
  44663. *
  44664. * @type {Boolean}
  44665. * @readonly
  44666. * @default true
  44667. */
  44668. this.isClippingGroup = true;
  44669. /**
  44670. * An array with clipping planes.
  44671. *
  44672. * @type {Array<Plane>}
  44673. */
  44674. this.clippingPlanes = [];
  44675. /**
  44676. * Whether clipping should be enabled or not.
  44677. *
  44678. * @type {Boolean}
  44679. * @default true
  44680. */
  44681. this.enabled = true;
  44682. /**
  44683. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  44684. *
  44685. * @type {Boolean}
  44686. * @default false
  44687. */
  44688. this.clipIntersection = false;
  44689. /**
  44690. * Whether shadows should be clipped or not.
  44691. *
  44692. * @type {Boolean}
  44693. * @default false
  44694. */
  44695. this.clipShadows = false;
  44696. }
  44697. }
  44698. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayElementNode, AssignNode, AttributeNode, BackSide, BasicEnvironmentNode, BasicShadowMap, BatchNode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, CacheNode, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, CodeNode, Color, ColorManagement, ColorSpaceNode, ComputeNode, ConstNode, ContextNode, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, DataArrayTexture, DataTexture, DecrementStencilOp, DecrementWrapStencilOp, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, Group, HalfFloatType, HemisphereLight, HemisphereLightNode, IESSpotLight, IESSpotLightNode, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InstanceNode, InstancedBufferAttribute, InstancedInterleavedBuffer, InstancedMeshNode, InstancedPointsNodeMaterial, IntType, InterleavedBuffer, InterleavedBufferAttribute, InvertStencilOp, IrradianceNode, JoinNode, KeepStencilOp, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, LightProbe, LightProbeNode, Lighting, LightingContextNode, LightingModel, LightingNode, LightsNode, Line2NodeMaterial, LineBasicMaterial, LineBasicNodeMaterial, LineDashedMaterial, LineDashedNodeMaterial, LinearFilter, LinearMipMapLinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, Loader, LoopNode, LuminanceAlphaFormat, LuminanceFormat, MRTNode, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAccess, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap, PMREMGenerator, PMREMNode, ParameterNode, PassNode, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PointLight, PointLightNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, 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, RendererUtils, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShadowBaseNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, ShortType, SkinningNode, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticDrawUsage, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TriplanarTexturesNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, shaderStages, vectorComponents };
粤ICP备19079148号