three.webgpu.js 1.5 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756
  1. /**
  2. * @license
  3. * Copyright 2010-2025 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, Camera, 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, 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. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  7222. return builder.context.setupNormal().context( { getUV: null } );
  7223. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  7224. /**
  7225. * TSL object that represents the transformed vertex normal in world space of the current rendered object.
  7226. *
  7227. * @type {Node<vec3>}
  7228. */
  7229. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  7230. /**
  7231. * TSL object that represents the transformed clearcoat vertex normal in view space of the current rendered object.
  7232. *
  7233. * @type {Node<vec3>}
  7234. */
  7235. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7236. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  7237. return builder.context.setupClearcoatNormal().context( { getUV: null } );
  7238. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  7239. /**
  7240. * Transforms the normal with the given matrix.
  7241. *
  7242. * @function
  7243. * @param {Node<vec3>} normal - The normal.
  7244. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  7245. * @return {Node<vec3>} The transformed normal.
  7246. */
  7247. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  7248. const m = mat3( matrix );
  7249. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  7250. return m.mul( transformedNormal ).xyz;
  7251. } );
  7252. /**
  7253. * Transforms the given normal from local to view space.
  7254. *
  7255. * @function
  7256. * @param {Node<vec3>} normal - The normal.
  7257. * @param {NodeBuilder} builder - The current node builder.
  7258. * @return {Node<vec3>} The transformed normal.
  7259. */
  7260. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  7261. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  7262. if ( modelNormalViewMatrix !== null ) {
  7263. return modelNormalViewMatrix.transformDirection( normal );
  7264. }
  7265. //
  7266. const transformedNormal = modelNormalMatrix.mul( normal );
  7267. return cameraViewMatrix.transformDirection( transformedNormal );
  7268. } );
  7269. /** @module MaterialProperties **/
  7270. /**
  7271. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  7272. *
  7273. * @type {UniformNode<float>}
  7274. */
  7275. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  7276. /** @module ReflectVector **/
  7277. /**
  7278. * The reflect vector in view space.
  7279. *
  7280. * @type {Node<vec3>}
  7281. */
  7282. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  7283. /**
  7284. * The refract vector in view space.
  7285. *
  7286. * @type {Node<vec3>}
  7287. */
  7288. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  7289. /**
  7290. * Used for sampling cube maps when using cube reflection mapping.
  7291. *
  7292. * @type {Node<vec3>}
  7293. */
  7294. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  7295. /**
  7296. * Used for sampling cube maps when using cube refraction mapping.
  7297. *
  7298. * @type {Node<vec3>}
  7299. */
  7300. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  7301. /** @module CubeTextureNode **/
  7302. /**
  7303. * This type of uniform node represents a cube texture.
  7304. *
  7305. * @augments module:TextureNode~TextureNode
  7306. */
  7307. class CubeTextureNode extends TextureNode {
  7308. static get type() {
  7309. return 'CubeTextureNode';
  7310. }
  7311. /**
  7312. * Constructs a new cube texture node.
  7313. *
  7314. * @param {CubeTexture} value - The cube texture.
  7315. * @param {Node<vec3>?} [uvNode=null] - The uv node.
  7316. * @param {Node<int>?} [levelNode=null] - The level node.
  7317. * @param {Node<float>?} [biasNode=null] - The bias node.
  7318. */
  7319. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  7320. super( value, uvNode, levelNode, biasNode );
  7321. /**
  7322. * This flag can be used for type testing.
  7323. *
  7324. * @type {Boolean}
  7325. * @readonly
  7326. * @default true
  7327. */
  7328. this.isCubeTextureNode = true;
  7329. }
  7330. /**
  7331. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  7332. *
  7333. * @param {NodeBuilder} builder - The current node builder.
  7334. * @return {String} The input type.
  7335. */
  7336. getInputType( /*builder*/ ) {
  7337. return 'cubeTexture';
  7338. }
  7339. /**
  7340. * Returns a default uvs based on the mapping type of the cube texture.
  7341. *
  7342. * @return {Node<vec3>} The default uv attribute.
  7343. */
  7344. getDefaultUV() {
  7345. const texture = this.value;
  7346. if ( texture.mapping === CubeReflectionMapping ) {
  7347. return reflectVector;
  7348. } else if ( texture.mapping === CubeRefractionMapping ) {
  7349. return refractVector;
  7350. } else {
  7351. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  7352. return vec3( 0, 0, 0 );
  7353. }
  7354. }
  7355. /**
  7356. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  7357. * for cube textures. The uv transformation matrix is not applied to cube textures.
  7358. *
  7359. * @param {Boolean} value - The update toggle.
  7360. */
  7361. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  7362. /**
  7363. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  7364. * to modify the uv node for correct sampling.
  7365. *
  7366. * @param {NodeBuilder} builder - The current node builder.
  7367. * @param {Node} uvNode - The uv node to setup.
  7368. * @return {Node} The updated uv node.
  7369. */
  7370. setupUV( builder, uvNode ) {
  7371. const texture = this.value;
  7372. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  7373. return vec3( uvNode.x.negate(), uvNode.yz );
  7374. } else {
  7375. return uvNode;
  7376. }
  7377. }
  7378. /**
  7379. * Generates the uv code snippet.
  7380. *
  7381. * @param {NodeBuilder} builder - The current node builder.
  7382. * @param {Node} cubeUV - The uv node to generate code for.
  7383. * @return {String} The generated code snippet.
  7384. */
  7385. generateUV( builder, cubeUV ) {
  7386. return cubeUV.build( builder, 'vec3' );
  7387. }
  7388. }
  7389. /**
  7390. * TSL function for creating a cube texture node.
  7391. *
  7392. * @function
  7393. * @param {CubeTexture} value - The cube texture.
  7394. * @param {Node<vec3>?} [uvNode=null] - The uv node.
  7395. * @param {Node<int>?} [levelNode=null] - The level node.
  7396. * @param {Node<float>?} [biasNode=null] - The bias node.
  7397. * @returns {CubeTextureNode}
  7398. */
  7399. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  7400. /** @module BufferNode **/
  7401. /**
  7402. * A special type of uniform node which represents array-like data
  7403. * as uniform buffers. The access usually happens via `element()`
  7404. * which returns an instance of {@link ArrayElementNode}. For example:
  7405. *
  7406. * ```js
  7407. * const bufferNode = buffer( array, 'mat4', count );
  7408. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  7409. * ```
  7410. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  7411. * since it handles more input types and automatically cares about buffer paddings.
  7412. *
  7413. * @augments module:UniformNode~UniformNode
  7414. */
  7415. class BufferNode extends UniformNode {
  7416. static get type() {
  7417. return 'BufferNode';
  7418. }
  7419. /**
  7420. * Constructs a new buffer node.
  7421. *
  7422. * @param {Array<Number>} value - Array-like buffer data.
  7423. * @param {String} bufferType - The data type of the buffer.
  7424. * @param {Number} [bufferCount=0] - The count of buffer elements.
  7425. */
  7426. constructor( value, bufferType, bufferCount = 0 ) {
  7427. super( value, bufferType );
  7428. /**
  7429. * This flag can be used for type testing.
  7430. *
  7431. * @type {Boolean}
  7432. * @readonly
  7433. * @default true
  7434. */
  7435. this.isBufferNode = true;
  7436. /**
  7437. * The data type of the buffer.
  7438. *
  7439. * @type {String}
  7440. */
  7441. this.bufferType = bufferType;
  7442. /**
  7443. * The uniform node that holds the value of the reference node.
  7444. *
  7445. * @type {Number}
  7446. * @default 0
  7447. */
  7448. this.bufferCount = bufferCount;
  7449. }
  7450. /**
  7451. * The data type of the buffer elements.
  7452. *
  7453. * @param {NodeBuilder} builder - The current node builder.
  7454. * @return {String} The element type.
  7455. */
  7456. getElementType( builder ) {
  7457. return this.getNodeType( builder );
  7458. }
  7459. /**
  7460. * Overwrites the default implementation to return a fixed value `'buffer'`.
  7461. *
  7462. * @param {NodeBuilder} builder - The current node builder.
  7463. * @return {String} The input type.
  7464. */
  7465. getInputType( /*builder*/ ) {
  7466. return 'buffer';
  7467. }
  7468. }
  7469. /**
  7470. * TSL function for creating a buffer node.
  7471. *
  7472. * @function
  7473. * @param {Array} value - Array-like buffer data.
  7474. * @param {String} type - The data type of a buffer element.
  7475. * @param {Number} count - The count of buffer elements.
  7476. * @returns {BufferNode}
  7477. */
  7478. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  7479. /** @module UniformArrayNode **/
  7480. /**
  7481. * Represents the element access on uniform array nodes.
  7482. *
  7483. * @augments ArrayElementNode
  7484. */
  7485. class UniformArrayElementNode extends ArrayElementNode {
  7486. static get type() {
  7487. return 'UniformArrayElementNode';
  7488. }
  7489. /**
  7490. * Constructs a new buffer node.
  7491. *
  7492. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  7493. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  7494. */
  7495. constructor( uniformArrayNode, indexNode ) {
  7496. super( uniformArrayNode, indexNode );
  7497. /**
  7498. * This flag can be used for type testing.
  7499. *
  7500. * @type {Boolean}
  7501. * @readonly
  7502. * @default true
  7503. */
  7504. this.isArrayBufferElementNode = true;
  7505. }
  7506. generate( builder ) {
  7507. const snippet = super.generate( builder );
  7508. const type = this.getNodeType();
  7509. const paddedType = this.node.getPaddedType();
  7510. return builder.format( snippet, paddedType, type );
  7511. }
  7512. }
  7513. /**
  7514. * Similar to {@link module:BufferNode~BufferNode} this module represents array-like data as
  7515. * uniform buffers. Unlike {@link module:BufferNode~BufferNode}, it can handle more common
  7516. * data types in the array (e.g `three.js` primitives) and automatically
  7517. * manage buffer padding. It should be the first choice when working with
  7518. * uniforms buffers.
  7519. * ```js
  7520. * const tintColors = uniformArray( [
  7521. * new Color( 1, 0, 0 ),
  7522. * new Color( 0, 1, 0 ),
  7523. * new Color( 0, 0, 1 )
  7524. * ], 'color' );
  7525. *
  7526. * const redColor = tintColors.element( 0 );
  7527. *
  7528. * @augments module:BufferNode~BufferNode
  7529. */
  7530. class UniformArrayNode extends BufferNode {
  7531. static get type() {
  7532. return 'UniformArrayNode';
  7533. }
  7534. /**
  7535. * Constructs a new uniform array node.
  7536. *
  7537. * @param {Array<Any>} value - Array holding the buffer data.
  7538. * @param {String?} [elementType=null] - The data type of a buffer element.
  7539. */
  7540. constructor( value, elementType = null ) {
  7541. super( null );
  7542. /**
  7543. * Array holding the buffer data. Unlike {@link module:BufferNode~BufferNode}, the array can
  7544. * hold number primitives as well as three.js objects like vectors, matrices
  7545. * or colors.
  7546. *
  7547. * @type {Array<Any>}
  7548. */
  7549. this.array = value;
  7550. /**
  7551. * The data type of an array element.
  7552. *
  7553. * @type {String}
  7554. */
  7555. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  7556. /**
  7557. * The padded type. Uniform buffers must conform to a certain buffer layout
  7558. * so a separate type is computed to ensure correct buffer size.
  7559. *
  7560. * @type {String}
  7561. */
  7562. this.paddedType = this.getPaddedType();
  7563. /**
  7564. * Overwritten since uniform array nodes are updated per render.
  7565. *
  7566. * @type {String}
  7567. * @default 'render'
  7568. */
  7569. this.updateType = NodeUpdateType.RENDER;
  7570. /**
  7571. * This flag can be used for type testing.
  7572. *
  7573. * @type {Boolean}
  7574. * @readonly
  7575. * @default true
  7576. */
  7577. this.isArrayBufferNode = true;
  7578. }
  7579. /**
  7580. * This method is overwritten since the node type is inferred from the
  7581. * {@link module:UniformArrayNode~UniformArrayNode#paddedType}.
  7582. *
  7583. * @param {NodeBuilder} builder - The current node builder.
  7584. * @return {String} The node type.
  7585. */
  7586. getNodeType( /*builder*/ ) {
  7587. return this.paddedType;
  7588. }
  7589. /**
  7590. * The data type of the array elements.
  7591. *
  7592. * @param {NodeBuilder} builder - The current node builder.
  7593. * @return {String} The element type.
  7594. */
  7595. getElementType() {
  7596. return this.elementType;
  7597. }
  7598. /**
  7599. * Returns the padded type based on the element type.
  7600. *
  7601. * @return {String} The padded type.
  7602. */
  7603. getPaddedType() {
  7604. const elementType = this.elementType;
  7605. let paddedType = 'vec4';
  7606. if ( elementType === 'mat2' ) {
  7607. paddedType = 'mat2';
  7608. } else if ( /mat/.test( elementType ) === true ) {
  7609. paddedType = 'mat4';
  7610. } else if ( elementType.charAt( 0 ) === 'i' ) {
  7611. paddedType = 'ivec4';
  7612. } else if ( elementType.charAt( 0 ) === 'u' ) {
  7613. paddedType = 'uvec4';
  7614. }
  7615. return paddedType;
  7616. }
  7617. /**
  7618. * The update makes sure to correctly transfer the data from the (complex) objects
  7619. * in the array to the internal, correctly padded value buffer.
  7620. *
  7621. * @param {NodeFrame} frame - A reference to the current node frame.
  7622. */
  7623. update( /*frame*/ ) {
  7624. const { array, value } = this;
  7625. const elementType = this.elementType;
  7626. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  7627. for ( let i = 0; i < array.length; i ++ ) {
  7628. const index = i * 4;
  7629. value[ index ] = array[ i ];
  7630. }
  7631. } else if ( elementType === 'color' ) {
  7632. for ( let i = 0; i < array.length; i ++ ) {
  7633. const index = i * 4;
  7634. const vector = array[ i ];
  7635. value[ index ] = vector.r;
  7636. value[ index + 1 ] = vector.g;
  7637. value[ index + 2 ] = vector.b || 0;
  7638. //value[ index + 3 ] = vector.a || 0;
  7639. }
  7640. } else if ( elementType === 'mat2' ) {
  7641. for ( let i = 0; i < array.length; i ++ ) {
  7642. const index = i * 4;
  7643. const matrix = array[ i ];
  7644. value[ index ] = matrix.elements[ 0 ];
  7645. value[ index + 1 ] = matrix.elements[ 1 ];
  7646. value[ index + 2 ] = matrix.elements[ 2 ];
  7647. value[ index + 3 ] = matrix.elements[ 3 ];
  7648. }
  7649. } else if ( elementType === 'mat3' ) {
  7650. for ( let i = 0; i < array.length; i ++ ) {
  7651. const index = i * 16;
  7652. const matrix = array[ i ];
  7653. value[ index ] = matrix.elements[ 0 ];
  7654. value[ index + 1 ] = matrix.elements[ 1 ];
  7655. value[ index + 2 ] = matrix.elements[ 2 ];
  7656. value[ index + 4 ] = matrix.elements[ 3 ];
  7657. value[ index + 5 ] = matrix.elements[ 4 ];
  7658. value[ index + 6 ] = matrix.elements[ 5 ];
  7659. value[ index + 8 ] = matrix.elements[ 6 ];
  7660. value[ index + 9 ] = matrix.elements[ 7 ];
  7661. value[ index + 10 ] = matrix.elements[ 8 ];
  7662. value[ index + 15 ] = 1;
  7663. }
  7664. } else if ( elementType === 'mat4' ) {
  7665. for ( let i = 0; i < array.length; i ++ ) {
  7666. const index = i * 16;
  7667. const matrix = array[ i ];
  7668. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  7669. value[ index + i ] = matrix.elements[ i ];
  7670. }
  7671. }
  7672. } else {
  7673. for ( let i = 0; i < array.length; i ++ ) {
  7674. const index = i * 4;
  7675. const vector = array[ i ];
  7676. value[ index ] = vector.x;
  7677. value[ index + 1 ] = vector.y;
  7678. value[ index + 2 ] = vector.z || 0;
  7679. value[ index + 3 ] = vector.w || 0;
  7680. }
  7681. }
  7682. }
  7683. /**
  7684. * Implement the value buffer creation based on the array data.
  7685. *
  7686. * @param {NodeBuilder} builder - A reference to the current node builder.
  7687. * @return {null}
  7688. */
  7689. setup( builder ) {
  7690. const length = this.array.length;
  7691. const elementType = this.elementType;
  7692. let arrayType = Float32Array;
  7693. const paddedType = this.paddedType;
  7694. const paddedElementLength = builder.getTypeLength( paddedType );
  7695. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  7696. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  7697. this.value = new arrayType( length * paddedElementLength );
  7698. this.bufferCount = length;
  7699. this.bufferType = paddedType;
  7700. return super.setup( builder );
  7701. }
  7702. /**
  7703. * Overwrites the default `element()` method to provide element access
  7704. * based on {@link module:UniformArrayNode~UniformArrayNode}.
  7705. *
  7706. * @param {IndexNode} indexNode - The index node.
  7707. * @return {UniformArrayElementNode}
  7708. */
  7709. element( indexNode ) {
  7710. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  7711. }
  7712. }
  7713. /**
  7714. * TSL function for creating an uniform array node.
  7715. *
  7716. * @function
  7717. * @param {Array<Any>} values - Array-like data.
  7718. * @param {String} nodeType - The data type of the array elements.
  7719. * @returns {UniformArrayNode}
  7720. */
  7721. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  7722. //
  7723. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  7724. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  7725. return nodeObject( new UniformArrayNode( values, nodeType ) );
  7726. };
  7727. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  7728. /** @module ReferenceNode **/
  7729. /**
  7730. * This class is only relevant if the referenced property is array-like.
  7731. * In this case, `ReferenceElementNode` allows to refer to a specific
  7732. * element inside the data structure via an index.
  7733. *
  7734. * @augments ArrayElementNode
  7735. */
  7736. class ReferenceElementNode extends ArrayElementNode {
  7737. static get type() {
  7738. return 'ReferenceElementNode';
  7739. }
  7740. /**
  7741. * Constructs a new reference element node.
  7742. *
  7743. * @param {Node?} referenceNode - The reference node.
  7744. * @param {Node} indexNode - The index node that defines the element access.
  7745. */
  7746. constructor( referenceNode, indexNode ) {
  7747. super( referenceNode, indexNode );
  7748. /**
  7749. * Similar to {@link module:ReferenceNode~ReferenceNode#reference}, an additional
  7750. * property references to the current node.
  7751. *
  7752. * @type {Node?}
  7753. * @default null
  7754. */
  7755. this.referenceNode = referenceNode;
  7756. /**
  7757. * This flag can be used for type testing.
  7758. *
  7759. * @type {Boolean}
  7760. * @readonly
  7761. * @default true
  7762. */
  7763. this.isReferenceElementNode = true;
  7764. }
  7765. /**
  7766. * This method is overwritten since the node type is inferred from
  7767. * the uniform type of the reference node.
  7768. *
  7769. * @param {NodeBuilder} builder - The current node builder.
  7770. * @return {String} The node type.
  7771. */
  7772. getNodeType() {
  7773. return this.referenceNode.uniformType;
  7774. }
  7775. generate( builder ) {
  7776. const snippet = super.generate( builder );
  7777. const arrayType = this.referenceNode.getNodeType();
  7778. const elementType = this.getNodeType();
  7779. return builder.format( snippet, arrayType, elementType );
  7780. }
  7781. }
  7782. /**
  7783. * This type of node establishes a reference to a property of another object.
  7784. * In this way, the value of the node is automatically linked to the value of
  7785. * referenced object. Reference nodes internally represent the linked value
  7786. * as a uniform.
  7787. *
  7788. * @augments Node
  7789. */
  7790. class ReferenceNode extends Node {
  7791. static get type() {
  7792. return 'ReferenceNode';
  7793. }
  7794. /**
  7795. * Constructs a new reference node.
  7796. *
  7797. * @param {String} property - The name of the property the node refers to.
  7798. * @param {String} uniformType - The uniform type that should be used to represent the property value.
  7799. * @param {Object?} [object=null] - The object the property belongs to.
  7800. * @param {Number?} [count=null] - When the linked property is an array-like, this parameter defines its length.
  7801. */
  7802. constructor( property, uniformType, object = null, count = null ) {
  7803. super();
  7804. /**
  7805. * The name of the property the node refers to.
  7806. *
  7807. * @type {String}
  7808. */
  7809. this.property = property;
  7810. /**
  7811. * The uniform type that should be used to represent the property value.
  7812. *
  7813. * @type {String}
  7814. */
  7815. this.uniformType = uniformType;
  7816. /**
  7817. * The object the property belongs to.
  7818. *
  7819. * @type {Object?}
  7820. * @default null
  7821. */
  7822. this.object = object;
  7823. /**
  7824. * When the linked property is an array, this parameter defines its length.
  7825. *
  7826. * @type {Number?}
  7827. * @default null
  7828. */
  7829. this.count = count;
  7830. /**
  7831. * The property name might have dots so nested properties can be referred.
  7832. * The hierarchy of the names is stored inside this array.
  7833. *
  7834. * @type {Array<String>}
  7835. */
  7836. this.properties = property.split( '.' );
  7837. /**
  7838. * Points to the current referred object. This property exists next to {@link module:ReferenceNode~ReferenceNode#object}
  7839. * since the final reference might be updated from calling code.
  7840. *
  7841. * @type {Object?}
  7842. * @default null
  7843. */
  7844. this.reference = object;
  7845. /**
  7846. * The uniform node that holds the value of the reference node.
  7847. *
  7848. * @type {UniformNode}
  7849. * @default null
  7850. */
  7851. this.node = null;
  7852. /**
  7853. * The uniform group of the internal uniform.
  7854. *
  7855. * @type {UniformGroupNode}
  7856. * @default null
  7857. */
  7858. this.group = null;
  7859. /**
  7860. * An optional label of the internal uniform node.
  7861. *
  7862. * @type {String?}
  7863. * @default null
  7864. */
  7865. this.name = null;
  7866. /**
  7867. * Overwritten since reference nodes are updated per object.
  7868. *
  7869. * @type {String}
  7870. * @default 'object'
  7871. */
  7872. this.updateType = NodeUpdateType.OBJECT;
  7873. }
  7874. /**
  7875. * When the referred property is array-like, this method can be used
  7876. * to access elements via an index node.
  7877. *
  7878. * @param {IndexNode} indexNode - indexNode.
  7879. * @return {ReferenceElementNode} A reference to an element.
  7880. */
  7881. element( indexNode ) {
  7882. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  7883. }
  7884. /**
  7885. * Sets the uniform group for this reference node.
  7886. *
  7887. * @param {UniformGroupNode} group - The uniform group to set.
  7888. * @return {ReferenceNode} A reference to this node.
  7889. */
  7890. setGroup( group ) {
  7891. this.group = group;
  7892. return this;
  7893. }
  7894. /**
  7895. * Sets the label for the internal uniform.
  7896. *
  7897. * @param {String} name - The label to set.
  7898. * @return {ReferenceNode} A reference to this node.
  7899. */
  7900. label( name ) {
  7901. this.name = name;
  7902. return this;
  7903. }
  7904. /**
  7905. * Sets the node type which automatically defines the internal
  7906. * uniform type.
  7907. *
  7908. * @param {String} uniformType - The type to set.
  7909. */
  7910. setNodeType( uniformType ) {
  7911. let node = null;
  7912. if ( this.count !== null ) {
  7913. node = buffer( null, uniformType, this.count );
  7914. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  7915. node = uniformArray( null, uniformType );
  7916. } else if ( uniformType === 'texture' ) {
  7917. node = texture( null );
  7918. } else if ( uniformType === 'cubeTexture' ) {
  7919. node = cubeTexture( null );
  7920. } else {
  7921. node = uniform( null, uniformType );
  7922. }
  7923. if ( this.group !== null ) {
  7924. node.setGroup( this.group );
  7925. }
  7926. if ( this.name !== null ) node.label( this.name );
  7927. this.node = node.getSelf();
  7928. }
  7929. /**
  7930. * This method is overwritten since the node type is inferred from
  7931. * the type of the reference node.
  7932. *
  7933. * @param {NodeBuilder} builder - The current node builder.
  7934. * @return {String} The node type.
  7935. */
  7936. getNodeType( builder ) {
  7937. if ( this.node === null ) {
  7938. this.updateReference( builder );
  7939. this.updateValue();
  7940. }
  7941. return this.node.getNodeType( builder );
  7942. }
  7943. /**
  7944. * Returns the property value from the given referred object.
  7945. *
  7946. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  7947. * @return {Any} The value.
  7948. */
  7949. getValueFromReference( object = this.reference ) {
  7950. const { properties } = this;
  7951. let value = object[ properties[ 0 ] ];
  7952. for ( let i = 1; i < properties.length; i ++ ) {
  7953. value = value[ properties[ i ] ];
  7954. }
  7955. return value;
  7956. }
  7957. /**
  7958. * Allows to update the reference based on the given state. The state is only
  7959. * evaluated {@link module:ReferenceNode~ReferenceNode#object} is not set.
  7960. *
  7961. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  7962. * @return {Object} The updated reference.
  7963. */
  7964. updateReference( state ) {
  7965. this.reference = this.object !== null ? this.object : state.object;
  7966. return this.reference;
  7967. }
  7968. /**
  7969. * The output of the reference node is the internal uniform node.
  7970. *
  7971. * @param {NodeBuilder} builder - The current node builder.
  7972. * @return {UniformNode} The output node.
  7973. */
  7974. setup( /* builder */ ) {
  7975. this.updateValue();
  7976. return this.node;
  7977. }
  7978. /**
  7979. * Overwritten to to update the internal uniform value.
  7980. *
  7981. * @param {NodeFrame} frame - A reference to the current node frame.
  7982. */
  7983. update( /*frame*/ ) {
  7984. this.updateValue();
  7985. }
  7986. /**
  7987. * Retrieves the value from the referred object property and uses it
  7988. * to updated the internal uniform.
  7989. */
  7990. updateValue() {
  7991. if ( this.node === null ) this.setNodeType( this.uniformType );
  7992. const value = this.getValueFromReference();
  7993. if ( Array.isArray( value ) ) {
  7994. this.node.array = value;
  7995. } else {
  7996. this.node.value = value;
  7997. }
  7998. }
  7999. }
  8000. /**
  8001. * TSL function for creating a reference node.
  8002. *
  8003. * @function
  8004. * @param {String} name - The name of the property the node refers to.
  8005. * @param {String} type - The uniform type that should be used to represent the property value.
  8006. * @param {Object} object - The object the property belongs to.
  8007. * @returns {ReferenceNode}
  8008. */
  8009. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  8010. /**
  8011. * TSL function for creating a reference node. Use this function if you want need a reference
  8012. * to an array-like property that should be represented as a uniform buffer.
  8013. *
  8014. * @function
  8015. * @param {String} name - The name of the property the node refers to.
  8016. * @param {String} type - The uniform type that should be used to represent the property value.
  8017. * @param {Number} count - The number of value inside the array-like object.
  8018. * @param {Object} object - An array-like object the property belongs to.
  8019. * @returns {ReferenceNode}
  8020. */
  8021. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  8022. /** @module MaterialReferenceNode **/
  8023. /**
  8024. * This node is a special type of reference node which is intended
  8025. * for linking material properties with node values.
  8026. * ```js
  8027. * const opacityNode = materialReference( 'opacity', 'float', material );
  8028. * ```
  8029. * When changing `material.opacity`, the node value of `opacityNode` will
  8030. * automatically be updated.
  8031. *
  8032. * @augments module:ReferenceNode~ReferenceNode
  8033. */
  8034. class MaterialReferenceNode extends ReferenceNode {
  8035. static get type() {
  8036. return 'MaterialReferenceNode';
  8037. }
  8038. /**
  8039. * Constructs a new material reference node.
  8040. *
  8041. * @param {String} property - The name of the property the node refers to.
  8042. * @param {String} inputType - The uniform type that should be used to represent the property value.
  8043. * @param {Material?} [material=null] - The material the property belongs to. When no material is set,
  8044. * the node refers to the material of the current rendered object.
  8045. */
  8046. constructor( property, inputType, material = null ) {
  8047. super( property, inputType, material );
  8048. /**
  8049. * The material the property belongs to. When no material is set,
  8050. * the node refers to the material of the current rendered object.
  8051. *
  8052. * @type {Material?}
  8053. * @default null
  8054. */
  8055. this.material = material;
  8056. /**
  8057. * This flag can be used for type testing.
  8058. *
  8059. * @type {Boolean}
  8060. * @readonly
  8061. * @default true
  8062. */
  8063. this.isMaterialReferenceNode = true;
  8064. }
  8065. /**
  8066. * Updates the reference based on the given state. The state is only evaluated
  8067. * {@link module:MaterialReferenceNode~MaterialReferenceNode#material} is not set.
  8068. *
  8069. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  8070. * @return {Object} The updated reference.
  8071. */
  8072. updateReference( state ) {
  8073. this.reference = this.material !== null ? this.material : state.material;
  8074. return this.reference;
  8075. }
  8076. }
  8077. /**
  8078. * TSL function for creating a material reference node.
  8079. *
  8080. * @function
  8081. * @param {String} name - The name of the property the node refers to.
  8082. * @param {String} type - The uniform type that should be used to represent the property value.
  8083. * @param {Material?} [material=null] - The material the property belongs to.
  8084. * When no material is set, the node refers to the material of the current rendered object.
  8085. * @returns {MaterialReferenceNode}
  8086. */
  8087. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  8088. /** @module Tangent **/
  8089. /**
  8090. * TSL object that represents the tangent attribute of the current rendered object.
  8091. *
  8092. * @type {Node<vec4>}
  8093. */
  8094. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  8095. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  8096. builder.geometry.computeTangents();
  8097. }
  8098. return attribute( 'tangent', 'vec4' );
  8099. } )();
  8100. /**
  8101. * TSL object that represents the vertex tangent in local space of the current rendered object.
  8102. *
  8103. * @type {Node<vec3>}
  8104. */
  8105. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  8106. /**
  8107. * TSL object that represents the vertex tangent in view space of the current rendered object.
  8108. *
  8109. * @type {Node<vec3>}
  8110. */
  8111. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.varying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  8112. /**
  8113. * TSL object that represents the vertex tangent in world space of the current rendered object.
  8114. *
  8115. * @type {Node<vec3>}
  8116. */
  8117. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).varying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  8118. /**
  8119. * TSL object that represents the transformed vertex tangent in view space of the current rendered object.
  8120. *
  8121. * @type {Node<vec3>}
  8122. */
  8123. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  8124. /**
  8125. * TSL object that represents the transformed vertex tangent in world space of the current rendered object.
  8126. *
  8127. * @type {Node<vec3>}
  8128. */
  8129. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  8130. /** @module Bitangent **/
  8131. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  8132. /**
  8133. * TSL object that represents the bitangent attribute of the current rendered object.
  8134. *
  8135. * @type {Node<vec3>}
  8136. */
  8137. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  8138. /**
  8139. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  8140. *
  8141. * @type {Node<vec3>}
  8142. */
  8143. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  8144. /**
  8145. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  8146. *
  8147. * @type {Node<vec4>}
  8148. */
  8149. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  8150. /**
  8151. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  8152. *
  8153. * @type {Node<vec4>}
  8154. */
  8155. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  8156. /**
  8157. * TSL object that represents the transformed vertex bitangent in view space of the current rendered object.
  8158. *
  8159. * @type {Node<vec4>}
  8160. */
  8161. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  8162. /**
  8163. * TSL object that represents the transformed vertex bitangent in world space of the current rendered object.
  8164. *
  8165. * @type {Node<vec4>}
  8166. */
  8167. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  8168. /** @module AccessorsUtils **/
  8169. /**
  8170. * TSL object that represents the TBN matrix in view space.
  8171. *
  8172. * @type {Node<mat3>}
  8173. */
  8174. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  8175. /**
  8176. * TSL object that represents the parallax direction.
  8177. *
  8178. * @type {Node<mat3>}
  8179. */
  8180. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  8181. /**
  8182. * TSL function for computing parallax uv coordinates.
  8183. *
  8184. * @function
  8185. * @param {Node<vec2>} uv - A uv node.
  8186. * @param {Node<vec2>} scale - A scale node.
  8187. * @returns {Node<vec2>} Parallax uv coordinates.
  8188. */
  8189. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  8190. /**
  8191. * TSL function for computing bent normals.
  8192. *
  8193. * @function
  8194. * @returns {Node<vec3>} Bent normals.
  8195. */
  8196. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  8197. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  8198. let bentNormal = anisotropyB.cross( positionViewDirection );
  8199. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  8200. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  8201. return bentNormal;
  8202. } )();
  8203. /** @module NormalMapNode **/
  8204. // Normal Mapping Without Precomputed Tangents
  8205. // http://www.thetenthplanet.de/archives/1180
  8206. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  8207. const { eye_pos, surf_norm, mapN, uv } = inputs;
  8208. const q0 = eye_pos.dFdx();
  8209. const q1 = eye_pos.dFdy();
  8210. const st0 = uv.dFdx();
  8211. const st1 = uv.dFdy();
  8212. const N = surf_norm; // normalized
  8213. const q1perp = q1.cross( N );
  8214. const q0perp = N.cross( q0 );
  8215. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  8216. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  8217. const det = T.dot( T ).max( B.dot( B ) );
  8218. const scale = faceDirection.mul( det.inverseSqrt() );
  8219. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  8220. } );
  8221. /**
  8222. * This class can be used for applying normals maps to materials.
  8223. *
  8224. * ```js
  8225. * material.normalNode = normalMap( texture( normalTex ) );
  8226. * ```
  8227. *
  8228. * @augments TempNode
  8229. */
  8230. class NormalMapNode extends TempNode {
  8231. static get type() {
  8232. return 'NormalMapNode';
  8233. }
  8234. /**
  8235. * Constructs a new normal map node.
  8236. *
  8237. * @param {Node<vec3>} node - Represents the normal map data.
  8238. * @param {Node<vec2>?} [scaleNode=null] - Controls the intensity of the effect.
  8239. */
  8240. constructor( node, scaleNode = null ) {
  8241. super( 'vec3' );
  8242. /**
  8243. * Represents the normal map data.
  8244. *
  8245. * @type {Node<vec3>}
  8246. */
  8247. this.node = node;
  8248. /**
  8249. * Controls the intensity of the effect.
  8250. *
  8251. * @type {Node<vec2>?}
  8252. * @default null
  8253. */
  8254. this.scaleNode = scaleNode;
  8255. /**
  8256. * The normal map type.
  8257. *
  8258. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  8259. * @default TangentSpaceNormalMap
  8260. */
  8261. this.normalMapType = TangentSpaceNormalMap;
  8262. }
  8263. setup( builder ) {
  8264. const { normalMapType, scaleNode } = this;
  8265. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  8266. if ( scaleNode !== null ) {
  8267. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  8268. }
  8269. let outputNode = null;
  8270. if ( normalMapType === ObjectSpaceNormalMap ) {
  8271. outputNode = transformNormalToView( normalMap );
  8272. } else if ( normalMapType === TangentSpaceNormalMap ) {
  8273. const tangent = builder.hasGeometryAttribute( 'tangent' );
  8274. if ( tangent === true ) {
  8275. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  8276. } else {
  8277. outputNode = perturbNormal2Arb( {
  8278. eye_pos: positionView,
  8279. surf_norm: normalView,
  8280. mapN: normalMap,
  8281. uv: uv()
  8282. } );
  8283. }
  8284. }
  8285. return outputNode;
  8286. }
  8287. }
  8288. /**
  8289. * TSL function for creating a normal map node.
  8290. *
  8291. * @function
  8292. * @param {Node<vec3>} node - Represents the normal map data.
  8293. * @param {Node<vec2>?} [scaleNode=null] - Controls the intensity of the effect.
  8294. * @returns {NormalMapNode}
  8295. */
  8296. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  8297. /** @module BumpMapNode **/
  8298. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  8299. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  8300. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  8301. // It's used to preserve the same TextureNode instance
  8302. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  8303. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  8304. return vec2(
  8305. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  8306. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  8307. ).mul( bumpScale );
  8308. } );
  8309. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8310. const perturbNormalArb = Fn( ( inputs ) => {
  8311. const { surf_pos, surf_norm, dHdxy } = inputs;
  8312. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  8313. const vSigmaX = surf_pos.dFdx().normalize();
  8314. const vSigmaY = surf_pos.dFdy().normalize();
  8315. const vN = surf_norm; // normalized
  8316. const R1 = vSigmaY.cross( vN );
  8317. const R2 = vN.cross( vSigmaX );
  8318. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  8319. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  8320. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  8321. } );
  8322. /**
  8323. * This class can be used for applying bump maps to materials.
  8324. *
  8325. * ```js
  8326. * material.normalNode = bumpMap( texture( bumpTex ) );
  8327. * ```
  8328. *
  8329. * @augments TempNode
  8330. */
  8331. class BumpMapNode extends TempNode {
  8332. static get type() {
  8333. return 'BumpMapNode';
  8334. }
  8335. /**
  8336. * Constructs a new bump map node.
  8337. *
  8338. * @param {Node<float>} textureNode - Represents the bump map data.
  8339. * @param {Node<float>?} [scaleNode=null] - Controls the intensity of the bump effect.
  8340. */
  8341. constructor( textureNode, scaleNode = null ) {
  8342. super( 'vec3' );
  8343. /**
  8344. * Represents the bump map data.
  8345. *
  8346. * @type {Node<float>}
  8347. */
  8348. this.textureNode = textureNode;
  8349. /**
  8350. * Controls the intensity of the bump effect.
  8351. *
  8352. * @type {Node<float>?}
  8353. * @default null
  8354. */
  8355. this.scaleNode = scaleNode;
  8356. }
  8357. setup() {
  8358. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  8359. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  8360. return perturbNormalArb( {
  8361. surf_pos: positionView,
  8362. surf_norm: normalView,
  8363. dHdxy
  8364. } );
  8365. }
  8366. }
  8367. /**
  8368. * TSL function for creating a bump map node.
  8369. *
  8370. * @function
  8371. * @param {Node<float>} textureNode - Represents the bump map data.
  8372. * @param {Node<float>?} [scaleNode=null] - Controls the intensity of the bump effect.
  8373. * @returns {BumpMapNode}
  8374. */
  8375. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  8376. /** @module MaterialNode **/
  8377. const _propertyCache = new Map();
  8378. /**
  8379. * This class should simplify the node access to material properties.
  8380. * It internal uses reference nodes to make sure changes to material
  8381. * properties are automatically reflected to predefined TSL objects
  8382. * like e.g. `materialColor`.
  8383. *
  8384. * @augments Node
  8385. */
  8386. class MaterialNode extends Node {
  8387. static get type() {
  8388. return 'MaterialNode';
  8389. }
  8390. /**
  8391. * Constructs a new material node.
  8392. *
  8393. * @param {String} scope - The scope defines what kind of material property is referred by the node.
  8394. */
  8395. constructor( scope ) {
  8396. super();
  8397. /**
  8398. * The scope defines what material property is referred by the node.
  8399. *
  8400. * @type {String}
  8401. */
  8402. this.scope = scope;
  8403. }
  8404. /**
  8405. * Returns a cached reference node for the given property and type.
  8406. *
  8407. * @param {String} property - The name of the material property.
  8408. * @param {String} type - The uniform type of the property.
  8409. * @return {MaterialReferenceNode} A material reference node representing the property access.
  8410. */
  8411. getCache( property, type ) {
  8412. let node = _propertyCache.get( property );
  8413. if ( node === undefined ) {
  8414. node = materialReference( property, type );
  8415. _propertyCache.set( property, node );
  8416. }
  8417. return node;
  8418. }
  8419. /**
  8420. * Returns a float-typed material reference node for the given property name.
  8421. *
  8422. * @param {String} property - The name of the material property.
  8423. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  8424. */
  8425. getFloat( property ) {
  8426. return this.getCache( property, 'float' );
  8427. }
  8428. /**
  8429. * Returns a color-typed material reference node for the given property name.
  8430. *
  8431. * @param {String} property - The name of the material property.
  8432. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  8433. */
  8434. getColor( property ) {
  8435. return this.getCache( property, 'color' );
  8436. }
  8437. /**
  8438. * Returns a texture-typed material reference node for the given property name.
  8439. *
  8440. * @param {String} property - The name of the material property.
  8441. * @return {MaterialReferenceNode} A material reference node representing the property access.
  8442. */
  8443. getTexture( property ) {
  8444. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  8445. }
  8446. /**
  8447. * The node setup is done depending on the selected scope. Multiple material properties
  8448. * might be grouped into a single node composition if they logically belong together.
  8449. *
  8450. * @param {NodeBuilder} builder - The current node builder.
  8451. * @return {Node} The node representing the selected scope.
  8452. */
  8453. setup( builder ) {
  8454. const material = builder.context.material;
  8455. const scope = this.scope;
  8456. let node = null;
  8457. if ( scope === MaterialNode.COLOR ) {
  8458. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  8459. if ( material.map && material.map.isTexture === true ) {
  8460. node = colorNode.mul( this.getTexture( 'map' ) );
  8461. } else {
  8462. node = colorNode;
  8463. }
  8464. } else if ( scope === MaterialNode.OPACITY ) {
  8465. const opacityNode = this.getFloat( scope );
  8466. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  8467. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  8468. } else {
  8469. node = opacityNode;
  8470. }
  8471. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  8472. if ( material.specularMap && material.specularMap.isTexture === true ) {
  8473. node = this.getTexture( 'specular' ).r;
  8474. } else {
  8475. node = float( 1 );
  8476. }
  8477. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  8478. const specularIntensityNode = this.getFloat( scope );
  8479. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  8480. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  8481. } else {
  8482. node = specularIntensityNode;
  8483. }
  8484. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  8485. const specularColorNode = this.getColor( scope );
  8486. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  8487. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  8488. } else {
  8489. node = specularColorNode;
  8490. }
  8491. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  8492. const roughnessNode = this.getFloat( scope );
  8493. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  8494. node = roughnessNode.mul( this.getTexture( scope ).g );
  8495. } else {
  8496. node = roughnessNode;
  8497. }
  8498. } else if ( scope === MaterialNode.METALNESS ) {
  8499. const metalnessNode = this.getFloat( scope );
  8500. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  8501. node = metalnessNode.mul( this.getTexture( scope ).b );
  8502. } else {
  8503. node = metalnessNode;
  8504. }
  8505. } else if ( scope === MaterialNode.EMISSIVE ) {
  8506. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  8507. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  8508. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  8509. node = emissiveNode.mul( this.getTexture( scope ) );
  8510. } else {
  8511. node = emissiveNode;
  8512. }
  8513. } else if ( scope === MaterialNode.NORMAL ) {
  8514. if ( material.normalMap ) {
  8515. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  8516. node.normalMapType = material.normalMapType;
  8517. } else if ( material.bumpMap ) {
  8518. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  8519. } else {
  8520. node = normalView;
  8521. }
  8522. } else if ( scope === MaterialNode.CLEARCOAT ) {
  8523. const clearcoatNode = this.getFloat( scope );
  8524. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  8525. node = clearcoatNode.mul( this.getTexture( scope ).r );
  8526. } else {
  8527. node = clearcoatNode;
  8528. }
  8529. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  8530. const clearcoatRoughnessNode = this.getFloat( scope );
  8531. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  8532. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  8533. } else {
  8534. node = clearcoatRoughnessNode;
  8535. }
  8536. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  8537. if ( material.clearcoatNormalMap ) {
  8538. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  8539. } else {
  8540. node = normalView;
  8541. }
  8542. } else if ( scope === MaterialNode.SHEEN ) {
  8543. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  8544. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  8545. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  8546. } else {
  8547. node = sheenNode;
  8548. }
  8549. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  8550. const sheenRoughnessNode = this.getFloat( scope );
  8551. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  8552. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  8553. } else {
  8554. node = sheenRoughnessNode;
  8555. }
  8556. node = node.clamp( 0.07, 1.0 );
  8557. } else if ( scope === MaterialNode.ANISOTROPY ) {
  8558. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  8559. const anisotropyPolar = this.getTexture( scope );
  8560. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  8561. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  8562. } else {
  8563. node = materialAnisotropyVector;
  8564. }
  8565. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  8566. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  8567. if ( material.iridescenceThicknessMap ) {
  8568. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  8569. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  8570. } else {
  8571. node = iridescenceThicknessMaximum;
  8572. }
  8573. } else if ( scope === MaterialNode.TRANSMISSION ) {
  8574. const transmissionNode = this.getFloat( scope );
  8575. if ( material.transmissionMap ) {
  8576. node = transmissionNode.mul( this.getTexture( scope ).r );
  8577. } else {
  8578. node = transmissionNode;
  8579. }
  8580. } else if ( scope === MaterialNode.THICKNESS ) {
  8581. const thicknessNode = this.getFloat( scope );
  8582. if ( material.thicknessMap ) {
  8583. node = thicknessNode.mul( this.getTexture( scope ).g );
  8584. } else {
  8585. node = thicknessNode;
  8586. }
  8587. } else if ( scope === MaterialNode.IOR ) {
  8588. node = this.getFloat( scope );
  8589. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  8590. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  8591. } else if ( scope === MaterialNode.AO ) {
  8592. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  8593. } else {
  8594. const outputType = this.getNodeType( builder );
  8595. node = this.getCache( scope, outputType );
  8596. }
  8597. return node;
  8598. }
  8599. }
  8600. MaterialNode.ALPHA_TEST = 'alphaTest';
  8601. MaterialNode.COLOR = 'color';
  8602. MaterialNode.OPACITY = 'opacity';
  8603. MaterialNode.SHININESS = 'shininess';
  8604. MaterialNode.SPECULAR = 'specular';
  8605. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  8606. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  8607. MaterialNode.SPECULAR_COLOR = 'specularColor';
  8608. MaterialNode.REFLECTIVITY = 'reflectivity';
  8609. MaterialNode.ROUGHNESS = 'roughness';
  8610. MaterialNode.METALNESS = 'metalness';
  8611. MaterialNode.NORMAL = 'normal';
  8612. MaterialNode.CLEARCOAT = 'clearcoat';
  8613. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  8614. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  8615. MaterialNode.EMISSIVE = 'emissive';
  8616. MaterialNode.ROTATION = 'rotation';
  8617. MaterialNode.SHEEN = 'sheen';
  8618. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  8619. MaterialNode.ANISOTROPY = 'anisotropy';
  8620. MaterialNode.IRIDESCENCE = 'iridescence';
  8621. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  8622. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  8623. MaterialNode.IOR = 'ior';
  8624. MaterialNode.TRANSMISSION = 'transmission';
  8625. MaterialNode.THICKNESS = 'thickness';
  8626. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  8627. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  8628. MaterialNode.LINE_SCALE = 'scale';
  8629. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  8630. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  8631. MaterialNode.LINE_WIDTH = 'linewidth';
  8632. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  8633. MaterialNode.POINT_WIDTH = 'pointWidth';
  8634. MaterialNode.DISPERSION = 'dispersion';
  8635. MaterialNode.LIGHT_MAP = 'light';
  8636. MaterialNode.AO = 'ao';
  8637. /**
  8638. * TSL object that represents alpha test of the current material.
  8639. *
  8640. * @type {Node<float>}
  8641. */
  8642. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  8643. /**
  8644. * TSL object that represents the diffuse color of the current material.
  8645. * The value is composed via `color` * `map`.
  8646. *
  8647. * @type {Node<vec3>}
  8648. */
  8649. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  8650. /**
  8651. * TSL object that represents the shininess of the current material.
  8652. *
  8653. * @type {Node<float>}
  8654. */
  8655. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  8656. /**
  8657. * TSL object that represents the emissive color of the current material.
  8658. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  8659. *
  8660. * @type {Node<vec3>}
  8661. */
  8662. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  8663. /**
  8664. * TSL object that represents the opacity of the current material.
  8665. * The value is composed via `opacity` * `alphaMap`.
  8666. *
  8667. * @type {Node<float>}
  8668. */
  8669. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  8670. /**
  8671. * TSL object that represents the specular of the current material.
  8672. *
  8673. * @type {Node<vec3>}
  8674. */
  8675. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  8676. /**
  8677. * TSL object that represents the specular intensity of the current material.
  8678. * The value is composed via `specularIntensity` * `specularMap.a`.
  8679. *
  8680. * @type {Node<float>}
  8681. */
  8682. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  8683. /**
  8684. * TSL object that represents the specular color of the current material.
  8685. * The value is composed via `specularColor` * `specularMap.rgb`.
  8686. *
  8687. * @type {Node<vec3>}
  8688. */
  8689. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  8690. /**
  8691. * TSL object that represents the specular strength of the current material.
  8692. * The value is composed via `specularMap.r`.
  8693. *
  8694. * @type {Node<float>}
  8695. */
  8696. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  8697. /**
  8698. * TSL object that represents the reflectivity of the current material.
  8699. *
  8700. * @type {Node<float>}
  8701. */
  8702. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  8703. /**
  8704. * TSL object that represents the roughness of the current material.
  8705. * The value is composed via `roughness` * `roughnessMap.g`.
  8706. *
  8707. * @type {Node<float>}
  8708. */
  8709. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  8710. /**
  8711. * TSL object that represents the metalness of the current material.
  8712. * The value is composed via `metalness` * `metalnessMap.b`.
  8713. *
  8714. * @type {Node<float>}
  8715. */
  8716. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  8717. /**
  8718. * TSL object that represents the normal of the current material.
  8719. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  8720. *
  8721. * @type {Node<vec3>}
  8722. */
  8723. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  8724. /**
  8725. * TSL object that represents the clearcoat of the current material.
  8726. * The value is composed via `clearcoat` * `clearcoatMap.r`
  8727. *
  8728. * @type {Node<float>}
  8729. */
  8730. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  8731. /**
  8732. * TSL object that represents the clearcoat roughness of the current material.
  8733. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  8734. *
  8735. * @type {Node<float>}
  8736. */
  8737. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  8738. /**
  8739. * TSL object that represents the clearcoat normal of the current material.
  8740. * The value will be either `clearcoatNormalMap` or `normalView`.
  8741. *
  8742. * @type {Node<vec3>}
  8743. */
  8744. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  8745. /**
  8746. * TSL object that represents the rotation of the current sprite material.
  8747. *
  8748. * @type {Node<float>}
  8749. */
  8750. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  8751. /**
  8752. * TSL object that represents the sheen color of the current material.
  8753. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  8754. *
  8755. * @type {Node<vec3>}
  8756. */
  8757. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  8758. /**
  8759. * TSL object that represents the sheen roughness of the current material.
  8760. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  8761. *
  8762. * @type {Node<float>}
  8763. */
  8764. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  8765. /**
  8766. * TSL object that represents the anisotropy of the current material.
  8767. *
  8768. * @type {Node<vec2>}
  8769. */
  8770. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  8771. /**
  8772. * TSL object that represents the iridescence of the current material.
  8773. *
  8774. * @type {Node<float>}
  8775. */
  8776. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  8777. /**
  8778. * TSL object that represents the iridescence IOR of the current material.
  8779. *
  8780. * @type {Node<float>}
  8781. */
  8782. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  8783. /**
  8784. * TSL object that represents the iridescence thickness of the current material.
  8785. *
  8786. * @type {Node<float>}
  8787. */
  8788. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  8789. /**
  8790. * TSL object that represents the transmission of the current material.
  8791. * The value is composed via `transmission` * `transmissionMap.r`.
  8792. *
  8793. * @type {Node<float>}
  8794. */
  8795. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  8796. /**
  8797. * TSL object that represents the thickness of the current material.
  8798. * The value is composed via `thickness` * `thicknessMap.g`.
  8799. *
  8800. * @type {Node<float>}
  8801. */
  8802. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  8803. /**
  8804. * TSL object that represents the IOR of the current material.
  8805. *
  8806. * @type {Node<float>}
  8807. */
  8808. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  8809. /**
  8810. * TSL object that represents the attenuation distance of the current material.
  8811. *
  8812. * @type {Node<float>}
  8813. */
  8814. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  8815. /**
  8816. * TSL object that represents the attenuation color of the current material.
  8817. *
  8818. * @type {Node<vec3>}
  8819. */
  8820. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  8821. /**
  8822. * TSL object that represents the scale of the current dashed line material.
  8823. *
  8824. * @type {Node<float>}
  8825. */
  8826. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  8827. /**
  8828. * TSL object that represents the dash size of the current dashed line material.
  8829. *
  8830. * @type {Node<float>}
  8831. */
  8832. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  8833. /**
  8834. * TSL object that represents the gap size of the current dashed line material.
  8835. *
  8836. * @type {Node<float>}
  8837. */
  8838. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  8839. /**
  8840. * TSL object that represents the line width of the current line material.
  8841. *
  8842. * @type {Node<float>}
  8843. */
  8844. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  8845. /**
  8846. * TSL object that represents the dash offset of the current line material.
  8847. *
  8848. * @type {Node<float>}
  8849. */
  8850. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  8851. /**
  8852. * TSL object that represents the point width of the current points material.
  8853. *
  8854. * @type {Node<float>}
  8855. */
  8856. const materialPointWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_WIDTH );
  8857. /**
  8858. * TSL object that represents the dispersion of the current material.
  8859. *
  8860. * @type {Node<float>}
  8861. */
  8862. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  8863. /**
  8864. * TSL object that represents the light map of the current material.
  8865. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  8866. *
  8867. * @type {Node<vec3>}
  8868. */
  8869. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  8870. /**
  8871. * TSL object that represents the ambient occlusion map of the current material.
  8872. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  8873. *
  8874. * @type {Node<float>}
  8875. */
  8876. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  8877. /**
  8878. * TSL object that represents the anisotropy vector of the current material.
  8879. *
  8880. * @type {Node<vec2>}
  8881. */
  8882. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  8883. return frame.material;
  8884. } ).onRenderUpdate( function ( { material } ) {
  8885. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  8886. } );
  8887. /** @module ModelViewProjectionNode **/
  8888. /**
  8889. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  8890. *
  8891. * @type {VaryingNode<vec4>}
  8892. */
  8893. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  8894. return builder.context.setupModelViewProjection();
  8895. }, 'vec4' ).once() )().varying( 'v_modelViewProjection' );
  8896. /** @module IndexNode **/
  8897. /**
  8898. * This class represents shader indices of different types. The following predefined node
  8899. * objects cover frequent use cases:
  8900. *
  8901. * - `vertexIndex`: The index of a vertex within a mesh.
  8902. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  8903. * - `drawIndex`: The index of a draw call.
  8904. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  8905. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  8906. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  8907. *
  8908. * @augments Node
  8909. */
  8910. class IndexNode extends Node {
  8911. static get type() {
  8912. return 'IndexNode';
  8913. }
  8914. /**
  8915. * Constructs a new index node.
  8916. *
  8917. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  8918. */
  8919. constructor( scope ) {
  8920. super( 'uint' );
  8921. /**
  8922. * The scope of the index node.
  8923. *
  8924. * @type {String}
  8925. */
  8926. this.scope = scope;
  8927. /**
  8928. * This flag can be used for type testing.
  8929. *
  8930. * @type {Boolean}
  8931. * @readonly
  8932. * @default true
  8933. */
  8934. this.isIndexNode = true;
  8935. }
  8936. generate( builder ) {
  8937. const nodeType = this.getNodeType( builder );
  8938. const scope = this.scope;
  8939. let propertyName;
  8940. if ( scope === IndexNode.VERTEX ) {
  8941. propertyName = builder.getVertexIndex();
  8942. } else if ( scope === IndexNode.INSTANCE ) {
  8943. propertyName = builder.getInstanceIndex();
  8944. } else if ( scope === IndexNode.DRAW ) {
  8945. propertyName = builder.getDrawIndex();
  8946. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  8947. propertyName = builder.getInvocationLocalIndex();
  8948. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  8949. propertyName = builder.getInvocationSubgroupIndex();
  8950. } else if ( scope === IndexNode.SUBGROUP ) {
  8951. propertyName = builder.getSubgroupIndex();
  8952. } else {
  8953. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  8954. }
  8955. let output;
  8956. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  8957. output = propertyName;
  8958. } else {
  8959. const nodeVarying = varying( this );
  8960. output = nodeVarying.build( builder, nodeType );
  8961. }
  8962. return output;
  8963. }
  8964. }
  8965. IndexNode.VERTEX = 'vertex';
  8966. IndexNode.INSTANCE = 'instance';
  8967. IndexNode.SUBGROUP = 'subgroup';
  8968. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  8969. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  8970. IndexNode.DRAW = 'draw';
  8971. /**
  8972. * TSL object that represents the index of a vertex within a mesh.
  8973. *
  8974. * @type {IndexNode}
  8975. */
  8976. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  8977. /**
  8978. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  8979. *
  8980. * @type {IndexNode}
  8981. */
  8982. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  8983. /**
  8984. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  8985. *
  8986. * @type {IndexNode}
  8987. */
  8988. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  8989. /**
  8990. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  8991. *
  8992. * @type {IndexNode}
  8993. */
  8994. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  8995. /**
  8996. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  8997. *
  8998. * @type {IndexNode}
  8999. */
  9000. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  9001. /**
  9002. * TSL object that represents the index of a draw call.
  9003. *
  9004. * @type {IndexNode}
  9005. */
  9006. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  9007. /** @module InstanceNode **/
  9008. /**
  9009. * This node implements the vertex shader logic which is required
  9010. * when rendering 3D objects via instancing. The code makes sure
  9011. * vertex positions, normals and colors can be modified via instanced
  9012. * data.
  9013. *
  9014. * @augments Node
  9015. */
  9016. class InstanceNode extends Node {
  9017. static get type() {
  9018. return 'InstanceNode';
  9019. }
  9020. /**
  9021. * Constructs a new instance node.
  9022. *
  9023. * @param {Number} count - The number of instances.
  9024. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  9025. * @param {InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  9026. */
  9027. constructor( count, instanceMatrix, instanceColor ) {
  9028. super( 'void' );
  9029. /**
  9030. * The number of instances.
  9031. *
  9032. * @type {Number}
  9033. */
  9034. this.count = count;
  9035. /**
  9036. * Instanced buffer attribute representing the transformation of instances.
  9037. *
  9038. * @type {InstancedBufferAttribute}
  9039. */
  9040. this.instanceMatrix = instanceMatrix;
  9041. /**
  9042. * Instanced buffer attribute representing the color of instances.
  9043. *
  9044. * @type {InstancedBufferAttribute}
  9045. */
  9046. this.instanceColor = instanceColor;
  9047. /**
  9048. * The node that represents the instance matrix data.
  9049. *
  9050. * @type {Node}
  9051. */
  9052. this.instanceMatrixNode = null;
  9053. /**
  9054. * The node that represents the instance color data.
  9055. *
  9056. * @type {Node}
  9057. */
  9058. this.instanceColorNode = null;
  9059. /**
  9060. * The update type is set to `frame` since an update
  9061. * of instanced buffer data must be checked per frame.
  9062. *
  9063. * @type {String}
  9064. * @default 'frame'
  9065. */
  9066. this.updateType = NodeUpdateType.FRAME;
  9067. /**
  9068. * A reference to a buffer that is used by `instanceMatrixNode`.
  9069. *
  9070. * @type {InstancedInterleavedBuffer}
  9071. */
  9072. this.buffer = null;
  9073. /**
  9074. * A reference to a buffer that is used by `instanceColorNode`.
  9075. *
  9076. * @type {InstancedInterleavedBuffer}
  9077. */
  9078. this.bufferColor = null;
  9079. }
  9080. /**
  9081. * Setups the internal buffers and nodes and assigns the transformed vertex data
  9082. * to predefined node variables for accumulation. That follows the same patterns
  9083. * like with morph and skinning nodes.
  9084. *
  9085. * @param {NodeBuilder} builder - The current node builder.
  9086. */
  9087. setup( builder ) {
  9088. const { count, instanceMatrix, instanceColor } = this;
  9089. let { instanceMatrixNode, instanceColorNode } = this;
  9090. if ( instanceMatrixNode === null ) {
  9091. // 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.
  9092. if ( count <= 1000 ) {
  9093. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  9094. } else {
  9095. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  9096. this.buffer = buffer;
  9097. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  9098. const instanceBuffers = [
  9099. // F.Signature -> bufferAttribute( array, type, stride, offset )
  9100. bufferFn( buffer, 'vec4', 16, 0 ),
  9101. bufferFn( buffer, 'vec4', 16, 4 ),
  9102. bufferFn( buffer, 'vec4', 16, 8 ),
  9103. bufferFn( buffer, 'vec4', 16, 12 )
  9104. ];
  9105. instanceMatrixNode = mat4( ...instanceBuffers );
  9106. }
  9107. this.instanceMatrixNode = instanceMatrixNode;
  9108. }
  9109. if ( instanceColor && instanceColorNode === null ) {
  9110. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  9111. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  9112. this.bufferColor = buffer;
  9113. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  9114. this.instanceColorNode = instanceColorNode;
  9115. }
  9116. // POSITION
  9117. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  9118. positionLocal.assign( instancePosition );
  9119. // NORMAL
  9120. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  9121. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  9122. // ASSIGNS
  9123. normalLocal.assign( instanceNormal );
  9124. }
  9125. // COLOR
  9126. if ( this.instanceColorNode !== null ) {
  9127. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  9128. }
  9129. }
  9130. /**
  9131. * Checks if the internal buffers required an update.
  9132. *
  9133. * @param {NodeFrame} frame - The current node frame.
  9134. */
  9135. update( /*frame*/ ) {
  9136. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer !== null && this.instanceMatrix.version !== this.buffer.version ) {
  9137. this.buffer.version = this.instanceMatrix.version;
  9138. }
  9139. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor !== null && this.instanceColor.version !== this.bufferColor.version ) {
  9140. this.bufferColor.version = this.instanceColor.version;
  9141. }
  9142. }
  9143. }
  9144. /**
  9145. * TSL function for creating an instance node.
  9146. *
  9147. * @function
  9148. * @param {Number} count - The number of instances.
  9149. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  9150. * @param {InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  9151. * @returns {InstanceNode}
  9152. */
  9153. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  9154. /** @module InstancedMeshNode **/
  9155. /**
  9156. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  9157. * It allows an easier setup of the instance node.
  9158. *
  9159. * @augments module:InstanceNode~InstanceNode
  9160. */
  9161. class InstancedMeshNode extends InstanceNode {
  9162. static get type() {
  9163. return 'InstancedMeshNode';
  9164. }
  9165. /**
  9166. * Constructs a new instanced mesh node.
  9167. *
  9168. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  9169. */
  9170. constructor( instancedMesh ) {
  9171. const { count, instanceMatrix, instanceColor } = instancedMesh;
  9172. super( count, instanceMatrix, instanceColor );
  9173. /**
  9174. * A reference to the instanced mesh.
  9175. *
  9176. * @type {InstancedMesh}
  9177. */
  9178. this.instancedMesh = instancedMesh;
  9179. }
  9180. }
  9181. /**
  9182. * TSL function for creating an instanced mesh node.
  9183. *
  9184. * @function
  9185. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  9186. * @returns {InstancedMeshNode}
  9187. */
  9188. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode );
  9189. /** @module BatchNode **/
  9190. /**
  9191. * This node implements the vertex shader logic which is required
  9192. * when rendering 3D objects via batching. `BatchNode` must be used
  9193. * with instances of {@link BatchedMesh}.
  9194. *
  9195. * @augments Node
  9196. */
  9197. class BatchNode extends Node {
  9198. static get type() {
  9199. return 'BatchNode';
  9200. }
  9201. /**
  9202. * Constructs a new batch node.
  9203. *
  9204. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  9205. */
  9206. constructor( batchMesh ) {
  9207. super( 'void' );
  9208. /**
  9209. * A reference to batched mesh.
  9210. *
  9211. * @type {BatchedMesh}
  9212. */
  9213. this.batchMesh = batchMesh;
  9214. /**
  9215. * The batching index node.
  9216. *
  9217. * @type {IndexNode?}
  9218. * @default null
  9219. */
  9220. this.batchingIdNode = null;
  9221. }
  9222. /**
  9223. * Setups the internal buffers and nodes and assigns the transformed vertex data
  9224. * to predefined node variables for accumulation. That follows the same patterns
  9225. * like with morph and skinning nodes.
  9226. *
  9227. * @param {NodeBuilder} builder - The current node builder.
  9228. */
  9229. setup( builder ) {
  9230. if ( this.batchingIdNode === null ) {
  9231. if ( builder.getDrawIndex() === null ) {
  9232. this.batchingIdNode = instanceIndex;
  9233. } else {
  9234. this.batchingIdNode = drawIndex;
  9235. }
  9236. }
  9237. const getIndirectIndex = Fn( ( [ id ] ) => {
  9238. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  9239. const x = int( id ).modInt( int( size ) );
  9240. const y = int( id ).div( int( size ) );
  9241. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  9242. } ).setLayout( {
  9243. name: 'getIndirectIndex',
  9244. type: 'uint',
  9245. inputs: [
  9246. { name: 'id', type: 'int' }
  9247. ]
  9248. } );
  9249. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  9250. const matricesTexture = this.batchMesh._matricesTexture;
  9251. const size = textureSize( textureLoad( matricesTexture ), 0 );
  9252. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  9253. const x = j.modInt( size );
  9254. const y = j.div( int( size ) );
  9255. const batchingMatrix = mat4(
  9256. textureLoad( matricesTexture, ivec2( x, y ) ),
  9257. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  9258. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  9259. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  9260. );
  9261. const colorsTexture = this.batchMesh._colorsTexture;
  9262. if ( colorsTexture !== null ) {
  9263. const getBatchingColor = Fn( ( [ id ] ) => {
  9264. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  9265. const j = id;
  9266. const x = j.modInt( size );
  9267. const y = j.div( size );
  9268. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  9269. } ).setLayout( {
  9270. name: 'getBatchingColor',
  9271. type: 'vec3',
  9272. inputs: [
  9273. { name: 'id', type: 'int' }
  9274. ]
  9275. } );
  9276. const color = getBatchingColor( indirectId );
  9277. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  9278. }
  9279. const bm = mat3( batchingMatrix );
  9280. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  9281. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  9282. const batchingNormal = bm.mul( transformedNormal ).xyz;
  9283. normalLocal.assign( batchingNormal );
  9284. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  9285. tangentLocal.mulAssign( bm );
  9286. }
  9287. }
  9288. }
  9289. /**
  9290. * TSL function for creating a batch node.
  9291. *
  9292. * @function
  9293. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  9294. * @returns {BatchNode}
  9295. */
  9296. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  9297. /** @module SkinningNode **/
  9298. const _frameId = new WeakMap();
  9299. /**
  9300. * This node implements the vertex transformation shader logic which is required
  9301. * for skinning/skeletal animation.
  9302. *
  9303. * @augments Node
  9304. */
  9305. class SkinningNode extends Node {
  9306. static get type() {
  9307. return 'SkinningNode';
  9308. }
  9309. /**
  9310. * Constructs a new skinning node.
  9311. *
  9312. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9313. * @param {Boolean} [useReference=false] - Whether to use reference nodes for internal skinned mesh related data or not.
  9314. */
  9315. constructor( skinnedMesh, useReference = false ) {
  9316. super( 'void' );
  9317. /**
  9318. * The skinned mesh.
  9319. *
  9320. * @type {SkinnedMesh}
  9321. */
  9322. this.skinnedMesh = skinnedMesh;
  9323. /**
  9324. * Whether to use reference nodes for internal skinned mesh related data or not.
  9325. * TODO: Explain the purpose of the property.
  9326. *
  9327. * @type {Boolean}
  9328. */
  9329. this.useReference = useReference;
  9330. /**
  9331. * The update type overwritten since skinning nodes are updated per object.
  9332. *
  9333. * @type {String}
  9334. */
  9335. this.updateType = NodeUpdateType.OBJECT;
  9336. //
  9337. /**
  9338. * The skin index attribute.
  9339. *
  9340. * @type {AttributeNode}
  9341. */
  9342. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  9343. /**
  9344. * The skin weight attribute.
  9345. *
  9346. * @type {AttributeNode}
  9347. */
  9348. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  9349. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  9350. if ( useReference ) {
  9351. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  9352. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  9353. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  9354. } else {
  9355. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  9356. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  9357. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  9358. }
  9359. /**
  9360. * The bind matrix node.
  9361. *
  9362. * @type {Node<mat4>}
  9363. */
  9364. this.bindMatrixNode = bindMatrixNode;
  9365. /**
  9366. * The bind matrix inverse node.
  9367. *
  9368. * @type {Node<mat4>}
  9369. */
  9370. this.bindMatrixInverseNode = bindMatrixInverseNode;
  9371. /**
  9372. * The bind matrices as a uniform buffer node.
  9373. *
  9374. * @type {Node}
  9375. */
  9376. this.boneMatricesNode = boneMatricesNode;
  9377. /**
  9378. * The previous bind matrices as a uniform buffer node.
  9379. * Required for computing motion vectors.
  9380. *
  9381. * @type {Node?}
  9382. * @default null
  9383. */
  9384. this.previousBoneMatricesNode = null;
  9385. }
  9386. /**
  9387. * Transforms the given vertex position via skinning.
  9388. *
  9389. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  9390. * @param {Node<vec3>} [position=positionLocal] - The vertex position in local space.
  9391. * @return {Node<vec3>} The transformed vertex position.
  9392. */
  9393. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  9394. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  9395. const boneMatX = boneMatrices.element( skinIndexNode.x );
  9396. const boneMatY = boneMatrices.element( skinIndexNode.y );
  9397. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  9398. const boneMatW = boneMatrices.element( skinIndexNode.w );
  9399. // POSITION
  9400. const skinVertex = bindMatrixNode.mul( position );
  9401. const skinned = add(
  9402. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  9403. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  9404. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  9405. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  9406. );
  9407. return bindMatrixInverseNode.mul( skinned ).xyz;
  9408. }
  9409. /**
  9410. * Transforms the given vertex normal via skinning.
  9411. *
  9412. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  9413. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  9414. * @return {Node<vec3>} The transformed vertex normal.
  9415. */
  9416. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  9417. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  9418. const boneMatX = boneMatrices.element( skinIndexNode.x );
  9419. const boneMatY = boneMatrices.element( skinIndexNode.y );
  9420. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  9421. const boneMatW = boneMatrices.element( skinIndexNode.w );
  9422. // NORMAL
  9423. let skinMatrix = add(
  9424. skinWeightNode.x.mul( boneMatX ),
  9425. skinWeightNode.y.mul( boneMatY ),
  9426. skinWeightNode.z.mul( boneMatZ ),
  9427. skinWeightNode.w.mul( boneMatW )
  9428. );
  9429. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  9430. return skinMatrix.transformDirection( normal ).xyz;
  9431. }
  9432. /**
  9433. * Transforms the given vertex normal via skinning.
  9434. *
  9435. * @param {NodeBuilder} builder - The current node builder.
  9436. * @return {Node<vec3>} The skinned position from the previous frame.
  9437. */
  9438. getPreviousSkinnedPosition( builder ) {
  9439. const skinnedMesh = builder.object;
  9440. if ( this.previousBoneMatricesNode === null ) {
  9441. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  9442. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  9443. }
  9444. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  9445. }
  9446. /**
  9447. * Returns `true` if bone matrices from the previous frame are required.
  9448. *
  9449. * @param {NodeBuilder} builder - The current node builder.
  9450. * @return {Boolean} Whether bone matrices from the previous frame are required or not.
  9451. */
  9452. needsPreviousBoneMatrices( builder ) {
  9453. const mrt = builder.renderer.getMRT();
  9454. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  9455. }
  9456. /**
  9457. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  9458. *
  9459. * @param {NodeBuilder} builder - The current node builder.
  9460. */
  9461. setup( builder ) {
  9462. if ( this.needsPreviousBoneMatrices( builder ) ) {
  9463. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  9464. }
  9465. const skinPosition = this.getSkinnedPosition();
  9466. positionLocal.assign( skinPosition );
  9467. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  9468. const skinNormal = this.getSkinnedNormal();
  9469. normalLocal.assign( skinNormal );
  9470. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  9471. tangentLocal.assign( skinNormal );
  9472. }
  9473. }
  9474. }
  9475. /**
  9476. * Generates the code snippet of the skinning node.
  9477. *
  9478. * @param {NodeBuilder} builder - The current node builder.
  9479. * @param {String} output - The current output.
  9480. * @return {String} The generated code snippet.
  9481. */
  9482. generate( builder, output ) {
  9483. if ( output !== 'void' ) {
  9484. return positionLocal.build( builder, output );
  9485. }
  9486. }
  9487. /**
  9488. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  9489. *
  9490. * @param {NodeFrame} frame - The current node frame.
  9491. */
  9492. update( frame ) {
  9493. const object = this.useReference ? frame.object : this.skinnedMesh;
  9494. const skeleton = object.skeleton;
  9495. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  9496. _frameId.set( skeleton, frame.frameId );
  9497. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  9498. skeleton.update();
  9499. }
  9500. }
  9501. /**
  9502. * TSL function for creating a skinning node.
  9503. *
  9504. * @function
  9505. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9506. * @returns {SkinningNode}
  9507. */
  9508. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  9509. /**
  9510. * TSL function for creating a skinning node with reference usage.
  9511. *
  9512. * @function
  9513. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9514. * @returns {SkinningNode}
  9515. */
  9516. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  9517. /** @module LoopNode **/
  9518. /**
  9519. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  9520. * ```js
  9521. * Loop( count, ( { i } ) => {
  9522. *
  9523. * } );
  9524. * ```
  9525. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  9526. * ```js
  9527. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  9528. *
  9529. * } );
  9530. *```
  9531. * Nested loops can be defined in a compacted form:
  9532. * ```js
  9533. * Loop( 10, 5, ( { i, j } ) => {
  9534. *
  9535. * } );
  9536. * ```
  9537. * Loops that should run backwards can be defined like so:
  9538. * ```js
  9539. * Loop( { start: 10 }, () => {} );
  9540. * ```
  9541. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  9542. * @augments Node
  9543. */
  9544. class LoopNode extends Node {
  9545. static get type() {
  9546. return 'LoopNode';
  9547. }
  9548. /**
  9549. * Constructs a new loop node.
  9550. *
  9551. * @param {Array<Any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  9552. */
  9553. constructor( params = [] ) {
  9554. super();
  9555. this.params = params;
  9556. }
  9557. /**
  9558. * Returns a loop variable name based on an index. The pattern is
  9559. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  9560. *
  9561. * @param {Number} index - The index.
  9562. * @return {String} The loop variable name.
  9563. */
  9564. getVarName( index ) {
  9565. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  9566. }
  9567. /**
  9568. * Returns properties about this node.
  9569. *
  9570. * @param {NodeBuilder} builder - The current node builder.
  9571. * @return {Object} The node properties.
  9572. */
  9573. getProperties( builder ) {
  9574. const properties = builder.getNodeProperties( this );
  9575. if ( properties.stackNode !== undefined ) return properties;
  9576. //
  9577. const inputs = {};
  9578. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  9579. const param = this.params[ i ];
  9580. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  9581. const type = ( param.isNode !== true && param.type ) || 'int';
  9582. inputs[ name ] = expression( name, type );
  9583. }
  9584. const stack = builder.addStack(); // TODO: cache() it
  9585. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  9586. properties.stackNode = stack;
  9587. builder.removeStack();
  9588. return properties;
  9589. }
  9590. /**
  9591. * This method is overwritten since the node type is inferred based on the loop configuration.
  9592. *
  9593. * @param {NodeBuilder} builder - The current node builder.
  9594. * @return {String} The node type.
  9595. */
  9596. getNodeType( builder ) {
  9597. const { returnsNode } = this.getProperties( builder );
  9598. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  9599. }
  9600. setup( builder ) {
  9601. // setup properties
  9602. this.getProperties( builder );
  9603. }
  9604. generate( builder ) {
  9605. const properties = this.getProperties( builder );
  9606. const params = this.params;
  9607. const stackNode = properties.stackNode;
  9608. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  9609. const param = params[ i ];
  9610. let start = null, end = null, name = null, type = null, condition = null, update = null;
  9611. if ( param.isNode ) {
  9612. type = 'int';
  9613. name = this.getVarName( i );
  9614. start = '0';
  9615. end = param.build( builder, type );
  9616. condition = '<';
  9617. } else {
  9618. type = param.type || 'int';
  9619. name = param.name || this.getVarName( i );
  9620. start = param.start;
  9621. end = param.end;
  9622. condition = param.condition;
  9623. update = param.update;
  9624. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  9625. else if ( start && start.isNode ) start = start.build( builder, type );
  9626. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  9627. else if ( end && end.isNode ) end = end.build( builder, type );
  9628. if ( start !== undefined && end === undefined ) {
  9629. start = start + ' - 1';
  9630. end = '0';
  9631. condition = '>=';
  9632. } else if ( end !== undefined && start === undefined ) {
  9633. start = '0';
  9634. condition = '<';
  9635. }
  9636. if ( condition === undefined ) {
  9637. if ( Number( start ) > Number( end ) ) {
  9638. condition = '>=';
  9639. } else {
  9640. condition = '<';
  9641. }
  9642. }
  9643. }
  9644. const internalParam = { start, end, condition };
  9645. //
  9646. const startSnippet = internalParam.start;
  9647. const endSnippet = internalParam.end;
  9648. let declarationSnippet = '';
  9649. let conditionalSnippet = '';
  9650. let updateSnippet = '';
  9651. if ( ! update ) {
  9652. if ( type === 'int' || type === 'uint' ) {
  9653. if ( condition.includes( '<' ) ) update = '++';
  9654. else update = '--';
  9655. } else {
  9656. if ( condition.includes( '<' ) ) update = '+= 1.';
  9657. else update = '-= 1.';
  9658. }
  9659. }
  9660. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  9661. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  9662. updateSnippet += name + ' ' + update;
  9663. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  9664. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  9665. }
  9666. const stackSnippet = stackNode.build( builder, 'void' );
  9667. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  9668. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  9669. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  9670. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  9671. }
  9672. builder.addFlowTab();
  9673. return returnsSnippet;
  9674. }
  9675. }
  9676. /**
  9677. * TSL function for creating a loop node.
  9678. *
  9679. * @function
  9680. * @param {...Any} params - A list of parameters.
  9681. * @returns {LoopNode}
  9682. */
  9683. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  9684. /**
  9685. * TSL function for creating a `Continue()` expression.
  9686. *
  9687. * @function
  9688. * @returns {ExpressionNode}
  9689. */
  9690. const Continue = () => expression( 'continue' ).append();
  9691. /**
  9692. * TSL function for creating a `Break()` expression.
  9693. *
  9694. * @function
  9695. * @returns {ExpressionNode}
  9696. */
  9697. const Break = () => expression( 'break' ).append();
  9698. //
  9699. const loop = ( ...params ) => { // @deprecated, r168
  9700. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  9701. return Loop( ...params );
  9702. };
  9703. /** @module MorphNode **/
  9704. const _morphTextures = /*@__PURE__*/ new WeakMap();
  9705. const _morphVec4 = /*@__PURE__*/ new Vector4();
  9706. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  9707. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  9708. const y = texelIndex.div( width );
  9709. const x = texelIndex.sub( y.mul( width ) );
  9710. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  9711. return bufferAttrib.mul( influence );
  9712. } );
  9713. function getEntry( geometry ) {
  9714. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  9715. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  9716. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  9717. // instead of using attributes, the WebGL 2 code path encodes morph targets
  9718. // into an array of data textures. Each layer represents a single morph target.
  9719. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  9720. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  9721. let entry = _morphTextures.get( geometry );
  9722. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  9723. if ( entry !== undefined ) entry.texture.dispose();
  9724. const morphTargets = geometry.morphAttributes.position || [];
  9725. const morphNormals = geometry.morphAttributes.normal || [];
  9726. const morphColors = geometry.morphAttributes.color || [];
  9727. let vertexDataCount = 0;
  9728. if ( hasMorphPosition === true ) vertexDataCount = 1;
  9729. if ( hasMorphNormals === true ) vertexDataCount = 2;
  9730. if ( hasMorphColors === true ) vertexDataCount = 3;
  9731. let width = geometry.attributes.position.count * vertexDataCount;
  9732. let height = 1;
  9733. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  9734. if ( width > maxTextureSize ) {
  9735. height = Math.ceil( width / maxTextureSize );
  9736. width = maxTextureSize;
  9737. }
  9738. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  9739. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  9740. bufferTexture.type = FloatType;
  9741. bufferTexture.needsUpdate = true;
  9742. // fill buffer
  9743. const vertexDataStride = vertexDataCount * 4;
  9744. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  9745. const morphTarget = morphTargets[ i ];
  9746. const morphNormal = morphNormals[ i ];
  9747. const morphColor = morphColors[ i ];
  9748. const offset = width * height * 4 * i;
  9749. for ( let j = 0; j < morphTarget.count; j ++ ) {
  9750. const stride = j * vertexDataStride;
  9751. if ( hasMorphPosition === true ) {
  9752. _morphVec4.fromBufferAttribute( morphTarget, j );
  9753. buffer[ offset + stride + 0 ] = _morphVec4.x;
  9754. buffer[ offset + stride + 1 ] = _morphVec4.y;
  9755. buffer[ offset + stride + 2 ] = _morphVec4.z;
  9756. buffer[ offset + stride + 3 ] = 0;
  9757. }
  9758. if ( hasMorphNormals === true ) {
  9759. _morphVec4.fromBufferAttribute( morphNormal, j );
  9760. buffer[ offset + stride + 4 ] = _morphVec4.x;
  9761. buffer[ offset + stride + 5 ] = _morphVec4.y;
  9762. buffer[ offset + stride + 6 ] = _morphVec4.z;
  9763. buffer[ offset + stride + 7 ] = 0;
  9764. }
  9765. if ( hasMorphColors === true ) {
  9766. _morphVec4.fromBufferAttribute( morphColor, j );
  9767. buffer[ offset + stride + 8 ] = _morphVec4.x;
  9768. buffer[ offset + stride + 9 ] = _morphVec4.y;
  9769. buffer[ offset + stride + 10 ] = _morphVec4.z;
  9770. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  9771. }
  9772. }
  9773. }
  9774. entry = {
  9775. count: morphTargetsCount,
  9776. texture: bufferTexture,
  9777. stride: vertexDataCount,
  9778. size: new Vector2( width, height )
  9779. };
  9780. _morphTextures.set( geometry, entry );
  9781. function disposeTexture() {
  9782. bufferTexture.dispose();
  9783. _morphTextures.delete( geometry );
  9784. geometry.removeEventListener( 'dispose', disposeTexture );
  9785. }
  9786. geometry.addEventListener( 'dispose', disposeTexture );
  9787. }
  9788. return entry;
  9789. }
  9790. /**
  9791. * This node implements the vertex transformation shader logic which is required
  9792. * for morph target animation.
  9793. *
  9794. * @augments Node
  9795. */
  9796. class MorphNode extends Node {
  9797. static get type() {
  9798. return 'MorphNode';
  9799. }
  9800. /**
  9801. * Constructs a new morph node.
  9802. *
  9803. * @param {Mesh} mesh - The mesh holding the morph targets.
  9804. */
  9805. constructor( mesh ) {
  9806. super( 'void' );
  9807. /**
  9808. * The mesh holding the morph targets.
  9809. *
  9810. * @type {Mesh}
  9811. */
  9812. this.mesh = mesh;
  9813. /**
  9814. * A uniform node which represents the morph base influence value.
  9815. *
  9816. * @type {UniformNode<float>}
  9817. */
  9818. this.morphBaseInfluence = uniform( 1 );
  9819. /**
  9820. * The update type overwritten since morph nodes are updated per object.
  9821. *
  9822. * @type {String}
  9823. */
  9824. this.updateType = NodeUpdateType.OBJECT;
  9825. }
  9826. /**
  9827. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  9828. *
  9829. * @param {NodeBuilder} builder - The current node builder.
  9830. */
  9831. setup( builder ) {
  9832. const { geometry } = builder;
  9833. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  9834. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  9835. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  9836. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  9837. // nodes
  9838. const { texture: bufferMap, stride, size } = getEntry( geometry );
  9839. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  9840. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  9841. const width = int( size.width );
  9842. Loop( morphTargetsCount, ( { i } ) => {
  9843. const influence = float( 0 ).toVar();
  9844. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  9845. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  9846. } else {
  9847. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  9848. }
  9849. if ( hasMorphPosition === true ) {
  9850. positionLocal.addAssign( getMorph( {
  9851. bufferMap,
  9852. influence,
  9853. stride,
  9854. width,
  9855. depth: i,
  9856. offset: int( 0 )
  9857. } ) );
  9858. }
  9859. if ( hasMorphNormals === true ) {
  9860. normalLocal.addAssign( getMorph( {
  9861. bufferMap,
  9862. influence,
  9863. stride,
  9864. width,
  9865. depth: i,
  9866. offset: int( 1 )
  9867. } ) );
  9868. }
  9869. } );
  9870. }
  9871. /**
  9872. * Updates the state of the morphed mesh by updating the base influence.
  9873. *
  9874. * @param {NodeFrame} frame - The current node frame.
  9875. */
  9876. update( /*frame*/ ) {
  9877. const morphBaseInfluence = this.morphBaseInfluence;
  9878. if ( this.mesh.geometry.morphTargetsRelative ) {
  9879. morphBaseInfluence.value = 1;
  9880. } else {
  9881. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  9882. }
  9883. }
  9884. }
  9885. /**
  9886. * TSL function for creating a morph node.
  9887. *
  9888. * @function
  9889. * @param {Mesh} mesh - The mesh holding the morph targets.
  9890. * @returns {MorphNode}
  9891. */
  9892. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  9893. /**
  9894. * Base class for lighting nodes.
  9895. *
  9896. * @augments Node
  9897. */
  9898. class LightingNode extends Node {
  9899. static get type() {
  9900. return 'LightingNode';
  9901. }
  9902. /**
  9903. * Constructs a new lighting node.
  9904. */
  9905. constructor() {
  9906. super( 'vec3' );
  9907. /**
  9908. * This flag can be used for type testing.
  9909. *
  9910. * @type {Boolean}
  9911. * @readonly
  9912. * @default true
  9913. */
  9914. this.isLightingNode = true;
  9915. }
  9916. }
  9917. /**
  9918. * A generic class that can be used by nodes which contribute
  9919. * ambient occlusion to the scene. E.g. an ambient occlusion map
  9920. * node can be used as input for this module. Used in {@link NodeMaterial}.
  9921. *
  9922. * @augments LightingNode
  9923. */
  9924. class AONode extends LightingNode {
  9925. static get type() {
  9926. return 'AONode';
  9927. }
  9928. /**
  9929. * Constructs a new AO node.
  9930. *
  9931. * @param {Node<float>?} [aoNode=null] - The ambient occlusion node.
  9932. */
  9933. constructor( aoNode = null ) {
  9934. super();
  9935. /**
  9936. * The ambient occlusion node.
  9937. *
  9938. * @type {Node<float>?}
  9939. * @default null
  9940. */
  9941. this.aoNode = aoNode;
  9942. }
  9943. setup( builder ) {
  9944. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  9945. }
  9946. }
  9947. /**
  9948. * `LightingContextNode` represents an extension of the {@link module:ContextNode~ContextNode} module
  9949. * by adding lighting specific context data. It represents the runtime context of
  9950. * {@link LightsNode}.
  9951. *
  9952. * @augments ContextNode
  9953. */
  9954. class LightingContextNode extends ContextNode {
  9955. static get type() {
  9956. return 'LightingContextNode';
  9957. }
  9958. /**
  9959. * Constructs a new lighting context node.
  9960. *
  9961. * @param {LightsNode} node - The lights node.
  9962. * @param {LightingModel?} [lightingModel=null] - The current lighting model.
  9963. * @param {Node<vec3>?} [backdropNode=null] - A backdrop node.
  9964. * @param {Node<float>?} [backdropAlphaNode=null] - A backdrop alpha node.
  9965. */
  9966. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  9967. super( node );
  9968. /**
  9969. * The current lighting model.
  9970. *
  9971. * @type {LightingModel?}
  9972. * @default null
  9973. */
  9974. this.lightingModel = lightingModel;
  9975. /**
  9976. * A backdrop node.
  9977. *
  9978. * @type {Node<vec3>?}
  9979. * @default null
  9980. */
  9981. this.backdropNode = backdropNode;
  9982. /**
  9983. * A backdrop alpha node.
  9984. *
  9985. * @type {Node<float>?}
  9986. * @default null
  9987. */
  9988. this.backdropAlphaNode = backdropAlphaNode;
  9989. this._value = null;
  9990. }
  9991. /**
  9992. * Returns a lighting context object.
  9993. *
  9994. * @return {{
  9995. * radiance: Node<vec3>,
  9996. * irradiance: Node<vec3>,
  9997. * iblIrradiance: Node<vec3>,
  9998. * ambientOcclusion: Node<float>,
  9999. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  10000. * backdrop: Node<vec3>,
  10001. * backdropAlpha: Node<float>
  10002. * }} The lighting context object.
  10003. */
  10004. getContext() {
  10005. const { backdropNode, backdropAlphaNode } = this;
  10006. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  10007. directSpecular = vec3().toVar( 'directSpecular' ),
  10008. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  10009. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  10010. const reflectedLight = {
  10011. directDiffuse,
  10012. directSpecular,
  10013. indirectDiffuse,
  10014. indirectSpecular
  10015. };
  10016. const context = {
  10017. radiance: vec3().toVar( 'radiance' ),
  10018. irradiance: vec3().toVar( 'irradiance' ),
  10019. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  10020. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  10021. reflectedLight,
  10022. backdrop: backdropNode,
  10023. backdropAlpha: backdropAlphaNode
  10024. };
  10025. return context;
  10026. }
  10027. setup( builder ) {
  10028. this.value = this._value || ( this._value = this.getContext() );
  10029. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  10030. return super.setup( builder );
  10031. }
  10032. }
  10033. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  10034. /**
  10035. * A generic class that can be used by nodes which contribute
  10036. * irradiance to the scene. E.g. a light map node can be used
  10037. * as input for this module. Used in {@link NodeMaterial}.
  10038. *
  10039. * @augments LightingNode
  10040. */
  10041. class IrradianceNode extends LightingNode {
  10042. static get type() {
  10043. return 'IrradianceNode';
  10044. }
  10045. /**
  10046. * Constructs a new irradiance node.
  10047. *
  10048. * @param {Node<vec3>} node - A node contributing irradiance.
  10049. */
  10050. constructor( node ) {
  10051. super();
  10052. /**
  10053. * A node contributing irradiance.
  10054. *
  10055. * @type {Node<vec3>}
  10056. */
  10057. this.node = node;
  10058. }
  10059. setup( builder ) {
  10060. builder.context.irradiance.addAssign( this.node );
  10061. }
  10062. }
  10063. /** @module ScreenNode **/
  10064. let screenSizeVec, viewportVec;
  10065. /**
  10066. * This node provides a collection of screen related metrics.
  10067. * Depending on {@link module:ScreenNode~ScreenNode#scope}, the nodes can represent
  10068. * resolution or viewport data as well as fragment or uv coordinates.
  10069. *
  10070. * @augments Node
  10071. */
  10072. class ScreenNode extends Node {
  10073. static get type() {
  10074. return 'ScreenNode';
  10075. }
  10076. /**
  10077. * Constructs a new screen node.
  10078. *
  10079. * @param {('coordinate'|'viewport'|'size'|'uv')} scope - The node's scope.
  10080. */
  10081. constructor( scope ) {
  10082. super();
  10083. /**
  10084. * The node represents different metric depending on which scope is selected.
  10085. *
  10086. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  10087. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  10088. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  10089. * - `ScreenNode.UV`: Normalized coordinates.
  10090. *
  10091. * @type {('coordinate'|'viewport'|'size'|'uv')}
  10092. */
  10093. this.scope = scope;
  10094. /**
  10095. * This flag can be used for type testing.
  10096. *
  10097. * @type {Boolean}
  10098. * @readonly
  10099. * @default true
  10100. */
  10101. this.isViewportNode = true;
  10102. }
  10103. /**
  10104. * This method is overwritten since the node type depends on the selected scope.
  10105. *
  10106. * @return {('vec2'|'vec4')} The node type.
  10107. */
  10108. getNodeType() {
  10109. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  10110. else return 'vec2';
  10111. }
  10112. /**
  10113. * This method is overwritten since the node's update type depends on the selected scope.
  10114. *
  10115. * @return {NodeUpdateType} The update type.
  10116. */
  10117. getUpdateType() {
  10118. let updateType = NodeUpdateType.NONE;
  10119. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  10120. updateType = NodeUpdateType.RENDER;
  10121. }
  10122. this.updateType = updateType;
  10123. return updateType;
  10124. }
  10125. /**
  10126. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  10127. * from the current renderer.
  10128. *
  10129. * @param {NodeFrame} frame - A reference to the current node frame.
  10130. */
  10131. update( { renderer } ) {
  10132. const renderTarget = renderer.getRenderTarget();
  10133. if ( this.scope === ScreenNode.VIEWPORT ) {
  10134. if ( renderTarget !== null ) {
  10135. viewportVec.copy( renderTarget.viewport );
  10136. } else {
  10137. renderer.getViewport( viewportVec );
  10138. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  10139. }
  10140. } else {
  10141. if ( renderTarget !== null ) {
  10142. screenSizeVec.width = renderTarget.width;
  10143. screenSizeVec.height = renderTarget.height;
  10144. } else {
  10145. renderer.getDrawingBufferSize( screenSizeVec );
  10146. }
  10147. }
  10148. }
  10149. setup( /*builder*/ ) {
  10150. const scope = this.scope;
  10151. let output = null;
  10152. if ( scope === ScreenNode.SIZE ) {
  10153. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  10154. } else if ( scope === ScreenNode.VIEWPORT ) {
  10155. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  10156. } else {
  10157. output = vec2( screenCoordinate.div( screenSize ) );
  10158. }
  10159. return output;
  10160. }
  10161. generate( builder ) {
  10162. if ( this.scope === ScreenNode.COORDINATE ) {
  10163. let coord = builder.getFragCoord();
  10164. if ( builder.isFlipY() ) {
  10165. // follow webgpu standards
  10166. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  10167. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  10168. }
  10169. return coord;
  10170. }
  10171. return super.generate( builder );
  10172. }
  10173. }
  10174. ScreenNode.COORDINATE = 'coordinate';
  10175. ScreenNode.VIEWPORT = 'viewport';
  10176. ScreenNode.SIZE = 'size';
  10177. ScreenNode.UV = 'uv';
  10178. // Screen
  10179. /**
  10180. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  10181. *
  10182. * @type {ScreenNode<vec2>}
  10183. */
  10184. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  10185. /**
  10186. * TSL object that represents the screen resolution in physical pixel units.
  10187. *
  10188. * @type {ScreenNode<vec2>}
  10189. */
  10190. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  10191. /**
  10192. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  10193. *
  10194. * @type {ScreenNode<vec2>}
  10195. */
  10196. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  10197. // Viewport
  10198. /**
  10199. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  10200. *
  10201. * @type {ScreenNode<vec4>}
  10202. */
  10203. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  10204. /**
  10205. * TSL object that represents the viewport resolution in physical pixel units.
  10206. *
  10207. * @type {ScreenNode<vec2>}
  10208. */
  10209. const viewportSize = viewport.zw;
  10210. /**
  10211. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  10212. *
  10213. * @type {ScreenNode<vec2>}
  10214. */
  10215. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  10216. /**
  10217. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  10218. *
  10219. * @type {ScreenNode<vec2>}
  10220. */
  10221. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  10222. // Deprecated
  10223. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  10224. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  10225. return screenSize;
  10226. }, 'vec2' ).once() )();
  10227. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  10228. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  10229. return screenUV;
  10230. }, 'vec2' ).once() )();
  10231. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  10232. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  10233. return screenUV.flipY();
  10234. }, 'vec2' ).once() )();
  10235. /** @module ViewportTextureNode **/
  10236. const _size$4 = /*@__PURE__*/ new Vector2();
  10237. /**
  10238. * A special type of texture node which represents the data of the current viewport
  10239. * as a texture. The module extracts data from the current bound framebuffer with
  10240. * a copy operation so no extra render pass is required to produce the texture data
  10241. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  10242. * variety of effects like refractive or transmissive materials.
  10243. *
  10244. * @augments module:TextureNode~TextureNode
  10245. */
  10246. class ViewportTextureNode extends TextureNode {
  10247. static get type() {
  10248. return 'ViewportTextureNode';
  10249. }
  10250. /**
  10251. * Constructs a new viewport texture node.
  10252. *
  10253. * @param {Node} [uvNode=screenUV] - The uv node.
  10254. * @param {Node?} [levelNode=null] - The level node.
  10255. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10256. */
  10257. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  10258. if ( framebufferTexture === null ) {
  10259. framebufferTexture = new FramebufferTexture();
  10260. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  10261. }
  10262. super( framebufferTexture, uvNode, levelNode );
  10263. /**
  10264. * Whether to generate mipmaps or not.
  10265. *
  10266. * @type {Boolean}
  10267. * @default false
  10268. */
  10269. this.generateMipmaps = false;
  10270. /**
  10271. * This flag can be used for type testing.
  10272. *
  10273. * @type {Boolean}
  10274. * @readonly
  10275. * @default true
  10276. */
  10277. this.isOutputTextureNode = true;
  10278. /**
  10279. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  10280. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  10281. *
  10282. * @type {String}
  10283. * @default 'frame'
  10284. */
  10285. this.updateBeforeType = NodeUpdateType.FRAME;
  10286. }
  10287. updateBefore( frame ) {
  10288. const renderer = frame.renderer;
  10289. renderer.getDrawingBufferSize( _size$4 );
  10290. //
  10291. const framebufferTexture = this.value;
  10292. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  10293. framebufferTexture.image.width = _size$4.width;
  10294. framebufferTexture.image.height = _size$4.height;
  10295. framebufferTexture.needsUpdate = true;
  10296. }
  10297. //
  10298. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  10299. framebufferTexture.generateMipmaps = this.generateMipmaps;
  10300. renderer.copyFramebufferToTexture( framebufferTexture );
  10301. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  10302. }
  10303. clone() {
  10304. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  10305. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  10306. return viewportTextureNode;
  10307. }
  10308. }
  10309. /**
  10310. * TSL function for creating a viewport texture node.
  10311. *
  10312. * @function
  10313. * @param {Node} [uvNode=screenUV] - The uv node.
  10314. * @param {Node?} [levelNode=null] - The level node.
  10315. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10316. * @returns {ViewportTextureNode}
  10317. */
  10318. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  10319. /**
  10320. * TSL function for creating a viewport texture node with enabled mipmap generation.
  10321. *
  10322. * @function
  10323. * @param {Node} [uvNode=screenUV] - The uv node.
  10324. * @param {Node?} [levelNode=null] - The level node.
  10325. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10326. * @returns {ViewportTextureNode}
  10327. */
  10328. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  10329. /** @module ViewportDepthTextureNode **/
  10330. let sharedDepthbuffer = null;
  10331. /**
  10332. * Represents the depth of the current viewport as a texture. This module
  10333. * can be used in combination with viewport texture to achieve effects
  10334. * that require depth evaluation.
  10335. *
  10336. * @augments module:ViewportTextureNode~ViewportTextureNode
  10337. */
  10338. class ViewportDepthTextureNode extends ViewportTextureNode {
  10339. static get type() {
  10340. return 'ViewportDepthTextureNode';
  10341. }
  10342. /**
  10343. * Constructs a new viewport depth texture node.
  10344. *
  10345. * @param {Node} [uvNode=screenUV] - The uv node.
  10346. * @param {Node?} [levelNode=null] - The level node.
  10347. */
  10348. constructor( uvNode = screenUV, levelNode = null ) {
  10349. if ( sharedDepthbuffer === null ) {
  10350. sharedDepthbuffer = new DepthTexture();
  10351. }
  10352. super( uvNode, levelNode, sharedDepthbuffer );
  10353. }
  10354. }
  10355. /**
  10356. * TSL function for a viewport depth texture node.
  10357. *
  10358. * @function
  10359. * @param {Node} [uvNode=screenUV] - The uv node.
  10360. * @param {Node?} [levelNode=null] - The level node.
  10361. * @returns {ViewportDepthTextureNode}
  10362. */
  10363. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  10364. /** @module ViewportDepthNode **/
  10365. /**
  10366. * This node offers a collection of features in context of the depth logic in the fragment shader.
  10367. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  10368. * fragment or for depth evaluation purposes.
  10369. *
  10370. * @augments Node
  10371. */
  10372. class ViewportDepthNode extends Node {
  10373. static get type() {
  10374. return 'ViewportDepthNode';
  10375. }
  10376. /**
  10377. * Constructs a new viewport depth node.
  10378. *
  10379. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  10380. * @param {Node?} [valueNode=null] - The value node.
  10381. */
  10382. constructor( scope, valueNode = null ) {
  10383. super( 'float' );
  10384. /**
  10385. * The node behaves differently depending on which scope is selected.
  10386. *
  10387. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  10388. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  10389. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  10390. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  10391. *
  10392. * @type {('depth'|'depthBase'|'linearDepth')}
  10393. */
  10394. this.scope = scope;
  10395. /**
  10396. * Can be used to define a custom depth value.
  10397. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  10398. *
  10399. * @type {Node?}
  10400. * @default null
  10401. */
  10402. this.valueNode = valueNode;
  10403. /**
  10404. * This flag can be used for type testing.
  10405. *
  10406. * @type {Boolean}
  10407. * @readonly
  10408. * @default true
  10409. */
  10410. this.isViewportDepthNode = true;
  10411. }
  10412. generate( builder ) {
  10413. const { scope } = this;
  10414. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  10415. return builder.getFragDepth();
  10416. }
  10417. return super.generate( builder );
  10418. }
  10419. setup( { camera } ) {
  10420. const { scope } = this;
  10421. const value = this.valueNode;
  10422. let node = null;
  10423. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  10424. if ( value !== null ) {
  10425. node = depthBase().assign( value );
  10426. }
  10427. } else if ( scope === ViewportDepthNode.DEPTH ) {
  10428. if ( camera.isPerspectiveCamera ) {
  10429. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  10430. } else {
  10431. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  10432. }
  10433. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  10434. if ( value !== null ) {
  10435. if ( camera.isPerspectiveCamera ) {
  10436. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  10437. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  10438. } else {
  10439. node = value;
  10440. }
  10441. } else {
  10442. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  10443. }
  10444. }
  10445. return node;
  10446. }
  10447. }
  10448. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  10449. ViewportDepthNode.DEPTH = 'depth';
  10450. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  10451. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  10452. /**
  10453. * TSL function for converting a viewZ value to an orthographic depth value.
  10454. *
  10455. * @function
  10456. * @param {Node<float>} viewZ - The viewZ node.
  10457. * @param {Node<float>} near - The camera's near value.
  10458. * @param {Node<float>} far - The camera's far value.
  10459. * @returns {Node<float>}
  10460. */
  10461. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  10462. /**
  10463. * TSL function for converting an orthographic depth value to a viewZ value.
  10464. *
  10465. * @function
  10466. * @param {Node<float>} depth - The orthographic depth.
  10467. * @param {Node<float>} near - The camera's near value.
  10468. * @param {Node<float>} far - The camera's far value.
  10469. * @returns {Node<float>}
  10470. */
  10471. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  10472. /**
  10473. * TSL function for converting a viewZ value to a perspective depth value.
  10474. *
  10475. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  10476. *
  10477. * @function
  10478. * @param {Node<float>} viewZ - The viewZ node.
  10479. * @param {Node<float>} near - The camera's near value.
  10480. * @param {Node<float>} far - The camera's far value.
  10481. * @returns {Node<float>}
  10482. */
  10483. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  10484. /**
  10485. * TSL function for converting a perspective depth value to a viewZ value.
  10486. *
  10487. * @function
  10488. * @param {Node<float>} depth - The perspective depth.
  10489. * @param {Node<float>} near - The camera's near value.
  10490. * @param {Node<float>} far - The camera's far value.
  10491. * @returns {Node<float>}
  10492. */
  10493. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  10494. /**
  10495. * TSL function for converting a viewZ value to a logarithmic depth value.
  10496. *
  10497. * @function
  10498. * @param {Node<float>} viewZ - The viewZ node.
  10499. * @param {Node<float>} near - The camera's near value.
  10500. * @param {Node<float>} far - The camera's far value.
  10501. * @returns {Node<float>}
  10502. */
  10503. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  10504. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  10505. // The final logarithmic depth formula used here is adapted from one described in an
  10506. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  10507. // which was an improvement upon an earlier formula one described in an
  10508. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  10509. // Ulrich's formula is the following:
  10510. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  10511. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  10512. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  10513. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  10514. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  10515. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  10516. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  10517. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  10518. // be used, and ultimately Ulrich's "near plane" version was chosen.
  10519. // Outerra eventually made another improvement to their original "C-constant" variant,
  10520. // but it still does not incorporate the camera near plane (for this version,
  10521. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  10522. // Here we make 4 changes to Ulrich's formula:
  10523. // 1. Clamp the camera near plane so we don't divide by 0.
  10524. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  10525. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  10526. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  10527. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  10528. // so we do the same here, hence the 'viewZ.negate()' call.
  10529. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  10530. near = near.max( 1e-6 ).toVar();
  10531. const numerator = log2( viewZ.negate().div( near ) );
  10532. const denominator = log2( far.div( near ) );
  10533. return numerator.div( denominator );
  10534. };
  10535. /**
  10536. * TSL function for converting a logarithmic depth value to a viewZ value.
  10537. *
  10538. * @function
  10539. * @param {Node<float>} depth - The logarithmic depth.
  10540. * @param {Node<float>} near - The camera's near value.
  10541. * @param {Node<float>} far - The camera's far value.
  10542. * @returns {Node<float>}
  10543. */
  10544. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  10545. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  10546. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  10547. // a negative viewZ).
  10548. const exponent = depth.mul( log( far.div( near ) ) );
  10549. return float( Math.E ).pow( exponent ).mul( near ).negate();
  10550. };
  10551. /**
  10552. * TSL function for defining a value for the current fragment's depth.
  10553. *
  10554. * @function
  10555. * @param {Node<float>} value - The depth value to set.
  10556. * @returns {ViewportDepthNode<float>}
  10557. */
  10558. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  10559. /**
  10560. * TSL object that represents the depth value for the current fragment.
  10561. *
  10562. * @type {ViewportDepthNode}
  10563. */
  10564. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  10565. /**
  10566. * TSL function for converting a perspective depth value to linear depth.
  10567. *
  10568. * @function
  10569. * @param {Node<float>} value - The perspective depth.
  10570. * @returns {ViewportDepthNode<float>}
  10571. */
  10572. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  10573. /**
  10574. * TSL object that represents the linear (orthographic) depth value of the current fragment
  10575. *
  10576. * @type {ViewportDepthNode}
  10577. */
  10578. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  10579. depth.assign = ( value ) => depthBase( value );
  10580. /** @module BuiltinNode **/
  10581. /**
  10582. * The node allows to set values for built-in shader variables. That is
  10583. * required for features like hardware-accelerated vertex clipping.
  10584. *
  10585. * @augments Node
  10586. */
  10587. class BuiltinNode extends Node {
  10588. /**
  10589. * Constructs a new builtin node.
  10590. *
  10591. * @param {String} name - The name of the built-in shader variable.
  10592. */
  10593. constructor( name ) {
  10594. super( 'float' );
  10595. /**
  10596. * The name of the built-in shader variable.
  10597. *
  10598. * @type {String}
  10599. */
  10600. this.name = name;
  10601. /**
  10602. * This flag can be used for type testing.
  10603. *
  10604. * @type {Boolean}
  10605. * @readonly
  10606. * @default true
  10607. */
  10608. this.isBuiltinNode = true;
  10609. }
  10610. /**
  10611. * Generates the code snippet of the builtin node.
  10612. *
  10613. * @param {NodeBuilder} builder - The current node builder.
  10614. * @return {String} The generated code snippet.
  10615. */
  10616. generate( /* builder */ ) {
  10617. return this.name;
  10618. }
  10619. }
  10620. /**
  10621. * TSL function for creating a builtin node.
  10622. *
  10623. * @function
  10624. * @param {String} name - The name of the built-in shader variable.
  10625. * @returns {BuiltinNode}
  10626. */
  10627. const builtin = nodeProxy( BuiltinNode );
  10628. /** @module ClippingNode **/
  10629. /**
  10630. * ```
  10631. * This node is used in {@link NodeMaterial} to setup the clipping
  10632. * which can happen hardware-accelerated (if supported) and optionally
  10633. * use alpha-to-coverage for anti-aliasing clipped edges.
  10634. * ```
  10635. * @augments Node
  10636. */
  10637. class ClippingNode extends Node {
  10638. static get type() {
  10639. return 'ClippingNode';
  10640. }
  10641. /**
  10642. * Constructs a new clipping node.
  10643. *
  10644. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  10645. * the selected scope influences the behavior of the node and what type of code is generated.
  10646. */
  10647. constructor( scope = ClippingNode.DEFAULT ) {
  10648. super();
  10649. /**
  10650. * The node's scope. Similar to other nodes, the selected scope influences
  10651. * the behavior of the node and what type of code is generated.
  10652. *
  10653. * @type {('default'|'hardware'|'alphaToCoverage')}
  10654. */
  10655. this.scope = scope;
  10656. }
  10657. /**
  10658. * Setups the node depending on the selected scope.
  10659. *
  10660. * @param {NodeBuilder} builder - The current node builder.
  10661. * @return {Node} The result node.
  10662. */
  10663. setup( builder ) {
  10664. super.setup( builder );
  10665. const clippingContext = builder.clippingContext;
  10666. const { intersectionPlanes, unionPlanes } = clippingContext;
  10667. this.hardwareClipping = builder.material.hardwareClipping;
  10668. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  10669. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  10670. } else if ( this.scope === ClippingNode.HARDWARE ) {
  10671. return this.setupHardwareClipping( unionPlanes, builder );
  10672. } else {
  10673. return this.setupDefault( intersectionPlanes, unionPlanes );
  10674. }
  10675. }
  10676. /**
  10677. * Setups alpha to coverage.
  10678. *
  10679. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  10680. * @param {Array<Vector4>} unionPlanes - The union planes.
  10681. * @return {Node} The result node.
  10682. */
  10683. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  10684. return Fn( () => {
  10685. const distanceToPlane = float().toVar( 'distanceToPlane' );
  10686. const distanceGradient = float().toVar( 'distanceToGradient' );
  10687. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  10688. const numUnionPlanes = unionPlanes.length;
  10689. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  10690. const clippingPlanes = uniformArray( unionPlanes );
  10691. Loop( numUnionPlanes, ( { i } ) => {
  10692. const plane = clippingPlanes.element( i );
  10693. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  10694. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  10695. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  10696. } );
  10697. }
  10698. const numIntersectionPlanes = intersectionPlanes.length;
  10699. if ( numIntersectionPlanes > 0 ) {
  10700. const clippingPlanes = uniformArray( intersectionPlanes );
  10701. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  10702. Loop( numIntersectionPlanes, ( { i } ) => {
  10703. const plane = clippingPlanes.element( i );
  10704. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  10705. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  10706. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  10707. } );
  10708. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  10709. }
  10710. diffuseColor.a.mulAssign( clipOpacity );
  10711. diffuseColor.a.equal( 0.0 ).discard();
  10712. } )();
  10713. }
  10714. /**
  10715. * Setups the default clipping.
  10716. *
  10717. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  10718. * @param {Array<Vector4>} unionPlanes - The union planes.
  10719. * @return {Node} The result node.
  10720. */
  10721. setupDefault( intersectionPlanes, unionPlanes ) {
  10722. return Fn( () => {
  10723. const numUnionPlanes = unionPlanes.length;
  10724. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  10725. const clippingPlanes = uniformArray( unionPlanes );
  10726. Loop( numUnionPlanes, ( { i } ) => {
  10727. const plane = clippingPlanes.element( i );
  10728. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  10729. } );
  10730. }
  10731. const numIntersectionPlanes = intersectionPlanes.length;
  10732. if ( numIntersectionPlanes > 0 ) {
  10733. const clippingPlanes = uniformArray( intersectionPlanes );
  10734. const clipped = bool( true ).toVar( 'clipped' );
  10735. Loop( numIntersectionPlanes, ( { i } ) => {
  10736. const plane = clippingPlanes.element( i );
  10737. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  10738. } );
  10739. clipped.discard();
  10740. }
  10741. } )();
  10742. }
  10743. /**
  10744. * Setups hardware clipping.
  10745. *
  10746. * @param {Array<Vector4>} unionPlanes - The union planes.
  10747. * @param {NodeBuilder} builder - The current node builder.
  10748. * @return {Node} The result node.
  10749. */
  10750. setupHardwareClipping( unionPlanes, builder ) {
  10751. const numUnionPlanes = unionPlanes.length;
  10752. builder.enableHardwareClipping( numUnionPlanes );
  10753. return Fn( () => {
  10754. const clippingPlanes = uniformArray( unionPlanes );
  10755. const hw_clip_distances = builtin( builder.getClipDistance() );
  10756. Loop( numUnionPlanes, ( { i } ) => {
  10757. const plane = clippingPlanes.element( i );
  10758. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  10759. hw_clip_distances.element( i ).assign( distance );
  10760. } );
  10761. } )();
  10762. }
  10763. }
  10764. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  10765. ClippingNode.DEFAULT = 'default';
  10766. ClippingNode.HARDWARE = 'hardware';
  10767. /**
  10768. * TSL function for setting up the default clipping logic.
  10769. *
  10770. * @function
  10771. * @returns {ClippingNode}
  10772. */
  10773. const clipping = () => nodeObject( new ClippingNode() );
  10774. /**
  10775. * TSL function for setting up alpha to coverage.
  10776. *
  10777. * @function
  10778. * @returns {ClippingNode}
  10779. */
  10780. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  10781. /**
  10782. * TSL function for setting up hardware-based clipping.
  10783. *
  10784. * @function
  10785. * @returns {ClippingNode}
  10786. */
  10787. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  10788. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  10789. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  10790. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  10791. 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 ) ) ) ) ) );
  10792. } );
  10793. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  10794. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  10795. } );
  10796. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  10797. // Find the discretized derivatives of our coordinates
  10798. const maxDeriv = max$1(
  10799. length( dFdx( position.xyz ) ),
  10800. length( dFdy( position.xyz ) )
  10801. );
  10802. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  10803. // Find two nearest log-discretized noise scales
  10804. const pixScales = vec2(
  10805. exp2( floor( log2( pixScale ) ) ),
  10806. exp2( ceil( log2( pixScale ) ) )
  10807. );
  10808. // Compute alpha thresholds at our two noise scales
  10809. const alpha = vec2(
  10810. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  10811. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  10812. );
  10813. // Factor to interpolate lerp with
  10814. const lerpFactor = fract( log2( pixScale ) );
  10815. // Interpolate alpha threshold from noise at two scales
  10816. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  10817. // Pass into CDF to compute uniformly distrib threshold
  10818. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  10819. const cases = vec3(
  10820. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  10821. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  10822. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  10823. // Find our final, uniformly distributed alpha threshold (ατ)
  10824. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  10825. // Avoids ατ == 0. Could also do ατ =1-ατ
  10826. return clamp( threshold, 1.0e-6, 1.0 );
  10827. } ).setLayout( {
  10828. name: 'getAlphaHashThreshold',
  10829. type: 'float',
  10830. inputs: [
  10831. { name: 'position', type: 'vec3' }
  10832. ]
  10833. } );
  10834. /**
  10835. * Base class for all node materials.
  10836. *
  10837. * @augments Material
  10838. */
  10839. class NodeMaterial extends Material {
  10840. static get type() {
  10841. return 'NodeMaterial';
  10842. }
  10843. /**
  10844. * Represents the type of the node material.
  10845. *
  10846. * @type {String}
  10847. */
  10848. get type() {
  10849. return this.constructor.type;
  10850. }
  10851. set type( _value ) { /* */ }
  10852. /**
  10853. * Constructs a new node material.
  10854. */
  10855. constructor() {
  10856. super();
  10857. /**
  10858. * This flag can be used for type testing.
  10859. *
  10860. * @type {Boolean}
  10861. * @readonly
  10862. * @default true
  10863. */
  10864. this.isNodeMaterial = true;
  10865. /**
  10866. * Whether this material is affected by fog or not.
  10867. *
  10868. * @type {Boolean}
  10869. * @default true
  10870. */
  10871. this.fog = true;
  10872. /**
  10873. * Whether this material is affected by lights or not.
  10874. *
  10875. * @type {Boolean}
  10876. * @default false
  10877. */
  10878. this.lights = false;
  10879. /**
  10880. * Whether this material uses hardware clipping or not.
  10881. * This property is managed by the engine and should not be
  10882. * modified by apps.
  10883. *
  10884. * @type {Boolean}
  10885. * @default false
  10886. */
  10887. this.hardwareClipping = false;
  10888. /**
  10889. * Node materials which set their `lights` property to `true`
  10890. * are affected by all lights of the scene. Sometimes selective
  10891. * lighting is wanted which means only _some_ lights in the scene
  10892. * affect a material. This can be achieved by creating an instance
  10893. * of {@link module:LightsNode~LightsNode} with a list of selective
  10894. * lights and assign the node to this property.
  10895. *
  10896. * ```js
  10897. * const customLightsNode = lights( [ light1, light2 ] );
  10898. * material.lightsNode = customLightsNode;
  10899. * ```
  10900. *
  10901. * @type {LightsNode?}
  10902. * @default null
  10903. */
  10904. this.lightsNode = null;
  10905. /**
  10906. * The environment of node materials can be defined by an environment
  10907. * map assigned to the `envMap` property or by `Scene.environment`
  10908. * if the node material is a PBR material. This node property allows to overwrite
  10909. * the default behavior and define the environment with a custom node.
  10910. *
  10911. * ```js
  10912. * material.envNode = pmremTexture( renderTarget.texture );
  10913. * ```
  10914. *
  10915. * @type {Node<vec3>?}
  10916. * @default null
  10917. */
  10918. this.envNode = null;
  10919. /**
  10920. * The lighting of node materials might be influenced by ambient occlusion.
  10921. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  10922. * and the respective `aoMapIntensity`. This node property allows to overwrite
  10923. * the default and define the ambient occlusion with a custom node instead.
  10924. *
  10925. * If you don't want to overwrite the diffuse color but modify the existing
  10926. * values instead, use {@link module:MaterialNode.materialAO}.
  10927. *
  10928. * @type {Node<float>?}
  10929. * @default null
  10930. */
  10931. this.aoNode = null;
  10932. /**
  10933. * The diffuse color of node materials is by default inferred from the
  10934. * `color` and `map` properties. This node property allows to overwrite the default
  10935. * and define the diffuse color with a node instead.
  10936. *
  10937. * ```js
  10938. * material.colorNode = color( 0xff0000 ); // define red color
  10939. * ```
  10940. *
  10941. * If you don't want to overwrite the diffuse color but modify the existing
  10942. * values instead, use {@link module:MaterialNode.materialColor}.
  10943. *
  10944. * ```js
  10945. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  10946. * ```
  10947. *
  10948. * @type {Node<vec3>?}
  10949. * @default null
  10950. */
  10951. this.colorNode = null;
  10952. /**
  10953. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  10954. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  10955. * and define the normals with a node instead.
  10956. *
  10957. * If you don't want to overwrite the normals but modify the existing values instead,
  10958. * use {@link module:MaterialNode.materialNormal}.
  10959. *
  10960. * @type {Node<vec3>?}
  10961. * @default null
  10962. */
  10963. this.normalNode = null;
  10964. /**
  10965. * The opacity of node materials is by default inferred from the `opacity`
  10966. * and `alphaMap` properties. This node property allows to overwrite the default
  10967. * and define the opacity with a node instead.
  10968. *
  10969. * If you don't want to overwrite the normals but modify the existing
  10970. * value instead, use {@link module:MaterialNode.materialOpacity}.
  10971. *
  10972. * @type {Node<float>?}
  10973. * @default null
  10974. */
  10975. this.opacityNode = null;
  10976. /**
  10977. * This node can be used to to implement a variety of filter-like effects. The idea is
  10978. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  10979. * to create an arbitrary effect and then assign the node composition to this property.
  10980. * Everything behind the object using this material will now be affected by a filter.
  10981. *
  10982. * ```js
  10983. * const material = new NodeMaterial()
  10984. * material.transparent = true;
  10985. *
  10986. * // everything behind the object will be monochromatic
  10987. * material.backdropNode = viewportSharedTexture().rgb.saturation( 0 );
  10988. * ```
  10989. *
  10990. * Backdrop computations are part of the lighting so only lit materials can use this property.
  10991. *
  10992. * @type {Node<vec3>?}
  10993. * @default null
  10994. */
  10995. this.backdropNode = null;
  10996. /**
  10997. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  10998. *
  10999. * @type {Node<float>?}
  11000. * @default null
  11001. */
  11002. this.backdropAlphaNode = null;
  11003. /**
  11004. * The alpha test of node materials is by default inferred from the `alphaTest`
  11005. * property. This node property allows to overwrite the default and define the
  11006. * alpha test with a node instead.
  11007. *
  11008. * If you don't want to overwrite the alpha test but modify the existing
  11009. * value instead, use {@link module:MaterialNode.materialAlphaTest}.
  11010. *
  11011. * @type {Node<float>?}
  11012. * @default null
  11013. */
  11014. this.alphaTestNode = null;
  11015. /**
  11016. * The local vertex positions are computed based on multiple factors like the
  11017. * attribute data, morphing or skinning. This node property allows to overwrite
  11018. * the default and define local vertex positions with nodes instead.
  11019. *
  11020. * If you don't want to overwrite the vertex positions but modify the existing
  11021. * values instead, use {@link module:Position.positionLocal}.
  11022. *
  11023. *```js
  11024. * material.positionNode = positionLocal.add( displace );
  11025. * ```
  11026. *
  11027. * @type {Node<vec3>?}
  11028. * @default null
  11029. */
  11030. this.positionNode = null;
  11031. /**
  11032. * This node property is intended for logic which modifies geometry data once or per animation step.
  11033. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  11034. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  11035. * can be implemented.
  11036. *
  11037. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  11038. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  11039. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  11040. * eventually assigned to `geometryNode`.
  11041. *
  11042. * @type {Function}
  11043. * @default null
  11044. */
  11045. this.geometryNode = null;
  11046. /**
  11047. * Allows to overwrite depth values in the fragment shader.
  11048. *
  11049. * @type {Node<float>?}
  11050. * @default null
  11051. */
  11052. this.depthNode = null;
  11053. /**
  11054. * Allows to overwrite the position used for shadow map rendering which
  11055. * is by default {@link module:Position.positionWorld}, the vertex position
  11056. * in world space.
  11057. *
  11058. * @type {Node<float>?}
  11059. * @default null
  11060. */
  11061. this.shadowPositionNode = null;
  11062. /**
  11063. * This node can be used to influence how an object using this node material
  11064. * receive shadows.
  11065. *
  11066. * ```js
  11067. * const totalShadows = float( 1 ).toVar();
  11068. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  11069. * totalShadows.mulAssign( shadow );
  11070. * //return float( 1 ); // bypass received shadows
  11071. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  11072. * } );
  11073. *
  11074. * @type {Node<vec4>?}
  11075. * @default null
  11076. */
  11077. this.receivedShadowNode = null;
  11078. /**
  11079. * This node can be used to influence how an object using this node material
  11080. * casts shadows. To apply a color to shadows, you can simply do:
  11081. *
  11082. * ```js
  11083. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  11084. * ```
  11085. *
  11086. * Which can be nice to fake colored shadows of semi-transparent objects. It
  11087. * is also common to use the property with `Fn` function so checks are performed
  11088. * per fragment.
  11089. *
  11090. * ```js
  11091. * materialCustomShadow.castShadowNode = Fn( () => {
  11092. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  11093. * return materialColor;
  11094. * } )();
  11095. * ```
  11096. *
  11097. * @type {Node<vec4>?}
  11098. * @default null
  11099. */
  11100. this.castShadowNode = null;
  11101. /**
  11102. * This node can be used to define the final output of the material.
  11103. *
  11104. * TODO: Explain the differences to `fragmentNode`.
  11105. *
  11106. * @type {Node<vec4>?}
  11107. * @default null
  11108. */
  11109. this.outputNode = null;
  11110. /**
  11111. * MRT configuration is done on renderer or pass level. This node allows to
  11112. * overwrite what values are written into MRT targets on material level. This
  11113. * can be useful for implementing selective FX features that should only affect
  11114. * specific objects.
  11115. *
  11116. * @type {MRTNode?}
  11117. * @default null
  11118. */
  11119. this.mrtNode = null;
  11120. /**
  11121. * This node property can be used if you need complete freedom in implementing
  11122. * the fragment shader. Assigning a node will replace the built-in material
  11123. * logic used in the fragment stage.
  11124. *
  11125. * @type {Node<vec4>?}
  11126. * @default null
  11127. */
  11128. this.fragmentNode = null;
  11129. /**
  11130. * This node property can be used if you need complete freedom in implementing
  11131. * the vertex shader. Assigning a node will replace the built-in material logic
  11132. * used in the vertex stage.
  11133. *
  11134. * @type {Node<vec4>?}
  11135. * @default null
  11136. */
  11137. this.vertexNode = null;
  11138. }
  11139. /**
  11140. * Allows to define a custom cache key that influence the material key computation
  11141. * for render objects.
  11142. *
  11143. * @return {String} The custom cache key.
  11144. */
  11145. customProgramCacheKey() {
  11146. return this.type + getCacheKey$1( this );
  11147. }
  11148. /**
  11149. * Builds this material with the given node builder.
  11150. *
  11151. * @param {NodeBuilder} builder - The current node builder.
  11152. */
  11153. build( builder ) {
  11154. this.setup( builder );
  11155. }
  11156. /**
  11157. * Setups a node material observer with the given builder.
  11158. *
  11159. * @param {NodeBuilder} builder - The current node builder.
  11160. * @return {NodeMaterialObserver} The node material observer.
  11161. */
  11162. setupObserver( builder ) {
  11163. return new NodeMaterialObserver( builder );
  11164. }
  11165. /**
  11166. * Setups the vertex and fragment stage of this node material.
  11167. *
  11168. * @param {NodeBuilder} builder - The current node builder.
  11169. */
  11170. setup( builder ) {
  11171. builder.context.setupNormal = () => this.setupNormal( builder );
  11172. builder.context.setupPositionView = () => this.setupPositionView( builder );
  11173. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  11174. const renderer = builder.renderer;
  11175. const renderTarget = renderer.getRenderTarget();
  11176. // < VERTEX STAGE >
  11177. builder.addStack();
  11178. const vertexNode = this.vertexNode || this.setupVertex( builder );
  11179. builder.stack.outputNode = vertexNode;
  11180. this.setupHardwareClipping( builder );
  11181. if ( this.geometryNode !== null ) {
  11182. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  11183. }
  11184. builder.addFlow( 'vertex', builder.removeStack() );
  11185. // < FRAGMENT STAGE >
  11186. builder.addStack();
  11187. let resultNode;
  11188. const clippingNode = this.setupClipping( builder );
  11189. if ( this.depthWrite === true || this.depthTest === true ) {
  11190. // only write depth if depth buffer is configured
  11191. if ( renderTarget !== null ) {
  11192. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  11193. } else {
  11194. if ( renderer.depth === true ) this.setupDepth( builder );
  11195. }
  11196. }
  11197. if ( this.fragmentNode === null ) {
  11198. this.setupDiffuseColor( builder );
  11199. this.setupVariants( builder );
  11200. const outgoingLightNode = this.setupLighting( builder );
  11201. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  11202. // force unsigned floats - useful for RenderTargets
  11203. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  11204. resultNode = this.setupOutput( builder, basicOutput );
  11205. // OUTPUT NODE
  11206. output.assign( resultNode );
  11207. //
  11208. if ( this.outputNode !== null ) resultNode = this.outputNode;
  11209. // MRT
  11210. if ( renderTarget !== null ) {
  11211. const mrt = renderer.getMRT();
  11212. const materialMRT = this.mrtNode;
  11213. if ( mrt !== null ) {
  11214. resultNode = mrt;
  11215. if ( materialMRT !== null ) {
  11216. resultNode = mrt.merge( materialMRT );
  11217. }
  11218. } else if ( materialMRT !== null ) {
  11219. resultNode = materialMRT;
  11220. }
  11221. }
  11222. } else {
  11223. let fragmentNode = this.fragmentNode;
  11224. if ( fragmentNode.isOutputStructNode !== true ) {
  11225. fragmentNode = vec4( fragmentNode );
  11226. }
  11227. resultNode = this.setupOutput( builder, fragmentNode );
  11228. }
  11229. builder.stack.outputNode = resultNode;
  11230. builder.addFlow( 'fragment', builder.removeStack() );
  11231. // < MONITOR >
  11232. builder.monitor = this.setupObserver( builder );
  11233. }
  11234. /**
  11235. * Setups the clipping node.
  11236. *
  11237. * @param {NodeBuilder} builder - The current node builder.
  11238. * @return {ClippingNode} The clipping node.
  11239. */
  11240. setupClipping( builder ) {
  11241. if ( builder.clippingContext === null ) return null;
  11242. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  11243. let result = null;
  11244. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  11245. const samples = builder.renderer.samples;
  11246. if ( this.alphaToCoverage && samples > 1 ) {
  11247. // to be added to flow when the color/alpha value has been determined
  11248. result = clippingAlpha();
  11249. } else {
  11250. builder.stack.add( clipping() );
  11251. }
  11252. }
  11253. return result;
  11254. }
  11255. /**
  11256. * Setups the hardware clipping if available on the current device.
  11257. *
  11258. * @param {NodeBuilder} builder - The current node builder.
  11259. */
  11260. setupHardwareClipping( builder ) {
  11261. this.hardwareClipping = false;
  11262. if ( builder.clippingContext === null ) return;
  11263. const candidateCount = builder.clippingContext.unionPlanes.length;
  11264. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  11265. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  11266. builder.stack.add( hardwareClipping() );
  11267. this.hardwareClipping = true;
  11268. }
  11269. return;
  11270. }
  11271. /**
  11272. * Setups the depth of this material.
  11273. *
  11274. * @param {NodeBuilder} builder - The current node builder.
  11275. */
  11276. setupDepth( builder ) {
  11277. const { renderer, camera } = builder;
  11278. // Depth
  11279. let depthNode = this.depthNode;
  11280. if ( depthNode === null ) {
  11281. const mrt = renderer.getMRT();
  11282. if ( mrt && mrt.has( 'depth' ) ) {
  11283. depthNode = mrt.get( 'depth' );
  11284. } else if ( renderer.logarithmicDepthBuffer === true ) {
  11285. if ( camera.isPerspectiveCamera ) {
  11286. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  11287. } else {
  11288. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  11289. }
  11290. }
  11291. }
  11292. if ( depthNode !== null ) {
  11293. depth.assign( depthNode ).append();
  11294. }
  11295. }
  11296. /**
  11297. * Setups the position node in view space. This method exists
  11298. * so derived node materials can modify the implementation e.g. sprite materials.
  11299. *
  11300. * @param {NodeBuilder} builder - The current node builder.
  11301. * @return {Node<vec3>} The position in view space.
  11302. */
  11303. setupPositionView( /*builder*/ ) {
  11304. return modelViewMatrix.mul( positionLocal ).xyz;
  11305. }
  11306. /**
  11307. * Setups the position in clip space.
  11308. *
  11309. * @param {NodeBuilder} builder - The current node builder.
  11310. * @return {Node<vec4>} The position in view space.
  11311. */
  11312. setupModelViewProjection( /*builder*/ ) {
  11313. return cameraProjectionMatrix.mul( positionView );
  11314. }
  11315. /**
  11316. * Setups the logic for the vertex stage.
  11317. *
  11318. * @param {NodeBuilder} builder - The current node builder.
  11319. * @return {Node<vec4>} The position in clip space.
  11320. */
  11321. setupVertex( builder ) {
  11322. builder.addStack();
  11323. this.setupPosition( builder );
  11324. builder.context.vertex = builder.removeStack();
  11325. return modelViewProjection;
  11326. }
  11327. /**
  11328. * Setups the computation of the position in local space.
  11329. *
  11330. * @param {NodeBuilder} builder - The current node builder.
  11331. * @return {Node<vec3>} The position in local space.
  11332. */
  11333. setupPosition( builder ) {
  11334. const { object, geometry } = builder;
  11335. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  11336. morphReference( object ).append();
  11337. }
  11338. if ( object.isSkinnedMesh === true ) {
  11339. skinningReference( object ).append();
  11340. }
  11341. if ( this.displacementMap ) {
  11342. const displacementMap = materialReference( 'displacementMap', 'texture' );
  11343. const displacementScale = materialReference( 'displacementScale', 'float' );
  11344. const displacementBias = materialReference( 'displacementBias', 'float' );
  11345. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  11346. }
  11347. if ( object.isBatchedMesh ) {
  11348. batch( object ).append();
  11349. }
  11350. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  11351. instancedMesh( object ).append();
  11352. }
  11353. if ( this.positionNode !== null ) {
  11354. positionLocal.assign( this.positionNode.context( { isPositionNodeInput: true } ) );
  11355. }
  11356. return positionLocal;
  11357. }
  11358. /**
  11359. * Setups the computation of the material's diffuse color.
  11360. *
  11361. * @param {NodeBuilder} builder - The current node builder.
  11362. * @param {BufferGeometry} geometry - The geometry.
  11363. */
  11364. setupDiffuseColor( { object, geometry } ) {
  11365. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  11366. // VERTEX COLORS
  11367. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  11368. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  11369. }
  11370. // Instanced colors
  11371. if ( object.instanceColor ) {
  11372. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  11373. colorNode = instanceColor.mul( colorNode );
  11374. }
  11375. if ( object.isBatchedMesh && object._colorsTexture ) {
  11376. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  11377. colorNode = batchColor.mul( colorNode );
  11378. }
  11379. // COLOR
  11380. diffuseColor.assign( colorNode );
  11381. // OPACITY
  11382. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  11383. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  11384. // ALPHA TEST
  11385. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  11386. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  11387. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  11388. }
  11389. // ALPHA HASH
  11390. if ( this.alphaHash === true ) {
  11391. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  11392. }
  11393. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  11394. diffuseColor.a.assign( 1.0 );
  11395. }
  11396. }
  11397. /**
  11398. * Abstract interface method that can be implemented by derived materials
  11399. * to setup material-specific node variables.
  11400. *
  11401. * @abstract
  11402. * @param {NodeBuilder} builder - The current node builder.
  11403. */
  11404. setupVariants( /*builder*/ ) {
  11405. // Interface function.
  11406. }
  11407. /**
  11408. * Setups the outgoing light node variable
  11409. *
  11410. * @return {Node<vec3>} The outgoing light node.
  11411. */
  11412. setupOutgoingLight() {
  11413. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  11414. }
  11415. /**
  11416. * Setups the normal node from the material.
  11417. *
  11418. * @return {Node<vec3>} The normal node.
  11419. */
  11420. setupNormal() {
  11421. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  11422. }
  11423. /**
  11424. * Setups the environment node from the material.
  11425. *
  11426. * @param {NodeBuilder} builder - The current node builder.
  11427. * @return {Node<vec4>} The environment node.
  11428. */
  11429. setupEnvironment( /*builder*/ ) {
  11430. let node = null;
  11431. if ( this.envNode ) {
  11432. node = this.envNode;
  11433. } else if ( this.envMap ) {
  11434. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  11435. }
  11436. return node;
  11437. }
  11438. /**
  11439. * Setups the light map node from the material.
  11440. *
  11441. * @param {NodeBuilder} builder - The current node builder.
  11442. * @return {Node<vec3>} The light map node.
  11443. */
  11444. setupLightMap( builder ) {
  11445. let node = null;
  11446. if ( builder.material.lightMap ) {
  11447. node = new IrradianceNode( materialLightMap );
  11448. }
  11449. return node;
  11450. }
  11451. /**
  11452. * Setups the lights node based on the scene, environment and material.
  11453. *
  11454. * @param {NodeBuilder} builder - The current node builder.
  11455. * @return {LightsNode} The lights node.
  11456. */
  11457. setupLights( builder ) {
  11458. const materialLightsNode = [];
  11459. //
  11460. const envNode = this.setupEnvironment( builder );
  11461. if ( envNode && envNode.isLightingNode ) {
  11462. materialLightsNode.push( envNode );
  11463. }
  11464. const lightMapNode = this.setupLightMap( builder );
  11465. if ( lightMapNode && lightMapNode.isLightingNode ) {
  11466. materialLightsNode.push( lightMapNode );
  11467. }
  11468. if ( this.aoNode !== null || builder.material.aoMap ) {
  11469. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  11470. materialLightsNode.push( new AONode( aoNode ) );
  11471. }
  11472. let lightsN = this.lightsNode || builder.lightsNode;
  11473. if ( materialLightsNode.length > 0 ) {
  11474. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  11475. }
  11476. return lightsN;
  11477. }
  11478. /**
  11479. * This method should be implemented by most derived materials
  11480. * since it defines the material's lighting model.
  11481. *
  11482. * @abstract
  11483. * @param {NodeBuilder} builder - The current node builder.
  11484. * @return {LightingModel} The lighting model.
  11485. */
  11486. setupLightingModel( /*builder*/ ) {
  11487. // Interface function.
  11488. }
  11489. /**
  11490. * Setups the outgoing light node.
  11491. *
  11492. * @param {NodeBuilder} builder - The current node builder.
  11493. * @return {Node<vec3>} The outgoing light node.
  11494. */
  11495. setupLighting( builder ) {
  11496. const { material } = builder;
  11497. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  11498. // OUTGOING LIGHT
  11499. const lights = this.lights === true || this.lightsNode !== null;
  11500. const lightsNode = lights ? this.setupLights( builder ) : null;
  11501. let outgoingLightNode = this.setupOutgoingLight( builder );
  11502. if ( lightsNode && lightsNode.getScope().hasLights ) {
  11503. const lightingModel = this.setupLightingModel( builder );
  11504. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  11505. } else if ( backdropNode !== null ) {
  11506. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  11507. }
  11508. // EMISSIVE
  11509. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  11510. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  11511. outgoingLightNode = outgoingLightNode.add( emissive );
  11512. }
  11513. return outgoingLightNode;
  11514. }
  11515. /**
  11516. * Setups the output node.
  11517. *
  11518. * @param {NodeBuilder} builder - The current node builder.
  11519. * @param {Node<vec4>} outputNode - The existing output node.
  11520. * @return {Node<vec4>} The output node.
  11521. */
  11522. setupOutput( builder, outputNode ) {
  11523. // FOG
  11524. if ( this.fog === true ) {
  11525. const fogNode = builder.fogNode;
  11526. if ( fogNode ) {
  11527. output.assign( outputNode );
  11528. outputNode = vec4( fogNode );
  11529. }
  11530. }
  11531. return outputNode;
  11532. }
  11533. /**
  11534. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  11535. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  11536. * defining all material properties of the classic type in the node type.
  11537. *
  11538. * @param {Material} material - The material to copy properties with their values to this node material.
  11539. */
  11540. setDefaultValues( material ) {
  11541. // This approach is to reuse the native refreshUniforms*
  11542. // and turn available the use of features like transmission and environment in core
  11543. for ( const property in material ) {
  11544. const value = material[ property ];
  11545. if ( this[ property ] === undefined ) {
  11546. this[ property ] = value;
  11547. if ( value && value.clone ) this[ property ] = value.clone();
  11548. }
  11549. }
  11550. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  11551. for ( const key in descriptors ) {
  11552. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  11553. descriptors[ key ].get !== undefined ) {
  11554. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  11555. }
  11556. }
  11557. }
  11558. /**
  11559. * Serializes this material to JSON.
  11560. *
  11561. * @param {(Object|String)?} meta - The meta information for serialization.
  11562. * @return {Object} The serialized node.
  11563. */
  11564. toJSON( meta ) {
  11565. const isRoot = ( meta === undefined || typeof meta === 'string' );
  11566. if ( isRoot ) {
  11567. meta = {
  11568. textures: {},
  11569. images: {},
  11570. nodes: {}
  11571. };
  11572. }
  11573. const data = Material.prototype.toJSON.call( this, meta );
  11574. const nodeChildren = getNodeChildren( this );
  11575. data.inputNodes = {};
  11576. for ( const { property, childNode } of nodeChildren ) {
  11577. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  11578. }
  11579. // TODO: Copied from Object3D.toJSON
  11580. function extractFromCache( cache ) {
  11581. const values = [];
  11582. for ( const key in cache ) {
  11583. const data = cache[ key ];
  11584. delete data.metadata;
  11585. values.push( data );
  11586. }
  11587. return values;
  11588. }
  11589. if ( isRoot ) {
  11590. const textures = extractFromCache( meta.textures );
  11591. const images = extractFromCache( meta.images );
  11592. const nodes = extractFromCache( meta.nodes );
  11593. if ( textures.length > 0 ) data.textures = textures;
  11594. if ( images.length > 0 ) data.images = images;
  11595. if ( nodes.length > 0 ) data.nodes = nodes;
  11596. }
  11597. return data;
  11598. }
  11599. /**
  11600. * Copies the properties of the given node material to this instance.
  11601. *
  11602. * @param {NodeMaterial} source - The material to copy.
  11603. * @return {NodeMaterial} A reference to this node material.
  11604. */
  11605. copy( source ) {
  11606. this.lightsNode = source.lightsNode;
  11607. this.envNode = source.envNode;
  11608. this.colorNode = source.colorNode;
  11609. this.normalNode = source.normalNode;
  11610. this.opacityNode = source.opacityNode;
  11611. this.backdropNode = source.backdropNode;
  11612. this.backdropAlphaNode = source.backdropAlphaNode;
  11613. this.alphaTestNode = source.alphaTestNode;
  11614. this.positionNode = source.positionNode;
  11615. this.geometryNode = source.geometryNode;
  11616. this.depthNode = source.depthNode;
  11617. this.shadowPositionNode = source.shadowPositionNode;
  11618. this.receivedShadowNode = source.receivedShadowNode;
  11619. this.castShadowNode = source.castShadowNode;
  11620. this.outputNode = source.outputNode;
  11621. this.mrtNode = source.mrtNode;
  11622. this.fragmentNode = source.fragmentNode;
  11623. this.vertexNode = source.vertexNode;
  11624. return super.copy( source );
  11625. }
  11626. }
  11627. const _defaultValues$e = /*@__PURE__*/ new PointsMaterial();
  11628. /**
  11629. * Unlike WebGL, WebGPU can render point primitives only with a size
  11630. * of one pixel. This type node material can be used to mimic the WebGL
  11631. * points rendering by rendering small planes via instancing.
  11632. *
  11633. * This material should be used with {@link InstancedPointsGeometry}.
  11634. *
  11635. * @augments NodeMaterial
  11636. */
  11637. class InstancedPointsNodeMaterial extends NodeMaterial {
  11638. static get type() {
  11639. return 'InstancedPointsNodeMaterial';
  11640. }
  11641. /**
  11642. * Constructs a new instanced points node material.
  11643. *
  11644. * @param {Object?} parameters - The configuration parameter.
  11645. */
  11646. constructor( parameters = {} ) {
  11647. super();
  11648. /**
  11649. * This flag can be used for type testing.
  11650. *
  11651. * @type {Boolean}
  11652. * @readonly
  11653. * @default true
  11654. */
  11655. this.isInstancedPointsNodeMaterial = true;
  11656. /**
  11657. * Whether vertex colors should be used or not. If set to `true`,
  11658. * each point instance can receive a custom color value.
  11659. *
  11660. * @type {Boolean}
  11661. * @default false
  11662. */
  11663. this.useColor = parameters.vertexColors;
  11664. /**
  11665. * The points width in pixels.
  11666. *
  11667. * @type {Number}
  11668. * @default 1
  11669. */
  11670. this.pointWidth = 1;
  11671. /**
  11672. * This node can be used to define the colors for each instance.
  11673. *
  11674. * @type {Node<vec3>?}
  11675. * @default null
  11676. */
  11677. this.pointColorNode = null;
  11678. /**
  11679. * This node can be used to define the width for each point instance.
  11680. *
  11681. * @type {Node<float>?}
  11682. * @default null
  11683. */
  11684. this.pointWidthNode = null;
  11685. this._useAlphaToCoverage = true;
  11686. this.setDefaultValues( _defaultValues$e );
  11687. this.setValues( parameters );
  11688. }
  11689. /**
  11690. * Setups the vertex and fragment stage of this node material.
  11691. *
  11692. * @param {NodeBuilder} builder - The current node builder.
  11693. */
  11694. setup( builder ) {
  11695. const { renderer } = builder;
  11696. const useAlphaToCoverage = this._useAlphaToCoverage;
  11697. const useColor = this.useColor;
  11698. this.vertexNode = Fn( () => {
  11699. const instancePosition = attribute( 'instancePosition' ).xyz;
  11700. // camera space
  11701. const mvPos = vec4( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  11702. const aspect = viewport.z.div( viewport.w );
  11703. // clip space
  11704. const clipPos = cameraProjectionMatrix.mul( mvPos );
  11705. // offset in ndc space
  11706. const offset = positionGeometry.xy.toVar();
  11707. offset.mulAssign( this.pointWidthNode ? this.pointWidthNode : materialPointWidth );
  11708. offset.assign( offset.div( viewport.z ) );
  11709. offset.y.assign( offset.y.mul( aspect ) );
  11710. // back to clip space
  11711. offset.assign( offset.mul( clipPos.w ) );
  11712. //clipPos.xy += offset;
  11713. clipPos.addAssign( vec4( offset, 0, 0 ) );
  11714. return clipPos;
  11715. } )();
  11716. this.fragmentNode = Fn( () => {
  11717. const alpha = float( 1 ).toVar();
  11718. const len2 = lengthSq( uv().mul( 2 ).sub( 1 ) );
  11719. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  11720. const dlen = float( len2.fwidth() ).toVar();
  11721. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  11722. } else {
  11723. len2.greaterThan( 1.0 ).discard();
  11724. }
  11725. let pointColorNode;
  11726. if ( this.pointColorNode ) {
  11727. pointColorNode = this.pointColorNode;
  11728. } else {
  11729. if ( useColor ) {
  11730. const instanceColor = attribute( 'instanceColor' );
  11731. pointColorNode = instanceColor.mul( materialColor );
  11732. } else {
  11733. pointColorNode = materialColor;
  11734. }
  11735. }
  11736. alpha.mulAssign( materialOpacity );
  11737. return vec4( pointColorNode, alpha );
  11738. } )();
  11739. super.setup( builder );
  11740. }
  11741. /**
  11742. * Whether alpha to coverage should be used or not.
  11743. *
  11744. * @type {Boolean}
  11745. * @default true
  11746. */
  11747. get alphaToCoverage() {
  11748. return this._useAlphaToCoverage;
  11749. }
  11750. set alphaToCoverage( value ) {
  11751. if ( this._useAlphaToCoverage !== value ) {
  11752. this._useAlphaToCoverage = value;
  11753. this.needsUpdate = true;
  11754. }
  11755. }
  11756. }
  11757. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  11758. /**
  11759. * Node material version of `LineBasicMaterial`.
  11760. *
  11761. * @augments NodeMaterial
  11762. */
  11763. class LineBasicNodeMaterial extends NodeMaterial {
  11764. static get type() {
  11765. return 'LineBasicNodeMaterial';
  11766. }
  11767. /**
  11768. * Constructs a new line basic node material.
  11769. *
  11770. * @param {Object?} parameters - The configuration parameter.
  11771. */
  11772. constructor( parameters ) {
  11773. super();
  11774. /**
  11775. * This flag can be used for type testing.
  11776. *
  11777. * @type {Boolean}
  11778. * @readonly
  11779. * @default true
  11780. */
  11781. this.isLineBasicNodeMaterial = true;
  11782. this.setDefaultValues( _defaultValues$d );
  11783. this.setValues( parameters );
  11784. }
  11785. }
  11786. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  11787. /**
  11788. * Node material version of `LineDashedMaterial`.
  11789. *
  11790. * @augments NodeMaterial
  11791. */
  11792. class LineDashedNodeMaterial extends NodeMaterial {
  11793. static get type() {
  11794. return 'LineDashedNodeMaterial';
  11795. }
  11796. /**
  11797. * Constructs a new line dashed node material.
  11798. *
  11799. * @param {Object?} parameters - The configuration parameter.
  11800. */
  11801. constructor( parameters ) {
  11802. super();
  11803. /**
  11804. * This flag can be used for type testing.
  11805. *
  11806. * @type {Boolean}
  11807. * @readonly
  11808. * @default true
  11809. */
  11810. this.isLineDashedNodeMaterial = true;
  11811. this.setDefaultValues( _defaultValues$c );
  11812. /**
  11813. * The dash offset.
  11814. *
  11815. * @type {Number}
  11816. * @default 0
  11817. */
  11818. this.dashOffset = 0;
  11819. /**
  11820. * The offset of dash materials is by default inferred from the `dashOffset`
  11821. * property. This node property allows to overwrite the default
  11822. * and define the offset with a node instead.
  11823. *
  11824. * If you don't want to overwrite the offset but modify the existing
  11825. * value instead, use {@link module:MaterialNode.materialLineDashOffset}.
  11826. *
  11827. * @type {Node<float>?}
  11828. * @default null
  11829. */
  11830. this.offsetNode = null;
  11831. /**
  11832. * The scale of dash materials is by default inferred from the `scale`
  11833. * property. This node property allows to overwrite the default
  11834. * and define the scale with a node instead.
  11835. *
  11836. * If you don't want to overwrite the scale but modify the existing
  11837. * value instead, use {@link module:MaterialNode.materialLineScale}.
  11838. *
  11839. * @type {Node<float>?}
  11840. * @default null
  11841. */
  11842. this.dashScaleNode = null;
  11843. /**
  11844. * The dash size of dash materials is by default inferred from the `dashSize`
  11845. * property. This node property allows to overwrite the default
  11846. * and define the dash size with a node instead.
  11847. *
  11848. * If you don't want to overwrite the dash size but modify the existing
  11849. * value instead, use {@link module:MaterialNode.materialLineDashSize}.
  11850. *
  11851. * @type {Node<float>?}
  11852. * @default null
  11853. */
  11854. this.dashSizeNode = null;
  11855. /**
  11856. * The gap size of dash materials is by default inferred from the `gapSize`
  11857. * property. This node property allows to overwrite the default
  11858. * and define the gap size with a node instead.
  11859. *
  11860. * If you don't want to overwrite the gap size but modify the existing
  11861. * value instead, use {@link module:MaterialNode.materialLineGapSize}.
  11862. *
  11863. * @type {Node<float>?}
  11864. * @default null
  11865. */
  11866. this.gapSizeNode = null;
  11867. this.setValues( parameters );
  11868. }
  11869. /**
  11870. * Setups the dash specific node variables.
  11871. *
  11872. * @param {NodeBuilder} builder - The current node builder.
  11873. */
  11874. setupVariants( /* builder */ ) {
  11875. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  11876. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  11877. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  11878. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  11879. dashSize.assign( dashSizeNode );
  11880. gapSize.assign( gapSizeNode );
  11881. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  11882. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  11883. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  11884. }
  11885. }
  11886. /** @module ViewportSharedTextureNode **/
  11887. let _sharedFramebuffer = null;
  11888. /**
  11889. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  11890. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  11891. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  11892. *
  11893. * @augments module:ViewportTextureNode~ViewportTextureNode
  11894. */
  11895. class ViewportSharedTextureNode extends ViewportTextureNode {
  11896. static get type() {
  11897. return 'ViewportSharedTextureNode';
  11898. }
  11899. /**
  11900. * Constructs a new viewport shared texture node.
  11901. *
  11902. * @param {Node} [uvNode=screenUV] - The uv node.
  11903. * @param {Node?} [levelNode=null] - The level node.
  11904. */
  11905. constructor( uvNode = screenUV, levelNode = null ) {
  11906. if ( _sharedFramebuffer === null ) {
  11907. _sharedFramebuffer = new FramebufferTexture();
  11908. }
  11909. super( uvNode, levelNode, _sharedFramebuffer );
  11910. }
  11911. updateReference() {
  11912. return this;
  11913. }
  11914. }
  11915. /**
  11916. * TSL function for creating a shared viewport texture node.
  11917. *
  11918. * @function
  11919. * @param {Node} [uvNode=screenUV] - The uv node.
  11920. * @param {Node?} [levelNode=null] - The level node.
  11921. * @returns {ViewportSharedTextureNode}
  11922. */
  11923. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  11924. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  11925. /**
  11926. * This node material can be used to render lines with a size larger than one
  11927. * by representing them as instanced meshes.
  11928. *
  11929. * @augments NodeMaterial
  11930. */
  11931. class Line2NodeMaterial extends NodeMaterial {
  11932. static get type() {
  11933. return 'Line2NodeMaterial';
  11934. }
  11935. /**
  11936. * Constructs a new node material for wide line rendering.
  11937. *
  11938. * @param {Object?} parameters - The configuration parameter.
  11939. */
  11940. constructor( parameters = {} ) {
  11941. super();
  11942. /**
  11943. * This flag can be used for type testing.
  11944. *
  11945. * @type {Boolean}
  11946. * @readonly
  11947. * @default true
  11948. */
  11949. this.isLine2NodeMaterial = true;
  11950. this.setDefaultValues( _defaultValues$b );
  11951. /**
  11952. * Whether vertex colors should be used or not.
  11953. *
  11954. * @type {Boolean}
  11955. * @default false
  11956. */
  11957. this.useColor = parameters.vertexColors;
  11958. /**
  11959. * The dash offset.
  11960. *
  11961. * @type {Number}
  11962. * @default 0
  11963. */
  11964. this.dashOffset = 0;
  11965. /**
  11966. * The line width.
  11967. *
  11968. * @type {Number}
  11969. * @default 0
  11970. */
  11971. this.lineWidth = 1;
  11972. /**
  11973. * Defines the lines color.
  11974. *
  11975. * @type {Node<vec3>?}
  11976. * @default null
  11977. */
  11978. this.lineColorNode = null;
  11979. /**
  11980. * Defines the offset.
  11981. *
  11982. * @type {Node<float>?}
  11983. * @default null
  11984. */
  11985. this.offsetNode = null;
  11986. /**
  11987. * Defines the dash scale.
  11988. *
  11989. * @type {Node<float>?}
  11990. * @default null
  11991. */
  11992. this.dashScaleNode = null;
  11993. /**
  11994. * Defines the dash size.
  11995. *
  11996. * @type {Node<float>?}
  11997. * @default null
  11998. */
  11999. this.dashSizeNode = null;
  12000. /**
  12001. * Defines the gap size.
  12002. *
  12003. * @type {Node<float>?}
  12004. * @default null
  12005. */
  12006. this.gapSizeNode = null;
  12007. /**
  12008. * Blending is set to `NoBlending` since transparency
  12009. * is not supported, yet.
  12010. *
  12011. * @type {Number}
  12012. * @default 0
  12013. */
  12014. this.blending = NoBlending;
  12015. this._useDash = parameters.dashed;
  12016. this._useAlphaToCoverage = true;
  12017. this._useWorldUnits = false;
  12018. this.setValues( parameters );
  12019. }
  12020. /**
  12021. * Setups the vertex and fragment stage of this node material.
  12022. *
  12023. * @param {NodeBuilder} builder - The current node builder.
  12024. */
  12025. setup( builder ) {
  12026. const { renderer } = builder;
  12027. const useAlphaToCoverage = this._useAlphaToCoverage;
  12028. const useColor = this.useColor;
  12029. const useDash = this._useDash;
  12030. const useWorldUnits = this._useWorldUnits;
  12031. const trimSegment = Fn( ( { start, end } ) => {
  12032. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  12033. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  12034. const nearEstimate = b.mul( - 0.5 ).div( a );
  12035. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  12036. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  12037. } ).setLayout( {
  12038. name: 'trimSegment',
  12039. type: 'vec4',
  12040. inputs: [
  12041. { name: 'start', type: 'vec4' },
  12042. { name: 'end', type: 'vec4' }
  12043. ]
  12044. } );
  12045. this.vertexNode = Fn( () => {
  12046. const instanceStart = attribute( 'instanceStart' );
  12047. const instanceEnd = attribute( 'instanceEnd' );
  12048. // camera space
  12049. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  12050. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  12051. if ( useDash ) {
  12052. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  12053. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  12054. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  12055. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  12056. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  12057. lineDistance = lineDistance.add( offsetNode );
  12058. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  12059. }
  12060. if ( useWorldUnits ) {
  12061. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  12062. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  12063. }
  12064. const aspect = viewport.z.div( viewport.w );
  12065. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  12066. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  12067. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  12068. // perhaps there is a more elegant solution -- WestLangley
  12069. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  12070. If( perspective, () => {
  12071. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  12072. end.assign( trimSegment( { start: start, end: end } ) );
  12073. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  12074. start.assign( trimSegment( { start: end, end: start } ) );
  12075. } );
  12076. } );
  12077. // clip space
  12078. const clipStart = cameraProjectionMatrix.mul( start );
  12079. const clipEnd = cameraProjectionMatrix.mul( end );
  12080. // ndc space
  12081. const ndcStart = clipStart.xyz.div( clipStart.w );
  12082. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  12083. // direction
  12084. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  12085. // account for clip-space aspect ratio
  12086. dir.x.assign( dir.x.mul( aspect ) );
  12087. dir.assign( dir.normalize() );
  12088. const clip = vec4().toVar();
  12089. if ( useWorldUnits ) {
  12090. // get the offset direction as perpendicular to the view vector
  12091. const worldDir = end.xyz.sub( start.xyz ).normalize();
  12092. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  12093. const worldUp = worldDir.cross( tmpFwd ).normalize();
  12094. const worldFwd = worldDir.cross( worldUp );
  12095. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  12096. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  12097. // height offset
  12098. const hw = materialLineWidth.mul( 0.5 );
  12099. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  12100. // don't extend the line if we're rendering dashes because we
  12101. // won't be rendering the endcaps
  12102. if ( ! useDash ) {
  12103. // cap extension
  12104. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  12105. // add width to the box
  12106. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  12107. // endcaps
  12108. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  12109. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  12110. } );
  12111. }
  12112. // project the worldpos
  12113. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  12114. // shift the depth of the projected points so the line
  12115. // segments overlap neatly
  12116. const clipPose = vec3().toVar();
  12117. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  12118. clip.z.assign( clipPose.z.mul( clip.w ) );
  12119. } else {
  12120. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  12121. // undo aspect ratio adjustment
  12122. dir.x.assign( dir.x.div( aspect ) );
  12123. offset.x.assign( offset.x.div( aspect ) );
  12124. // sign flip
  12125. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  12126. // endcaps
  12127. If( positionGeometry.y.lessThan( 0.0 ), () => {
  12128. offset.assign( offset.sub( dir ) );
  12129. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  12130. offset.assign( offset.add( dir ) );
  12131. } );
  12132. // adjust for linewidth
  12133. offset.assign( offset.mul( materialLineWidth ) );
  12134. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  12135. offset.assign( offset.div( viewport.w ) );
  12136. // select end
  12137. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  12138. // back to clip space
  12139. offset.assign( offset.mul( clip.w ) );
  12140. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  12141. }
  12142. return clip;
  12143. } )();
  12144. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  12145. const p13 = p1.sub( p3 );
  12146. const p43 = p4.sub( p3 );
  12147. const p21 = p2.sub( p1 );
  12148. const d1343 = p13.dot( p43 );
  12149. const d4321 = p43.dot( p21 );
  12150. const d1321 = p13.dot( p21 );
  12151. const d4343 = p43.dot( p43 );
  12152. const d2121 = p21.dot( p21 );
  12153. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  12154. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  12155. const mua = numer.div( denom ).clamp();
  12156. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  12157. return vec2( mua, mub );
  12158. } );
  12159. this.colorNode = Fn( () => {
  12160. const vUv = uv();
  12161. if ( useDash ) {
  12162. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  12163. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  12164. dashSize.assign( dashSizeNode );
  12165. gapSize.assign( gapSizeNode );
  12166. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  12167. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  12168. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  12169. }
  12170. const alpha = float( 1 ).toVar( 'alpha' );
  12171. if ( useWorldUnits ) {
  12172. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  12173. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  12174. // Find the closest points on the view ray and the line segment
  12175. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  12176. const lineDir = worldEnd.sub( worldStart );
  12177. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  12178. const p1 = worldStart.add( lineDir.mul( params.x ) );
  12179. const p2 = rayEnd.mul( params.y );
  12180. const delta = p1.sub( p2 );
  12181. const len = delta.length();
  12182. const norm = len.div( materialLineWidth );
  12183. if ( ! useDash ) {
  12184. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  12185. const dnorm = norm.fwidth();
  12186. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  12187. } else {
  12188. norm.greaterThan( 0.5 ).discard();
  12189. }
  12190. }
  12191. } else {
  12192. // round endcaps
  12193. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  12194. const a = vUv.x;
  12195. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  12196. const len2 = a.mul( a ).add( b.mul( b ) );
  12197. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  12198. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  12199. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  12200. } );
  12201. } else {
  12202. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  12203. const a = vUv.x;
  12204. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  12205. const len2 = a.mul( a ).add( b.mul( b ) );
  12206. len2.greaterThan( 1.0 ).discard();
  12207. } );
  12208. }
  12209. }
  12210. let lineColorNode;
  12211. if ( this.lineColorNode ) {
  12212. lineColorNode = this.lineColorNode;
  12213. } else {
  12214. if ( useColor ) {
  12215. const instanceColorStart = attribute( 'instanceColorStart' );
  12216. const instanceColorEnd = attribute( 'instanceColorEnd' );
  12217. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  12218. lineColorNode = instanceColor.mul( materialColor );
  12219. } else {
  12220. lineColorNode = materialColor;
  12221. }
  12222. }
  12223. return vec4( lineColorNode, alpha );
  12224. } )();
  12225. if ( this.transparent ) {
  12226. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12227. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  12228. }
  12229. super.setup( builder );
  12230. }
  12231. /**
  12232. * Whether the lines should sized in world units or not.
  12233. * When set to `false` the unit is pixel.
  12234. *
  12235. * @type {Boolean}
  12236. * @default false
  12237. */
  12238. get worldUnits() {
  12239. return this._useWorldUnits;
  12240. }
  12241. set worldUnits( value ) {
  12242. if ( this._useWorldUnits !== value ) {
  12243. this._useWorldUnits = value;
  12244. this.needsUpdate = true;
  12245. }
  12246. }
  12247. /**
  12248. * Whether the lines should be dashed or not.
  12249. *
  12250. * @type {Boolean}
  12251. * @default false
  12252. */
  12253. get dashed() {
  12254. return this._useDash;
  12255. }
  12256. set dashed( value ) {
  12257. if ( this._useDash !== value ) {
  12258. this._useDash = value;
  12259. this.needsUpdate = true;
  12260. }
  12261. }
  12262. /**
  12263. * Whether alpha to coverage should be used or not.
  12264. *
  12265. * @type {Boolean}
  12266. * @default true
  12267. */
  12268. get alphaToCoverage() {
  12269. return this._useAlphaToCoverage;
  12270. }
  12271. set alphaToCoverage( value ) {
  12272. if ( this._useAlphaToCoverage !== value ) {
  12273. this._useAlphaToCoverage = value;
  12274. this.needsUpdate = true;
  12275. }
  12276. }
  12277. }
  12278. /** @module Packing **/
  12279. /**
  12280. * Packs a direction vector into a color value.
  12281. *
  12282. * @method
  12283. * @param {Node<vec3>} node - The direction to pack.
  12284. * @return {Node<vec3>} The color.
  12285. */
  12286. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  12287. /**
  12288. * Unpacks a color value into a direction vector.
  12289. *
  12290. * @method
  12291. * @param {Node<vec3>} node - The color to unpack.
  12292. * @return {Node<vec3>} The direction.
  12293. */
  12294. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  12295. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  12296. /**
  12297. * Node material version of `MeshNormalMaterial`.
  12298. *
  12299. * @augments NodeMaterial
  12300. */
  12301. class MeshNormalNodeMaterial extends NodeMaterial {
  12302. static get type() {
  12303. return 'MeshNormalNodeMaterial';
  12304. }
  12305. /**
  12306. * Constructs a new mesh normal node material.
  12307. *
  12308. * @param {Object?} parameters - The configuration parameter.
  12309. */
  12310. constructor( parameters ) {
  12311. super();
  12312. /**
  12313. * This flag can be used for type testing.
  12314. *
  12315. * @type {Boolean}
  12316. * @readonly
  12317. * @default true
  12318. */
  12319. this.isMeshNormalNodeMaterial = true;
  12320. this.setDefaultValues( _defaultValues$a );
  12321. this.setValues( parameters );
  12322. }
  12323. /**
  12324. * Overwrites the default implementation by computing the diffuse color
  12325. * based on the normal data.
  12326. */
  12327. setupDiffuseColor() {
  12328. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12329. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  12330. }
  12331. }
  12332. /** @module EquirectUVNode **/
  12333. /**
  12334. * Can be used to compute texture coordinates for projecting an
  12335. * equirectangular texture onto a mesh for using it as the scene's
  12336. * background.
  12337. *
  12338. * ```js
  12339. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  12340. * ```
  12341. *
  12342. * @augments TempNode
  12343. */
  12344. class EquirectUVNode extends TempNode {
  12345. static get type() {
  12346. return 'EquirectUVNode';
  12347. }
  12348. /**
  12349. * Constructs a new equirect uv node.
  12350. *
  12351. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  12352. */
  12353. constructor( dirNode = positionWorldDirection ) {
  12354. super( 'vec2' );
  12355. /**
  12356. * A direction vector for sampling why is by default `positionWorldDirection`.
  12357. *
  12358. * @type {Node<vec3>}
  12359. */
  12360. this.dirNode = dirNode;
  12361. }
  12362. setup() {
  12363. const dir = this.dirNode;
  12364. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  12365. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  12366. return vec2( u, v );
  12367. }
  12368. }
  12369. /**
  12370. * TSL function for creating an equirect uv node.
  12371. *
  12372. * @function
  12373. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  12374. * @returns {EquirectUVNode}
  12375. */
  12376. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  12377. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  12378. /**
  12379. * This class represents a cube render target. It is a special version
  12380. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  12381. *
  12382. * @augments WebGLCubeRenderTarget
  12383. */
  12384. class CubeRenderTarget extends WebGLCubeRenderTarget {
  12385. constructor( size = 1, options = {} ) {
  12386. super( size, options );
  12387. this.isCubeRenderTarget = true;
  12388. }
  12389. /**
  12390. * Converts the given equirectangular texture to a cube map.
  12391. *
  12392. * @param {Renderer} renderer - The renderer.
  12393. * @param {Texture} texture - The equirectangular texture.
  12394. * @return {CubeRenderTarget} A reference to this cube render target.
  12395. */
  12396. fromEquirectangularTexture( renderer, texture$1 ) {
  12397. const currentMinFilter = texture$1.minFilter;
  12398. const currentGenerateMipmaps = texture$1.generateMipmaps;
  12399. texture$1.generateMipmaps = true;
  12400. this.texture.type = texture$1.type;
  12401. this.texture.colorSpace = texture$1.colorSpace;
  12402. this.texture.generateMipmaps = texture$1.generateMipmaps;
  12403. this.texture.minFilter = texture$1.minFilter;
  12404. this.texture.magFilter = texture$1.magFilter;
  12405. const geometry = new BoxGeometry( 5, 5, 5 );
  12406. const uvNode = equirectUV( positionWorldDirection );
  12407. const material = new NodeMaterial();
  12408. material.colorNode = texture( texture$1, uvNode, 0 );
  12409. material.side = BackSide;
  12410. material.blending = NoBlending;
  12411. const mesh = new Mesh( geometry, material );
  12412. const scene = new Scene();
  12413. scene.add( mesh );
  12414. // Avoid blurred poles
  12415. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  12416. const camera = new CubeCamera( 1, 10, this );
  12417. const currentMRT = renderer.getMRT();
  12418. renderer.setMRT( null );
  12419. camera.update( renderer, scene );
  12420. renderer.setMRT( currentMRT );
  12421. texture$1.minFilter = currentMinFilter;
  12422. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  12423. mesh.geometry.dispose();
  12424. mesh.material.dispose();
  12425. return this;
  12426. }
  12427. }
  12428. /** @module CubeMapNode **/
  12429. const _cache$1 = new WeakMap();
  12430. /**
  12431. * This node can be used to automatically convert environment maps in the
  12432. * equirectangular format into the cube map format.
  12433. *
  12434. * @augments TempNode
  12435. */
  12436. class CubeMapNode extends TempNode {
  12437. static get type() {
  12438. return 'CubeMapNode';
  12439. }
  12440. /**
  12441. * Constructs a new cube map node.
  12442. *
  12443. * @param {Node} envNode - The node representing the environment map.
  12444. */
  12445. constructor( envNode ) {
  12446. super( 'vec3' );
  12447. /**
  12448. * The node representing the environment map.
  12449. *
  12450. * @type {Node}
  12451. */
  12452. this.envNode = envNode;
  12453. /**
  12454. * A reference to the internal cube texture.
  12455. *
  12456. * @private
  12457. * @type {CubeTexture}
  12458. * @default null
  12459. */
  12460. this._cubeTexture = null;
  12461. /**
  12462. * A reference to the internal cube texture node.
  12463. *
  12464. * @private
  12465. * @type {CubeTextureNode}
  12466. */
  12467. this._cubeTextureNode = cubeTexture();
  12468. const defaultTexture = new CubeTexture();
  12469. defaultTexture.isRenderTargetTexture = true;
  12470. /**
  12471. * A default cube texture that acts as a placeholder.
  12472. * It is used when the conversion from equirectangular to cube
  12473. * map has not finished yet for a given texture.
  12474. *
  12475. * @private
  12476. * @type {CubeTexture}
  12477. */
  12478. this._defaultTexture = defaultTexture;
  12479. /**
  12480. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  12481. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  12482. *
  12483. * @type {String}
  12484. * @default 'render'
  12485. */
  12486. this.updateBeforeType = NodeUpdateType.RENDER;
  12487. }
  12488. updateBefore( frame ) {
  12489. const { renderer, material } = frame;
  12490. const envNode = this.envNode;
  12491. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  12492. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  12493. if ( texture && texture.isTexture ) {
  12494. const mapping = texture.mapping;
  12495. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  12496. // check for converted cubemap map
  12497. if ( _cache$1.has( texture ) ) {
  12498. const cubeMap = _cache$1.get( texture );
  12499. mapTextureMapping( cubeMap, texture.mapping );
  12500. this._cubeTexture = cubeMap;
  12501. } else {
  12502. // create cube map from equirectangular map
  12503. const image = texture.image;
  12504. if ( isEquirectangularMapReady$1( image ) ) {
  12505. const renderTarget = new CubeRenderTarget( image.height );
  12506. renderTarget.fromEquirectangularTexture( renderer, texture );
  12507. mapTextureMapping( renderTarget.texture, texture.mapping );
  12508. this._cubeTexture = renderTarget.texture;
  12509. _cache$1.set( texture, renderTarget.texture );
  12510. texture.addEventListener( 'dispose', onTextureDispose );
  12511. } else {
  12512. // default cube texture as fallback when equirectangular texture is not yet loaded
  12513. this._cubeTexture = this._defaultTexture;
  12514. }
  12515. }
  12516. //
  12517. this._cubeTextureNode.value = this._cubeTexture;
  12518. } else {
  12519. // envNode already refers to a cube map
  12520. this._cubeTextureNode = this.envNode;
  12521. }
  12522. }
  12523. }
  12524. }
  12525. setup( builder ) {
  12526. this.updateBefore( builder );
  12527. return this._cubeTextureNode;
  12528. }
  12529. }
  12530. /**
  12531. * Returns true if the given equirectangular image has been fully loaded
  12532. * and is ready for further processing.
  12533. *
  12534. * @private
  12535. * @param {Image} image - The equirectangular image to check.
  12536. * @return {Boolean} Whether the image is ready or not.
  12537. */
  12538. function isEquirectangularMapReady$1( image ) {
  12539. if ( image === null || image === undefined ) return false;
  12540. return image.height > 0;
  12541. }
  12542. /**
  12543. * This function is executed when `dispose()` is called on the equirectangular
  12544. * texture. In this case, the generated cube map with its render target
  12545. * is deleted as well.
  12546. *
  12547. * @private
  12548. * @param {Object} event - The event object.
  12549. */
  12550. function onTextureDispose( event ) {
  12551. const texture = event.target;
  12552. texture.removeEventListener( 'dispose', onTextureDispose );
  12553. const renderTarget = _cache$1.get( texture );
  12554. if ( renderTarget !== undefined ) {
  12555. _cache$1.delete( texture );
  12556. renderTarget.dispose();
  12557. }
  12558. }
  12559. /**
  12560. * This function makes sure the generated cube map uses the correct
  12561. * texture mapping that corresponds to the equirectangular original.
  12562. *
  12563. * @private
  12564. * @param {Texture} texture - The cube texture.
  12565. * @param {Number} mapping - The original texture mapping.
  12566. */
  12567. function mapTextureMapping( texture, mapping ) {
  12568. if ( mapping === EquirectangularReflectionMapping ) {
  12569. texture.mapping = CubeReflectionMapping;
  12570. } else if ( mapping === EquirectangularRefractionMapping ) {
  12571. texture.mapping = CubeRefractionMapping;
  12572. }
  12573. }
  12574. /**
  12575. * TSL function for creating a cube map node.
  12576. *
  12577. * @function
  12578. * @param {Node} envNode - The node representing the environment map.
  12579. * @returns {CubeMapNode}
  12580. */
  12581. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  12582. /**
  12583. * Represents a basic model for Image-based lighting (IBL). The environment
  12584. * is defined via environment maps in the equirectangular or cube map format.
  12585. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  12586. * or {@link MeshPhongNodeMaterial}.
  12587. *
  12588. * @augments LightingNode
  12589. */
  12590. class BasicEnvironmentNode extends LightingNode {
  12591. static get type() {
  12592. return 'BasicEnvironmentNode';
  12593. }
  12594. /**
  12595. * Constructs a new basic environment node.
  12596. *
  12597. * @param {Node} [envNode=null] - A node representing the environment.
  12598. */
  12599. constructor( envNode = null ) {
  12600. super();
  12601. /**
  12602. * A node representing the environment.
  12603. *
  12604. * @type {Node}
  12605. * @default null
  12606. */
  12607. this.envNode = envNode;
  12608. }
  12609. setup( builder ) {
  12610. // environment property is used in the finish() method of BasicLightingModel
  12611. builder.context.environment = cubeMapNode( this.envNode );
  12612. }
  12613. }
  12614. /**
  12615. * A specific version of {@link IrradianceNode} that is only relevant
  12616. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  12617. * requires a special scaling factor for the light map.
  12618. *
  12619. * @augments LightingNode
  12620. */
  12621. class BasicLightMapNode extends LightingNode {
  12622. static get type() {
  12623. return 'BasicLightMapNode';
  12624. }
  12625. /**
  12626. * Constructs a new basic light map node.
  12627. *
  12628. * @param {Node<vec3>?} [lightMapNode=null] - The light map node.
  12629. */
  12630. constructor( lightMapNode = null ) {
  12631. super();
  12632. /**
  12633. * The light map node.
  12634. *
  12635. * @type {Node<vec3>?}
  12636. */
  12637. this.lightMapNode = lightMapNode;
  12638. }
  12639. setup( builder ) {
  12640. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  12641. const RECIPROCAL_PI = float( 1 / Math.PI );
  12642. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  12643. }
  12644. }
  12645. /**
  12646. * Abstract class for implementing lighting models. The module defines
  12647. * multiple methods that concrete lighting models can implement. These
  12648. * methods are executed at different points during the light evaluation
  12649. * process.
  12650. */
  12651. class LightingModel {
  12652. /**
  12653. * This method is intended for setting up lighting model and context data
  12654. * which are later used in the evaluation process.
  12655. *
  12656. * @abstract
  12657. * @param {ContextNode} input - The current node context.
  12658. * @param {StackNode} stack - The current stack.
  12659. * @param {NodeBuilder} builder - The current node builder.
  12660. */
  12661. start( /*input, stack, builder*/ ) { }
  12662. /**
  12663. * This method is intended for executing final tasks like final updates
  12664. * to the outgoing light.
  12665. *
  12666. * @abstract
  12667. * @param {ContextNode} input - The current node context.
  12668. * @param {StackNode} stack - The current stack.
  12669. * @param {NodeBuilder} builder - The current node builder.
  12670. */
  12671. finish( /*input, stack, builder*/ ) { }
  12672. /**
  12673. * This method is intended for implementing the direct light term and
  12674. * executed during the build process of directional, point and spot light nodes.
  12675. *
  12676. * @abstract
  12677. * @param {Object} input - The input data.
  12678. * @param {StackNode} stack - The current stack.
  12679. * @param {NodeBuilder} builder - The current node builder.
  12680. */
  12681. direct( /*input, stack, builder*/ ) { }
  12682. /**
  12683. * This method is intended for implementing the direct light term for
  12684. * rect area light nodes.
  12685. *
  12686. * @abstract
  12687. * @param {Object} input - The input data.
  12688. * @param {StackNode} stack - The current stack.
  12689. * @param {NodeBuilder} builder - The current node builder.
  12690. */
  12691. directRectArea( /*input, stack, builder*/ ) {}
  12692. /**
  12693. * This method is intended for implementing the indirect light term.
  12694. *
  12695. * @abstract
  12696. * @param {ContextNode} input - The current node context.
  12697. * @param {StackNode} stack - The current stack.
  12698. * @param {NodeBuilder} builder - The current node builder.
  12699. */
  12700. indirect( /*input, stack, builder*/ ) { }
  12701. /**
  12702. * This method is intended for implementing the ambient occlusion term.
  12703. * Unlike other methods, this method must be called manually by the lighting
  12704. * model in its indirect term.
  12705. *
  12706. * @abstract
  12707. * @param {ContextNode} input - The current node context.
  12708. * @param {StackNode} stack - The current stack.
  12709. * @param {NodeBuilder} builder - The current node builder.
  12710. */
  12711. ambientOcclusion( /*input, stack, builder*/ ) { }
  12712. }
  12713. /**
  12714. * Represents the lighting model for unlit materials. The only light contribution
  12715. * is baked indirect lighting modulated with ambient occlusion and the material's
  12716. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  12717. *
  12718. * @augments LightingModel
  12719. */
  12720. class BasicLightingModel extends LightingModel {
  12721. /**
  12722. * Constructs a new basic lighting model.
  12723. */
  12724. constructor() {
  12725. super();
  12726. }
  12727. /**
  12728. * Implements the baked indirect lighting with its modulation.
  12729. *
  12730. * @param {ContextNode} context - The current node context.
  12731. * @param {StackNode} stack - The current stack.
  12732. * @param {NodeBuilder} builder - The current node builder.
  12733. */
  12734. indirect( context, stack, builder ) {
  12735. const ambientOcclusion = context.ambientOcclusion;
  12736. const reflectedLight = context.reflectedLight;
  12737. const irradianceLightMap = builder.context.irradianceLightMap;
  12738. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  12739. // accumulation (baked indirect lighting only)
  12740. if ( irradianceLightMap ) {
  12741. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  12742. } else {
  12743. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  12744. }
  12745. // modulation
  12746. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  12747. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  12748. }
  12749. /**
  12750. * Implements the environment mapping.
  12751. *
  12752. * @param {ContextNode} context - The current node context.
  12753. * @param {StackNode} stack - The current stack.
  12754. * @param {NodeBuilder} builder - The current node builder.
  12755. */
  12756. finish( context, stack, builder ) {
  12757. const material = builder.material;
  12758. const outgoingLight = context.outgoingLight;
  12759. const envNode = builder.context.environment;
  12760. if ( envNode ) {
  12761. switch ( material.combine ) {
  12762. case MultiplyOperation:
  12763. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  12764. break;
  12765. case MixOperation:
  12766. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  12767. break;
  12768. case AddOperation:
  12769. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  12770. break;
  12771. default:
  12772. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  12773. break;
  12774. }
  12775. }
  12776. }
  12777. }
  12778. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  12779. /**
  12780. * Node material version of `MeshBasicMaterial`.
  12781. *
  12782. * @augments NodeMaterial
  12783. */
  12784. class MeshBasicNodeMaterial extends NodeMaterial {
  12785. static get type() {
  12786. return 'MeshBasicNodeMaterial';
  12787. }
  12788. /**
  12789. * Constructs a new mesh basic node material.
  12790. *
  12791. * @param {Object?} parameters - The configuration parameter.
  12792. */
  12793. constructor( parameters ) {
  12794. super();
  12795. /**
  12796. * This flag can be used for type testing.
  12797. *
  12798. * @type {Boolean}
  12799. * @readonly
  12800. * @default true
  12801. */
  12802. this.isMeshBasicNodeMaterial = true;
  12803. /**
  12804. * Although the basic material is by definition unlit, we set
  12805. * this property to `true` since we use a lighting model to compute
  12806. * the outgoing light of the fragment shader.
  12807. *
  12808. * @type {Boolean}
  12809. * @default true
  12810. */
  12811. this.lights = true;
  12812. this.setDefaultValues( _defaultValues$9 );
  12813. this.setValues( parameters );
  12814. }
  12815. /**
  12816. * Basic materials are not affected by normal and bump maps so we
  12817. * return by default {@link module:Normal.normalView}.
  12818. *
  12819. * @return {Node<vec3>} The normal node.
  12820. */
  12821. setupNormal() {
  12822. return normalView; // see #28839
  12823. }
  12824. /**
  12825. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  12826. * to implement the default environment mapping.
  12827. *
  12828. * @param {NodeBuilder} builder - The current node builder.
  12829. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  12830. */
  12831. setupEnvironment( builder ) {
  12832. const envNode = super.setupEnvironment( builder );
  12833. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  12834. }
  12835. /**
  12836. * This method must be overwritten since light maps are evaluated
  12837. * with a special scaling factor for basic materials.
  12838. *
  12839. * @param {NodeBuilder} builder - The current node builder.
  12840. * @return {BasicLightMapNode<vec3>?} The light map node.
  12841. */
  12842. setupLightMap( builder ) {
  12843. let node = null;
  12844. if ( builder.material.lightMap ) {
  12845. node = new BasicLightMapNode( materialLightMap );
  12846. }
  12847. return node;
  12848. }
  12849. /**
  12850. * The material overwrites this method because `lights` is set to `true` but
  12851. * we still want to return the diffuse color as the outgoing light.
  12852. *
  12853. * @return {Node<vec3>} The outgoing light node.
  12854. */
  12855. setupOutgoingLight() {
  12856. return diffuseColor.rgb;
  12857. }
  12858. /**
  12859. * Setups the lighting model.
  12860. *
  12861. * @return {BasicLightingModel} The lighting model.
  12862. */
  12863. setupLightingModel() {
  12864. return new BasicLightingModel();
  12865. }
  12866. }
  12867. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  12868. // Original approximation by Christophe Schlick '94
  12869. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  12870. // Optimized variant (presented by Epic at SIGGRAPH '13)
  12871. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  12872. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  12873. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  12874. } ); // validated
  12875. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  12876. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  12877. } ); // validated
  12878. const G_BlinnPhong_Implicit = () => float( 0.25 );
  12879. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  12880. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  12881. } );
  12882. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  12883. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  12884. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  12885. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  12886. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  12887. const G = G_BlinnPhong_Implicit();
  12888. const D = D_BlinnPhong( { dotNH } );
  12889. return F.mul( G ).mul( D );
  12890. } );
  12891. /**
  12892. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  12893. *
  12894. * @augments BasicLightingModel
  12895. */
  12896. class PhongLightingModel extends BasicLightingModel {
  12897. /**
  12898. * Constructs a new phong lighting model.
  12899. *
  12900. * @param {Boolean} [specular=true] - Whether specular is supported or not.
  12901. */
  12902. constructor( specular = true ) {
  12903. super();
  12904. /**
  12905. * Whether specular is supported or not. Set this to `false` if you are
  12906. * looking for a Lambert-like material meaning a material for non-shiny
  12907. * surfaces, without specular highlights.
  12908. *
  12909. * @type {Boolean}
  12910. * @default true
  12911. */
  12912. this.specular = specular;
  12913. }
  12914. /**
  12915. * Implements the direct lighting. The specular portion is optional an can be controlled
  12916. * with the {@link PhongLightingModel#specular} flag.
  12917. *
  12918. * @param {Object} input - The input data.
  12919. * @param {StackNode} stack - The current stack.
  12920. * @param {NodeBuilder} builder - The current node builder.
  12921. */
  12922. direct( { lightDirection, lightColor, reflectedLight } ) {
  12923. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  12924. const irradiance = dotNL.mul( lightColor );
  12925. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  12926. if ( this.specular === true ) {
  12927. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  12928. }
  12929. }
  12930. /**
  12931. * Implements the indirect lighting.
  12932. *
  12933. * @param {ContextNode} input - The current node context.
  12934. * @param {StackNode} stack - The current stack.
  12935. * @param {NodeBuilder} builder - The current node builder.
  12936. */
  12937. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  12938. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  12939. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  12940. }
  12941. }
  12942. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  12943. /**
  12944. * Node material version of `MeshLambertMaterial`.
  12945. *
  12946. * @augments NodeMaterial
  12947. */
  12948. class MeshLambertNodeMaterial extends NodeMaterial {
  12949. static get type() {
  12950. return 'MeshLambertNodeMaterial';
  12951. }
  12952. /**
  12953. * Constructs a new mesh lambert node material.
  12954. *
  12955. * @param {Object?} parameters - The configuration parameter.
  12956. */
  12957. constructor( parameters ) {
  12958. super();
  12959. /**
  12960. * This flag can be used for type testing.
  12961. *
  12962. * @type {Boolean}
  12963. * @readonly
  12964. * @default true
  12965. */
  12966. this.isMeshLambertNodeMaterial = true;
  12967. /**
  12968. * Set to `true` because lambert materials react on lights.
  12969. *
  12970. * @type {Boolean}
  12971. * @default true
  12972. */
  12973. this.lights = true;
  12974. this.setDefaultValues( _defaultValues$8 );
  12975. this.setValues( parameters );
  12976. }
  12977. /**
  12978. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  12979. * to implement the default environment mapping.
  12980. *
  12981. * @param {NodeBuilder} builder - The current node builder.
  12982. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  12983. */
  12984. setupEnvironment( builder ) {
  12985. const envNode = super.setupEnvironment( builder );
  12986. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  12987. }
  12988. /**
  12989. * Setups the lighting model.
  12990. *
  12991. * @return {PhongLightingModel} The lighting model.
  12992. */
  12993. setupLightingModel( /*builder*/ ) {
  12994. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  12995. }
  12996. }
  12997. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  12998. /**
  12999. * Node material version of `MeshPhongMaterial`.
  13000. *
  13001. * @augments NodeMaterial
  13002. */
  13003. class MeshPhongNodeMaterial extends NodeMaterial {
  13004. static get type() {
  13005. return 'MeshPhongNodeMaterial';
  13006. }
  13007. /**
  13008. * Constructs a new mesh lambert node material.
  13009. *
  13010. * @param {Object?} parameters - The configuration parameter.
  13011. */
  13012. constructor( parameters ) {
  13013. super();
  13014. /**
  13015. * This flag can be used for type testing.
  13016. *
  13017. * @type {Boolean}
  13018. * @readonly
  13019. * @default true
  13020. */
  13021. this.isMeshPhongNodeMaterial = true;
  13022. /**
  13023. * Set to `true` because phong materials react on lights.
  13024. *
  13025. * @type {Boolean}
  13026. * @default true
  13027. */
  13028. this.lights = true;
  13029. /**
  13030. * The shininess of phong materials is by default inferred from the `shininess`
  13031. * property. This node property allows to overwrite the default
  13032. * and define the shininess with a node instead.
  13033. *
  13034. * If you don't want to overwrite the shininess but modify the existing
  13035. * value instead, use {@link module:MaterialNode.materialShininess}.
  13036. *
  13037. * @type {Node<float>?}
  13038. * @default null
  13039. */
  13040. this.shininessNode = null;
  13041. /**
  13042. * The specular color of phong materials is by default inferred from the
  13043. * `specular` property. This node property allows to overwrite the default
  13044. * and define the specular color with a node instead.
  13045. *
  13046. * If you don't want to overwrite the specular color but modify the existing
  13047. * value instead, use {@link module:MaterialNode.materialSpecular}.
  13048. *
  13049. * @type {Node<vec3>?}
  13050. * @default null
  13051. */
  13052. this.specularNode = null;
  13053. this.setDefaultValues( _defaultValues$7 );
  13054. this.setValues( parameters );
  13055. }
  13056. /**
  13057. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  13058. * to implement the default environment mapping.
  13059. *
  13060. * @param {NodeBuilder} builder - The current node builder.
  13061. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  13062. */
  13063. setupEnvironment( builder ) {
  13064. const envNode = super.setupEnvironment( builder );
  13065. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  13066. }
  13067. /**
  13068. * Setups the lighting model.
  13069. *
  13070. * @return {PhongLightingModel} The lighting model.
  13071. */
  13072. setupLightingModel( /*builder*/ ) {
  13073. return new PhongLightingModel();
  13074. }
  13075. /**
  13076. * Setups the phong specific node variables.
  13077. *
  13078. * @param {NodeBuilder} builder - The current node builder.
  13079. */
  13080. setupVariants( /*builder*/ ) {
  13081. // SHININESS
  13082. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  13083. shininess.assign( shininessNode );
  13084. // SPECULAR COLOR
  13085. const specularNode = this.specularNode || materialSpecular;
  13086. specularColor.assign( specularNode );
  13087. }
  13088. copy( source ) {
  13089. this.shininessNode = source.shininessNode;
  13090. this.specularNode = source.specularNode;
  13091. return super.copy( source );
  13092. }
  13093. }
  13094. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  13095. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  13096. return float( 0 );
  13097. }
  13098. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  13099. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  13100. return geometryRoughness;
  13101. } );
  13102. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  13103. const { roughness } = inputs;
  13104. const geometryRoughness = getGeometryRoughness();
  13105. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  13106. roughnessFactor = roughnessFactor.add( geometryRoughness );
  13107. roughnessFactor = roughnessFactor.min( 1.0 );
  13108. return roughnessFactor;
  13109. } );
  13110. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  13111. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  13112. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  13113. const a2 = alpha.pow2();
  13114. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  13115. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  13116. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  13117. } ).setLayout( {
  13118. name: 'V_GGX_SmithCorrelated',
  13119. type: 'float',
  13120. inputs: [
  13121. { name: 'alpha', type: 'float' },
  13122. { name: 'dotNL', type: 'float' },
  13123. { name: 'dotNV', type: 'float' }
  13124. ]
  13125. } ); // validated
  13126. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  13127. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  13128. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  13129. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  13130. const v = div( 0.5, gv.add( gl ) );
  13131. return v.saturate();
  13132. } ).setLayout( {
  13133. name: 'V_GGX_SmithCorrelated_Anisotropic',
  13134. type: 'float',
  13135. inputs: [
  13136. { name: 'alphaT', type: 'float', qualifier: 'in' },
  13137. { name: 'alphaB', type: 'float', qualifier: 'in' },
  13138. { name: 'dotTV', type: 'float', qualifier: 'in' },
  13139. { name: 'dotBV', type: 'float', qualifier: 'in' },
  13140. { name: 'dotTL', type: 'float', qualifier: 'in' },
  13141. { name: 'dotBL', type: 'float', qualifier: 'in' },
  13142. { name: 'dotNV', type: 'float', qualifier: 'in' },
  13143. { name: 'dotNL', type: 'float', qualifier: 'in' }
  13144. ]
  13145. } );
  13146. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  13147. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  13148. // alpha is "roughness squared" in Disney’s reparameterization
  13149. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  13150. const a2 = alpha.pow2();
  13151. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  13152. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  13153. } ).setLayout( {
  13154. name: 'D_GGX',
  13155. type: 'float',
  13156. inputs: [
  13157. { name: 'alpha', type: 'float' },
  13158. { name: 'dotNH', type: 'float' }
  13159. ]
  13160. } ); // validated
  13161. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  13162. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  13163. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  13164. const a2 = alphaT.mul( alphaB );
  13165. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  13166. const v2 = v.dot( v );
  13167. const w2 = a2.div( v2 );
  13168. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  13169. } ).setLayout( {
  13170. name: 'D_GGX_Anisotropic',
  13171. type: 'float',
  13172. inputs: [
  13173. { name: 'alphaT', type: 'float', qualifier: 'in' },
  13174. { name: 'alphaB', type: 'float', qualifier: 'in' },
  13175. { name: 'dotNH', type: 'float', qualifier: 'in' },
  13176. { name: 'dotTH', type: 'float', qualifier: 'in' },
  13177. { name: 'dotBH', type: 'float', qualifier: 'in' }
  13178. ]
  13179. } );
  13180. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  13181. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  13182. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  13183. const normalView = inputs.normalView || transformedNormalView;
  13184. const alpha = roughness.pow2(); // UE4's roughness
  13185. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13186. const dotNL = normalView.dot( lightDirection ).clamp();
  13187. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13188. const dotNH = normalView.dot( halfDir ).clamp();
  13189. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  13190. let F = F_Schlick( { f0, f90, dotVH } );
  13191. let V, D;
  13192. if ( defined( USE_IRIDESCENCE ) ) {
  13193. F = iridescence.mix( F, f );
  13194. }
  13195. if ( defined( USE_ANISOTROPY ) ) {
  13196. const dotTL = anisotropyT.dot( lightDirection );
  13197. const dotTV = anisotropyT.dot( positionViewDirection );
  13198. const dotTH = anisotropyT.dot( halfDir );
  13199. const dotBL = anisotropyB.dot( lightDirection );
  13200. const dotBV = anisotropyB.dot( positionViewDirection );
  13201. const dotBH = anisotropyB.dot( halfDir );
  13202. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  13203. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  13204. } else {
  13205. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  13206. D = D_GGX( { alpha, dotNH } );
  13207. }
  13208. return F.mul( V ).mul( D );
  13209. } ); // validated
  13210. // Analytical approximation of the DFG LUT, one half of the
  13211. // split-sum approximation used in indirect specular lighting.
  13212. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  13213. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  13214. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  13215. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  13216. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  13217. const r = roughness.mul( c0 ).add( c1 );
  13218. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  13219. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  13220. return fab;
  13221. } ).setLayout( {
  13222. name: 'DFGApprox',
  13223. type: 'vec2',
  13224. inputs: [
  13225. { name: 'roughness', type: 'float' },
  13226. { name: 'dotNV', type: 'vec3' }
  13227. ]
  13228. } );
  13229. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  13230. const { dotNV, specularColor, specularF90, roughness } = inputs;
  13231. const fab = DFGApprox( { dotNV, roughness } );
  13232. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  13233. } );
  13234. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  13235. const x = dotVH.oneMinus().saturate();
  13236. const x2 = x.mul( x );
  13237. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  13238. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  13239. } ).setLayout( {
  13240. name: 'Schlick_to_F0',
  13241. type: 'vec3',
  13242. inputs: [
  13243. { name: 'f', type: 'vec3' },
  13244. { name: 'f90', type: 'float' },
  13245. { name: 'dotVH', type: 'float' }
  13246. ]
  13247. } );
  13248. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  13249. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  13250. const alpha = roughness.pow2();
  13251. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  13252. const invAlpha = float( 1.0 ).div( alpha );
  13253. const cos2h = dotNH.pow2();
  13254. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  13255. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  13256. } ).setLayout( {
  13257. name: 'D_Charlie',
  13258. type: 'float',
  13259. inputs: [
  13260. { name: 'roughness', type: 'float' },
  13261. { name: 'dotNH', type: 'float' }
  13262. ]
  13263. } );
  13264. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  13265. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  13266. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  13267. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  13268. } ).setLayout( {
  13269. name: 'V_Neubelt',
  13270. type: 'float',
  13271. inputs: [
  13272. { name: 'dotNV', type: 'float' },
  13273. { name: 'dotNL', type: 'float' }
  13274. ]
  13275. } );
  13276. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  13277. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13278. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  13279. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  13280. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  13281. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  13282. const V = V_Neubelt( { dotNV, dotNL } );
  13283. return sheen.mul( D ).mul( V );
  13284. } );
  13285. // Rect Area Light
  13286. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  13287. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  13288. // code: https://github.com/selfshadow/ltc_code/
  13289. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  13290. const LUT_SIZE = 64.0;
  13291. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  13292. const LUT_BIAS = 0.5 / LUT_SIZE;
  13293. const dotNV = N.dot( V ).saturate();
  13294. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  13295. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  13296. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  13297. return uv;
  13298. } ).setLayout( {
  13299. name: 'LTC_Uv',
  13300. type: 'vec2',
  13301. inputs: [
  13302. { name: 'N', type: 'vec3' },
  13303. { name: 'V', type: 'vec3' },
  13304. { name: 'roughness', type: 'float' }
  13305. ]
  13306. } );
  13307. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  13308. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  13309. // An approximation of the form factor of a horizon-clipped rectangle.
  13310. const l = f.length();
  13311. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  13312. } ).setLayout( {
  13313. name: 'LTC_ClippedSphereFormFactor',
  13314. type: 'float',
  13315. inputs: [
  13316. { name: 'f', type: 'vec3' }
  13317. ]
  13318. } );
  13319. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  13320. const x = v1.dot( v2 );
  13321. const y = x.abs().toVar();
  13322. // rational polynomial approximation to theta / sin( theta ) / 2PI
  13323. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  13324. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  13325. const v = a.div( b );
  13326. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  13327. return v1.cross( v2 ).mul( theta_sintheta );
  13328. } ).setLayout( {
  13329. name: 'LTC_EdgeVectorFormFactor',
  13330. type: 'vec3',
  13331. inputs: [
  13332. { name: 'v1', type: 'vec3' },
  13333. { name: 'v2', type: 'vec3' }
  13334. ]
  13335. } );
  13336. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  13337. // bail if point is on back side of plane of light
  13338. // assumes ccw winding order of light vertices
  13339. const v1 = p1.sub( p0 ).toVar();
  13340. const v2 = p3.sub( p0 ).toVar();
  13341. const lightNormal = v1.cross( v2 );
  13342. const result = vec3().toVar();
  13343. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  13344. // construct orthonormal basis around N
  13345. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  13346. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  13347. // compute transform
  13348. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  13349. // transform rect
  13350. // & project rect onto sphere
  13351. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  13352. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  13353. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  13354. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  13355. // calculate vector form factor
  13356. const vectorFormFactor = vec3( 0 ).toVar();
  13357. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  13358. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  13359. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  13360. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  13361. // adjust for horizon clipping
  13362. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  13363. } );
  13364. return result;
  13365. } ).setLayout( {
  13366. name: 'LTC_Evaluate',
  13367. type: 'vec3',
  13368. inputs: [
  13369. { name: 'N', type: 'vec3' },
  13370. { name: 'V', type: 'vec3' },
  13371. { name: 'P', type: 'vec3' },
  13372. { name: 'mInv', type: 'mat3' },
  13373. { name: 'p0', type: 'vec3' },
  13374. { name: 'p1', type: 'vec3' },
  13375. { name: 'p2', type: 'vec3' },
  13376. { name: 'p3', type: 'vec3' }
  13377. ]
  13378. } );
  13379. /** @module TextureBicubic **/
  13380. // Mipped Bicubic Texture Filtering by N8
  13381. // https://www.shadertoy.com/view/Dl2SDW
  13382. const bC = 1.0 / 6.0;
  13383. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  13384. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  13385. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  13386. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  13387. const g0 = ( a ) => w0( a ).add( w1( a ) );
  13388. const g1 = ( a ) => w2( a ).add( w3( a ) );
  13389. // h0 and h1 are the two offset functions
  13390. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  13391. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  13392. const bicubic = ( textureNode, texelSize, lod ) => {
  13393. const uv = textureNode.uvNode;
  13394. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  13395. const iuv = floor( uvScaled );
  13396. const fuv = fract( uvScaled );
  13397. const g0x = g0( fuv.x );
  13398. const g1x = g1( fuv.x );
  13399. const h0x = h0( fuv.x );
  13400. const h1x = h1( fuv.x );
  13401. const h0y = h0( fuv.y );
  13402. const h1y = h1( fuv.y );
  13403. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  13404. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  13405. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  13406. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  13407. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  13408. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  13409. return a.add( b );
  13410. };
  13411. /**
  13412. * Applies mipped bicubic texture filtering to the given texture node.
  13413. *
  13414. * @method
  13415. * @param {TextureNode} textureNode - The texture node that should be filtered.
  13416. * @param {Node<float>} [lodNode=float(3)] - Defines the LOD to sample from.
  13417. * @return {Node} The filtered texture sample.
  13418. */
  13419. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  13420. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  13421. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  13422. const fLodSizeInv = div( 1.0, fLodSize );
  13423. const cLodSizeInv = div( 1.0, cLodSize );
  13424. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  13425. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  13426. return fract( lodNode ).mix( fSample, cSample );
  13427. } );
  13428. //
  13429. // Transmission
  13430. //
  13431. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  13432. // Direction of refracted light.
  13433. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  13434. // Compute rotation-independent scaling of the model matrix.
  13435. const modelScale = vec3(
  13436. length( modelMatrix[ 0 ].xyz ),
  13437. length( modelMatrix[ 1 ].xyz ),
  13438. length( modelMatrix[ 2 ].xyz )
  13439. );
  13440. // The thickness is specified in local space.
  13441. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  13442. } ).setLayout( {
  13443. name: 'getVolumeTransmissionRay',
  13444. type: 'vec3',
  13445. inputs: [
  13446. { name: 'n', type: 'vec3' },
  13447. { name: 'v', type: 'vec3' },
  13448. { name: 'thickness', type: 'float' },
  13449. { name: 'ior', type: 'float' },
  13450. { name: 'modelMatrix', type: 'mat4' }
  13451. ]
  13452. } );
  13453. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  13454. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  13455. // an IOR of 1.5 results in the default amount of microfacet refraction.
  13456. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  13457. } ).setLayout( {
  13458. name: 'applyIorToRoughness',
  13459. type: 'float',
  13460. inputs: [
  13461. { name: 'roughness', type: 'float' },
  13462. { name: 'ior', type: 'float' }
  13463. ]
  13464. } );
  13465. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  13466. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  13467. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  13468. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  13469. const transmissionSample = vTexture.sample( fragCoord );
  13470. //const transmissionSample = viewportMipTexture( fragCoord );
  13471. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  13472. return textureBicubic( transmissionSample, lod );
  13473. } );
  13474. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  13475. If( attenuationDistance.notEqual( 0 ), () => {
  13476. // Compute light attenuation using Beer's law.
  13477. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  13478. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  13479. return transmittance;
  13480. } );
  13481. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  13482. return vec3( 1.0 );
  13483. } ).setLayout( {
  13484. name: 'volumeAttenuation',
  13485. type: 'vec3',
  13486. inputs: [
  13487. { name: 'transmissionDistance', type: 'float' },
  13488. { name: 'attenuationColor', type: 'vec3' },
  13489. { name: 'attenuationDistance', type: 'float' }
  13490. ]
  13491. } );
  13492. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  13493. let transmittedLight, transmittance;
  13494. if ( dispersion ) {
  13495. transmittedLight = vec4().toVar();
  13496. transmittance = vec3().toVar();
  13497. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  13498. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  13499. Loop( { start: 0, end: 3 }, ( { i } ) => {
  13500. const ior = iors.element( i );
  13501. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  13502. const refractedRayExit = position.add( transmissionRay );
  13503. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  13504. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  13505. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  13506. refractionCoords.addAssign( 1.0 );
  13507. refractionCoords.divAssign( 2.0 );
  13508. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  13509. // Sample framebuffer to get pixel the refracted ray hits.
  13510. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  13511. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  13512. transmittedLight.a.addAssign( transmissionSample.a );
  13513. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  13514. } );
  13515. transmittedLight.a.divAssign( 3.0 );
  13516. } else {
  13517. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  13518. const refractedRayExit = position.add( transmissionRay );
  13519. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  13520. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  13521. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  13522. refractionCoords.addAssign( 1.0 );
  13523. refractionCoords.divAssign( 2.0 );
  13524. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  13525. // Sample framebuffer to get pixel the refracted ray hits.
  13526. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  13527. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  13528. }
  13529. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  13530. const dotNV = n.dot( v ).clamp();
  13531. // Get the specular component.
  13532. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  13533. dotNV,
  13534. specularColor,
  13535. specularF90,
  13536. roughness
  13537. } ) );
  13538. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  13539. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  13540. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  13541. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  13542. } );
  13543. //
  13544. // Iridescence
  13545. //
  13546. // XYZ to linear-sRGB color space
  13547. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  13548. 3.2404542, - 0.9692660, 0.0556434,
  13549. - 1.5371385, 1.8760108, - 0.2040259,
  13550. - 0.4985314, 0.0415560, 1.0572252
  13551. );
  13552. // Assume air interface for top
  13553. // Note: We don't handle the case fresnel0 == 1
  13554. const Fresnel0ToIor = ( fresnel0 ) => {
  13555. const sqrtF0 = fresnel0.sqrt();
  13556. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  13557. };
  13558. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  13559. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  13560. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  13561. };
  13562. // Fresnel equations for dielectric/dielectric interfaces.
  13563. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  13564. // Evaluation XYZ sensitivity curves in Fourier space
  13565. const evalSensitivity = ( OPD, shift ) => {
  13566. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  13567. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  13568. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  13569. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  13570. 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() );
  13571. 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() );
  13572. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  13573. const rgb = XYZ_TO_REC709.mul( xyz );
  13574. return rgb;
  13575. };
  13576. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  13577. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  13578. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  13579. // Evaluate the cosTheta on the base layer (Snell law)
  13580. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  13581. // Handle TIR:
  13582. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  13583. If( cosTheta2Sq.lessThan( 0 ), () => {
  13584. return vec3( 1.0 );
  13585. } );
  13586. const cosTheta2 = cosTheta2Sq.sqrt();
  13587. // First interface
  13588. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  13589. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  13590. //const R21 = R12;
  13591. const T121 = R12.oneMinus();
  13592. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  13593. const phi21 = float( Math.PI ).sub( phi12 );
  13594. // Second interface
  13595. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  13596. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  13597. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  13598. const phi23 = vec3(
  13599. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  13600. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  13601. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  13602. );
  13603. // Phase shift
  13604. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  13605. const phi = vec3( phi21 ).add( phi23 );
  13606. // Compound terms
  13607. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  13608. const r123 = R123.sqrt();
  13609. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  13610. // Reflectance term for m = 0 (DC term amplitude)
  13611. const C0 = R12.add( Rs );
  13612. const I = C0.toVar();
  13613. // Reflectance term for m > 0 (pairs of diracs)
  13614. const Cm = Rs.sub( T121 ).toVar();
  13615. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  13616. Cm.mulAssign( r123 );
  13617. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  13618. I.addAssign( Cm.mul( Sm ) );
  13619. } );
  13620. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  13621. return I.max( vec3( 0.0 ) );
  13622. } ).setLayout( {
  13623. name: 'evalIridescence',
  13624. type: 'vec3',
  13625. inputs: [
  13626. { name: 'outsideIOR', type: 'float' },
  13627. { name: 'eta2', type: 'float' },
  13628. { name: 'cosTheta1', type: 'float' },
  13629. { name: 'thinFilmThickness', type: 'float' },
  13630. { name: 'baseF0', type: 'vec3' }
  13631. ]
  13632. } );
  13633. //
  13634. // Sheen
  13635. //
  13636. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  13637. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  13638. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  13639. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  13640. const dotNV = normal.dot( viewDir ).saturate();
  13641. const r2 = roughness.pow2();
  13642. const a = select(
  13643. roughness.lessThan( 0.25 ),
  13644. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  13645. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  13646. );
  13647. const b = select(
  13648. roughness.lessThan( 0.25 ),
  13649. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  13650. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  13651. );
  13652. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  13653. return DG.mul( 1.0 / Math.PI ).saturate();
  13654. } );
  13655. const clearcoatF0 = vec3( 0.04 );
  13656. const clearcoatF90 = float( 1 );
  13657. /**
  13658. * Represents the lighting model for a PBR material.
  13659. *
  13660. * @augments LightingModel
  13661. */
  13662. class PhysicalLightingModel extends LightingModel {
  13663. /**
  13664. * Constructs a new physical lighting model.
  13665. *
  13666. * @param {Boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  13667. * @param {Boolean} [sheen=false] - Whether sheen is supported or not.
  13668. * @param {Boolean} [iridescence=false] - Whether iridescence is supported or not.
  13669. * @param {Boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  13670. * @param {Boolean} [transmission=false] - Whether transmission is supported or not.
  13671. * @param {Boolean} [dispersion=false] - Whether dispersion is supported or not.
  13672. */
  13673. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  13674. super();
  13675. /**
  13676. * Whether clearcoat is supported or not.
  13677. *
  13678. * @type {Boolean}
  13679. * @default false
  13680. */
  13681. this.clearcoat = clearcoat;
  13682. /**
  13683. * Whether sheen is supported or not.
  13684. *
  13685. * @type {Boolean}
  13686. * @default false
  13687. */
  13688. this.sheen = sheen;
  13689. /**
  13690. * Whether iridescence is supported or not.
  13691. *
  13692. * @type {Boolean}
  13693. * @default false
  13694. */
  13695. this.iridescence = iridescence;
  13696. /**
  13697. * Whether anisotropy is supported or not.
  13698. *
  13699. * @type {Boolean}
  13700. * @default false
  13701. */
  13702. this.anisotropy = anisotropy;
  13703. /**
  13704. * Whether transmission is supported or not.
  13705. *
  13706. * @type {Boolean}
  13707. * @default false
  13708. */
  13709. this.transmission = transmission;
  13710. /**
  13711. * Whether dispersion is supported or not.
  13712. *
  13713. * @type {Boolean}
  13714. * @default false
  13715. */
  13716. this.dispersion = dispersion;
  13717. /**
  13718. * The clear coat radiance.
  13719. *
  13720. * @type {Node?}
  13721. * @default null
  13722. */
  13723. this.clearcoatRadiance = null;
  13724. /**
  13725. * The clear coat specular direct.
  13726. *
  13727. * @type {Node?}
  13728. * @default null
  13729. */
  13730. this.clearcoatSpecularDirect = null;
  13731. /**
  13732. * The clear coat specular indirect.
  13733. *
  13734. * @type {Node?}
  13735. * @default null
  13736. */
  13737. this.clearcoatSpecularIndirect = null;
  13738. /**
  13739. * The sheen specular direct.
  13740. *
  13741. * @type {Node?}
  13742. * @default null
  13743. */
  13744. this.sheenSpecularDirect = null;
  13745. /**
  13746. * The sheen specular indirect.
  13747. *
  13748. * @type {Node?}
  13749. * @default null
  13750. */
  13751. this.sheenSpecularIndirect = null;
  13752. /**
  13753. * The iridescence Fresnel.
  13754. *
  13755. * @type {Node?}
  13756. * @default null
  13757. */
  13758. this.iridescenceFresnel = null;
  13759. /**
  13760. * The iridescence F0.
  13761. *
  13762. * @type {Node?}
  13763. * @default null
  13764. */
  13765. this.iridescenceF0 = null;
  13766. }
  13767. /**
  13768. * Depending on what features are requested, the method prepares certain node variables
  13769. * which are later used for lighting computations.
  13770. *
  13771. * @param {ContextNode} context - The current node context.
  13772. */
  13773. start( context ) {
  13774. if ( this.clearcoat === true ) {
  13775. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  13776. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  13777. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  13778. }
  13779. if ( this.sheen === true ) {
  13780. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  13781. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  13782. }
  13783. if ( this.iridescence === true ) {
  13784. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  13785. this.iridescenceFresnel = evalIridescence( {
  13786. outsideIOR: float( 1.0 ),
  13787. eta2: iridescenceIOR,
  13788. cosTheta1: dotNVi,
  13789. thinFilmThickness: iridescenceThickness,
  13790. baseF0: specularColor
  13791. } );
  13792. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  13793. }
  13794. if ( this.transmission === true ) {
  13795. const position = positionWorld;
  13796. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  13797. const n = transformedNormalWorld;
  13798. context.backdrop = getIBLVolumeRefraction(
  13799. n,
  13800. v,
  13801. roughness,
  13802. diffuseColor,
  13803. specularColor,
  13804. specularF90, // specularF90
  13805. position, // positionWorld
  13806. modelWorldMatrix, // modelMatrix
  13807. cameraViewMatrix, // viewMatrix
  13808. cameraProjectionMatrix, // projMatrix
  13809. ior,
  13810. thickness,
  13811. attenuationColor,
  13812. attenuationDistance,
  13813. this.dispersion ? dispersion : null
  13814. );
  13815. context.backdropAlpha = transmission;
  13816. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  13817. }
  13818. }
  13819. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  13820. // Approximates multi-scattering in order to preserve energy.
  13821. // http://www.jcgt.org/published/0008/01/03/
  13822. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  13823. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13824. const fab = DFGApprox( { roughness, dotNV } );
  13825. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  13826. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  13827. const Ess = fab.x.add( fab.y );
  13828. const Ems = Ess.oneMinus();
  13829. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  13830. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  13831. singleScatter.addAssign( FssEss );
  13832. multiScatter.addAssign( Fms.mul( Ems ) );
  13833. }
  13834. /**
  13835. * Implements the direct light.
  13836. *
  13837. * @param {Object} input - The input data.
  13838. * @param {StackNode} stack - The current stack.
  13839. * @param {NodeBuilder} builder - The current node builder.
  13840. */
  13841. direct( { lightDirection, lightColor, reflectedLight } ) {
  13842. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  13843. const irradiance = dotNL.mul( lightColor );
  13844. if ( this.sheen === true ) {
  13845. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  13846. }
  13847. if ( this.clearcoat === true ) {
  13848. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  13849. const ccIrradiance = dotNLcc.mul( lightColor );
  13850. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  13851. }
  13852. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  13853. 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 } ) ) );
  13854. }
  13855. /**
  13856. * This method is intended for implementing the direct light term for
  13857. * rect area light nodes.
  13858. *
  13859. * @param {Object} input - The input data.
  13860. * @param {StackNode} stack - The current stack.
  13861. * @param {NodeBuilder} builder - The current node builder.
  13862. */
  13863. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  13864. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  13865. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  13866. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  13867. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  13868. const N = transformedNormalView;
  13869. const V = positionViewDirection;
  13870. const P = positionView.toVar();
  13871. const uv = LTC_Uv( { N, V, roughness } );
  13872. const t1 = ltc_1.sample( uv ).toVar();
  13873. const t2 = ltc_2.sample( uv ).toVar();
  13874. const mInv = mat3(
  13875. vec3( t1.x, 0, t1.y ),
  13876. vec3( 0, 1, 0 ),
  13877. vec3( t1.z, 0, t1.w )
  13878. ).toVar();
  13879. // LTC Fresnel Approximation by Stephen Hill
  13880. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  13881. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  13882. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  13883. 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 } ) ) );
  13884. }
  13885. /**
  13886. * Implements the indirect lighting.
  13887. *
  13888. * @param {ContextNode} context - The current node context.
  13889. * @param {StackNode} stack - The current stack.
  13890. * @param {NodeBuilder} builder - The current node builder.
  13891. */
  13892. indirect( context, stack, builder ) {
  13893. this.indirectDiffuse( context, stack, builder );
  13894. this.indirectSpecular( context, stack, builder );
  13895. this.ambientOcclusion( context, stack, builder );
  13896. }
  13897. /**
  13898. * Implements the indirect diffuse term.
  13899. *
  13900. * @param {ContextNode} input - The current node context.
  13901. * @param {StackNode} stack - The current stack.
  13902. * @param {NodeBuilder} builder - The current node builder.
  13903. */
  13904. indirectDiffuse( { irradiance, reflectedLight } ) {
  13905. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  13906. }
  13907. /**
  13908. * Implements the indirect specular term.
  13909. *
  13910. * @param {ContextNode} input - The current node context.
  13911. * @param {StackNode} stack - The current stack.
  13912. * @param {NodeBuilder} builder - The current node builder.
  13913. */
  13914. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  13915. if ( this.sheen === true ) {
  13916. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  13917. sheen,
  13918. IBLSheenBRDF( {
  13919. normal: transformedNormalView,
  13920. viewDir: positionViewDirection,
  13921. roughness: sheenRoughness
  13922. } )
  13923. ) );
  13924. }
  13925. if ( this.clearcoat === true ) {
  13926. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  13927. const clearcoatEnv = EnvironmentBRDF( {
  13928. dotNV: dotNVcc,
  13929. specularColor: clearcoatF0,
  13930. specularF90: clearcoatF90,
  13931. roughness: clearcoatRoughness
  13932. } );
  13933. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  13934. }
  13935. // Both indirect specular and indirect diffuse light accumulate here
  13936. const singleScattering = vec3().toVar( 'singleScattering' );
  13937. const multiScattering = vec3().toVar( 'multiScattering' );
  13938. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  13939. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  13940. const totalScattering = singleScattering.add( multiScattering );
  13941. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  13942. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  13943. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  13944. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  13945. }
  13946. /**
  13947. * Implements the ambient occlusion term.
  13948. *
  13949. * @param {ContextNode} input - The current node context.
  13950. * @param {StackNode} stack - The current stack.
  13951. * @param {NodeBuilder} builder - The current node builder.
  13952. */
  13953. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  13954. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13955. const aoNV = dotNV.add( ambientOcclusion );
  13956. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  13957. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  13958. if ( this.clearcoat === true ) {
  13959. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  13960. }
  13961. if ( this.sheen === true ) {
  13962. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  13963. }
  13964. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  13965. reflectedLight.indirectSpecular.mulAssign( aoNode );
  13966. }
  13967. /**
  13968. * Used for final lighting accumulations depending on the requested features.
  13969. *
  13970. * @param {ContextNode} context - The current node context.
  13971. * @param {StackNode} stack - The current stack.
  13972. * @param {NodeBuilder} builder - The current node builder.
  13973. */
  13974. finish( context ) {
  13975. const { outgoingLight } = context;
  13976. if ( this.clearcoat === true ) {
  13977. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  13978. const Fcc = F_Schlick( {
  13979. dotVH: dotNVcc,
  13980. f0: clearcoatF0,
  13981. f90: clearcoatF90
  13982. } );
  13983. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  13984. outgoingLight.assign( clearcoatLight );
  13985. }
  13986. if ( this.sheen === true ) {
  13987. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  13988. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  13989. outgoingLight.assign( sheenLight );
  13990. }
  13991. }
  13992. }
  13993. // These defines must match with PMREMGenerator
  13994. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  13995. const cubeUV_m0 = /*@__PURE__*/ float( - 2.0 );
  13996. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  13997. const cubeUV_m1 = /*@__PURE__*/ float( - 1.0 );
  13998. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  13999. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  14000. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  14001. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  14002. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  14003. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  14004. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  14005. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  14006. // These shader functions convert between the UV coordinates of a single face of
  14007. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  14008. // sampling a textureCube (not generally normalized ).
  14009. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  14010. const absDirection = vec3( abs( direction ) ).toVar();
  14011. const face = float( - 1.0 ).toVar();
  14012. If( absDirection.x.greaterThan( absDirection.z ), () => {
  14013. If( absDirection.x.greaterThan( absDirection.y ), () => {
  14014. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  14015. } ).Else( () => {
  14016. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  14017. } );
  14018. } ).Else( () => {
  14019. If( absDirection.z.greaterThan( absDirection.y ), () => {
  14020. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  14021. } ).Else( () => {
  14022. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  14023. } );
  14024. } );
  14025. return face;
  14026. } ).setLayout( {
  14027. name: 'getFace',
  14028. type: 'float',
  14029. inputs: [
  14030. { name: 'direction', type: 'vec3' }
  14031. ]
  14032. } );
  14033. // RH coordinate system; PMREM face-indexing convention
  14034. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  14035. const uv = vec2().toVar();
  14036. If( face.equal( 0.0 ), () => {
  14037. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  14038. } ).ElseIf( face.equal( 1.0 ), () => {
  14039. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  14040. } ).ElseIf( face.equal( 2.0 ), () => {
  14041. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  14042. } ).ElseIf( face.equal( 3.0 ), () => {
  14043. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  14044. } ).ElseIf( face.equal( 4.0 ), () => {
  14045. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  14046. } ).Else( () => {
  14047. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  14048. } );
  14049. return mul( 0.5, uv.add( 1.0 ) );
  14050. } ).setLayout( {
  14051. name: 'getUV',
  14052. type: 'vec2',
  14053. inputs: [
  14054. { name: 'direction', type: 'vec3' },
  14055. { name: 'face', type: 'float' }
  14056. ]
  14057. } );
  14058. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  14059. const mip = float( 0.0 ).toVar();
  14060. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  14061. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  14062. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  14063. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  14064. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  14065. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  14066. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  14067. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  14068. } ).Else( () => {
  14069. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  14070. } );
  14071. return mip;
  14072. } ).setLayout( {
  14073. name: 'roughnessToMip',
  14074. type: 'float',
  14075. inputs: [
  14076. { name: 'roughness', type: 'float' }
  14077. ]
  14078. } );
  14079. // RH coordinate system; PMREM face-indexing convention
  14080. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  14081. const uv = uv_immutable.toVar();
  14082. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  14083. const direction = vec3( uv, 1.0 ).toVar();
  14084. If( face.equal( 0.0 ), () => {
  14085. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  14086. } ).ElseIf( face.equal( 1.0 ), () => {
  14087. direction.assign( direction.xzy );
  14088. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  14089. } ).ElseIf( face.equal( 2.0 ), () => {
  14090. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  14091. } ).ElseIf( face.equal( 3.0 ), () => {
  14092. direction.assign( direction.zyx );
  14093. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  14094. } ).ElseIf( face.equal( 4.0 ), () => {
  14095. direction.assign( direction.xzy );
  14096. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  14097. } ).ElseIf( face.equal( 5.0 ), () => {
  14098. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  14099. } );
  14100. return direction;
  14101. } ).setLayout( {
  14102. name: 'getDirection',
  14103. type: 'vec3',
  14104. inputs: [
  14105. { name: 'uv', type: 'vec2' },
  14106. { name: 'face', type: 'float' }
  14107. ]
  14108. } );
  14109. //
  14110. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  14111. const roughness = float( roughness_immutable );
  14112. const sampleDir = vec3( sampleDir_immutable );
  14113. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  14114. const mipF = fract( mip );
  14115. const mipInt = floor( mip );
  14116. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  14117. If( mipF.notEqual( 0.0 ), () => {
  14118. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  14119. color0.assign( mix( color0, color1, mipF ) );
  14120. } );
  14121. return color0;
  14122. } );
  14123. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  14124. const mipInt = float( mipInt_immutable ).toVar();
  14125. const direction = vec3( direction_immutable );
  14126. const face = float( getFace( direction ) ).toVar();
  14127. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  14128. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  14129. const faceSize = float( exp2( mipInt ) ).toVar();
  14130. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  14131. If( face.greaterThan( 2.0 ), () => {
  14132. uv.y.addAssign( faceSize );
  14133. face.subAssign( 3.0 );
  14134. } );
  14135. uv.x.addAssign( face.mul( faceSize ) );
  14136. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  14137. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  14138. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  14139. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  14140. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  14141. } );
  14142. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  14143. const cosTheta = cos( theta );
  14144. // Rodrigues' axis-angle rotation
  14145. const sampleDirection = outputDirection.mul( cosTheta )
  14146. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  14147. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  14148. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  14149. } );
  14150. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  14151. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  14152. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  14153. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  14154. } );
  14155. axis.assign( normalize( axis ) );
  14156. const gl_FragColor = vec3().toVar();
  14157. 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 } ) ) );
  14158. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  14159. If( i.greaterThanEqual( samples ), () => {
  14160. Break();
  14161. } );
  14162. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  14163. 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 } ) ) );
  14164. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14165. } );
  14166. return vec4( gl_FragColor, 1 );
  14167. } );
  14168. /** @module PMREMNode **/
  14169. let _generator = null;
  14170. const _cache = new WeakMap();
  14171. /**
  14172. * Generates the cubeUV size based on the given image height.
  14173. *
  14174. * @private
  14175. * @param {Number} imageHeight - The image height.
  14176. * @return {{texelWidth: Number,texelHeight: Number, maxMip: Number}} The result object.
  14177. */
  14178. function _generateCubeUVSize( imageHeight ) {
  14179. const maxMip = Math.log2( imageHeight ) - 2;
  14180. const texelHeight = 1.0 / imageHeight;
  14181. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  14182. return { texelWidth, texelHeight, maxMip };
  14183. }
  14184. /**
  14185. * Generates a PMREM from the given texture .
  14186. *
  14187. * @private
  14188. * @param {Texture} texture - The texture to create the PMREM for.
  14189. * @return {Texture} The PMREM.
  14190. */
  14191. function _getPMREMFromTexture( texture ) {
  14192. let cacheTexture = _cache.get( texture );
  14193. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  14194. if ( pmremVersion !== texture.pmremVersion ) {
  14195. const image = texture.image;
  14196. if ( texture.isCubeTexture ) {
  14197. if ( isCubeMapReady( image ) ) {
  14198. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  14199. } else {
  14200. return null;
  14201. }
  14202. } else {
  14203. if ( isEquirectangularMapReady( image ) ) {
  14204. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  14205. } else {
  14206. return null;
  14207. }
  14208. }
  14209. cacheTexture.pmremVersion = texture.pmremVersion;
  14210. _cache.set( texture, cacheTexture );
  14211. }
  14212. return cacheTexture.texture;
  14213. }
  14214. /**
  14215. * This node represents a PMREM which is a special type of preprocessed
  14216. * environment map intended for PBR materials.
  14217. *
  14218. * ```js
  14219. * const material = new MeshStandardNodeMaterial();
  14220. * material.envNode = pmremTexture( envMap );
  14221. * ```
  14222. *
  14223. * @augments TempNode
  14224. */
  14225. class PMREMNode extends TempNode {
  14226. static get type() {
  14227. return 'PMREMNode';
  14228. }
  14229. /**
  14230. * Constructs a new function overloading node.
  14231. *
  14232. * @param {Texture} value - The input texture.
  14233. * @param {Node<vec2>} [uvNode=null] - The uv node.
  14234. * @param {Node<float>} [levelNode=null] - The level node.
  14235. */
  14236. constructor( value, uvNode = null, levelNode = null ) {
  14237. super( 'vec3' );
  14238. /**
  14239. * Reference to the input texture.
  14240. *
  14241. * @private
  14242. * @type {Texture}
  14243. */
  14244. this._value = value;
  14245. /**
  14246. * Reference to the generated PMREM.
  14247. *
  14248. * @private
  14249. * @type {Texture | null}
  14250. * @default null
  14251. */
  14252. this._pmrem = null;
  14253. /**
  14254. * The uv node.
  14255. *
  14256. * @type {Node<vec2>}
  14257. */
  14258. this.uvNode = uvNode;
  14259. /**
  14260. * The level node.
  14261. *
  14262. * @type {Node<float>}
  14263. */
  14264. this.levelNode = levelNode;
  14265. /**
  14266. * Reference to a PMREM generator.
  14267. *
  14268. * @private
  14269. * @type {PMREMGenerator}
  14270. * @default null
  14271. */
  14272. this._generator = null;
  14273. const defaultTexture = new Texture();
  14274. defaultTexture.isRenderTargetTexture = true;
  14275. /**
  14276. * The texture node holding the generated PMREM.
  14277. *
  14278. * @private
  14279. * @type {TextureNode}
  14280. */
  14281. this._texture = texture( defaultTexture );
  14282. /**
  14283. * A uniform representing the PMREM's width.
  14284. *
  14285. * @private
  14286. * @type {UniformNode<float>}
  14287. */
  14288. this._width = uniform( 0 );
  14289. /**
  14290. * A uniform representing the PMREM's height.
  14291. *
  14292. * @private
  14293. * @type {UniformNode<float>}
  14294. */
  14295. this._height = uniform( 0 );
  14296. /**
  14297. * A uniform representing the PMREM's max Mip.
  14298. *
  14299. * @private
  14300. * @type {UniformNode<float>}
  14301. */
  14302. this._maxMip = uniform( 0 );
  14303. /**
  14304. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  14305. *
  14306. * @type {String}
  14307. * @default 'render'
  14308. */
  14309. this.updateBeforeType = NodeUpdateType.RENDER;
  14310. }
  14311. set value( value ) {
  14312. this._value = value;
  14313. this._pmrem = null;
  14314. }
  14315. /**
  14316. * The node's texture value.
  14317. *
  14318. * @type {Texture}
  14319. */
  14320. get value() {
  14321. return this._value;
  14322. }
  14323. /**
  14324. * Uses the given PMREM texture to update internal values.
  14325. *
  14326. * @param {Texture} texture - The PMREM texture.
  14327. */
  14328. updateFromTexture( texture ) {
  14329. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  14330. this._texture.value = texture;
  14331. this._width.value = cubeUVSize.texelWidth;
  14332. this._height.value = cubeUVSize.texelHeight;
  14333. this._maxMip.value = cubeUVSize.maxMip;
  14334. }
  14335. updateBefore() {
  14336. let pmrem = this._pmrem;
  14337. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  14338. const texture = this._value;
  14339. if ( pmremVersion !== texture.pmremVersion ) {
  14340. if ( texture.isPMREMTexture === true ) {
  14341. pmrem = texture;
  14342. } else {
  14343. pmrem = _getPMREMFromTexture( texture );
  14344. }
  14345. if ( pmrem !== null ) {
  14346. this._pmrem = pmrem;
  14347. this.updateFromTexture( pmrem );
  14348. }
  14349. }
  14350. }
  14351. setup( builder ) {
  14352. if ( _generator === null ) {
  14353. _generator = builder.createPMREMGenerator();
  14354. }
  14355. //
  14356. this.updateBefore( builder );
  14357. //
  14358. let uvNode = this.uvNode;
  14359. if ( uvNode === null && builder.context.getUV ) {
  14360. uvNode = builder.context.getUV( this );
  14361. }
  14362. //
  14363. const texture = this.value;
  14364. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  14365. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  14366. }
  14367. uvNode = vec3( uvNode.x, uvNode.y.negate(), uvNode.z );
  14368. //
  14369. let levelNode = this.levelNode;
  14370. if ( levelNode === null && builder.context.getTextureLevel ) {
  14371. levelNode = builder.context.getTextureLevel( this );
  14372. }
  14373. //
  14374. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  14375. }
  14376. }
  14377. /**
  14378. * Returns `true` if the given cube map image has been fully loaded.
  14379. *
  14380. * @private
  14381. * @param {Array<(Image|Object)>} image - The cube map image.
  14382. * @return {Boolean} Whether the given cube map is ready or not.
  14383. */
  14384. function isCubeMapReady( image ) {
  14385. if ( image === null || image === undefined ) return false;
  14386. let count = 0;
  14387. const length = 6;
  14388. for ( let i = 0; i < length; i ++ ) {
  14389. if ( image[ i ] !== undefined ) count ++;
  14390. }
  14391. return count === length;
  14392. }
  14393. /**
  14394. * Returns `true` if the given equirectangular image has been fully loaded.
  14395. *
  14396. * @private
  14397. * @param {(Image|Object)} image - The equirectangular image.
  14398. * @return {Boolean} Whether the given cube map is ready or not.
  14399. */
  14400. function isEquirectangularMapReady( image ) {
  14401. if ( image === null || image === undefined ) return false;
  14402. return image.height > 0;
  14403. }
  14404. /**
  14405. * TSL function for creating a PMREM node.
  14406. *
  14407. * @function
  14408. * @param {Texture} value - The input texture.
  14409. * @param {Node<vec2>} [uvNode=null] - The uv node.
  14410. * @param {Node<float>} [levelNode=null] - The level node.
  14411. * @returns {PMREMNode}
  14412. */
  14413. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  14414. const _envNodeCache = new WeakMap();
  14415. /**
  14416. * Represents a physical model for Image-based lighting (IBL). The environment
  14417. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  14418. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  14419. *
  14420. * @augments LightingNode
  14421. */
  14422. class EnvironmentNode extends LightingNode {
  14423. static get type() {
  14424. return 'EnvironmentNode';
  14425. }
  14426. /**
  14427. * Constructs a new environment node.
  14428. *
  14429. * @param {Node} [envNode=null] - A node representing the environment.
  14430. */
  14431. constructor( envNode = null ) {
  14432. super();
  14433. /**
  14434. * A node representing the environment.
  14435. *
  14436. * @type {Node?}
  14437. * @default null
  14438. */
  14439. this.envNode = envNode;
  14440. }
  14441. setup( builder ) {
  14442. const { material } = builder;
  14443. let envNode = this.envNode;
  14444. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  14445. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  14446. let cacheEnvNode = _envNodeCache.get( value );
  14447. if ( cacheEnvNode === undefined ) {
  14448. cacheEnvNode = pmremTexture( value );
  14449. _envNodeCache.set( value, cacheEnvNode );
  14450. }
  14451. envNode = cacheEnvNode;
  14452. }
  14453. //
  14454. const envMap = material.envMap;
  14455. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  14456. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  14457. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  14458. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  14459. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  14460. const isolateRadiance = cache( radiance );
  14461. const isolateIrradiance = cache( irradiance );
  14462. //
  14463. builder.context.radiance.addAssign( isolateRadiance );
  14464. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  14465. //
  14466. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  14467. if ( clearcoatRadiance ) {
  14468. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  14469. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  14470. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  14471. }
  14472. }
  14473. }
  14474. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  14475. let reflectVec = null;
  14476. return {
  14477. getUV: () => {
  14478. if ( reflectVec === null ) {
  14479. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  14480. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  14481. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  14482. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  14483. }
  14484. return reflectVec;
  14485. },
  14486. getTextureLevel: () => {
  14487. return roughnessNode;
  14488. }
  14489. };
  14490. };
  14491. const createIrradianceContext = ( normalWorldNode ) => {
  14492. return {
  14493. getUV: () => {
  14494. return normalWorldNode;
  14495. },
  14496. getTextureLevel: () => {
  14497. return float( 1.0 );
  14498. }
  14499. };
  14500. };
  14501. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  14502. /**
  14503. * Node material version of `MeshStandardMaterial`.
  14504. *
  14505. * @augments NodeMaterial
  14506. */
  14507. class MeshStandardNodeMaterial extends NodeMaterial {
  14508. static get type() {
  14509. return 'MeshStandardNodeMaterial';
  14510. }
  14511. /**
  14512. * Constructs a new mesh standard node material.
  14513. *
  14514. * @param {Object?} parameters - The configuration parameter.
  14515. */
  14516. constructor( parameters ) {
  14517. super();
  14518. /**
  14519. * This flag can be used for type testing.
  14520. *
  14521. * @type {Boolean}
  14522. * @readonly
  14523. * @default true
  14524. */
  14525. this.isMeshStandardNodeMaterial = true;
  14526. /**
  14527. * Set to `true` because standard materials react on lights.
  14528. *
  14529. * @type {Boolean}
  14530. * @default true
  14531. */
  14532. this.lights = true;
  14533. /**
  14534. * The emissive color of standard materials is by default inferred from the `emissive`,
  14535. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  14536. * overwrite the default and define the emissive color with a node instead.
  14537. *
  14538. * If you don't want to overwrite the emissive color but modify the existing
  14539. * value instead, use {@link module:MaterialNode.materialEmissive}.
  14540. *
  14541. * @type {Node<vec3>?}
  14542. * @default null
  14543. */
  14544. this.emissiveNode = null;
  14545. /**
  14546. * The metalness of standard materials is by default inferred from the `metalness`,
  14547. * and `metalnessMap` properties. This node property allows to
  14548. * overwrite the default and define the metalness with a node instead.
  14549. *
  14550. * If you don't want to overwrite the metalness but modify the existing
  14551. * value instead, use {@link module:MaterialNode.materialMetalness}.
  14552. *
  14553. * @type {Node<float>?}
  14554. * @default null
  14555. */
  14556. this.metalnessNode = null;
  14557. /**
  14558. * The roughness of standard materials is by default inferred from the `roughness`,
  14559. * and `roughnessMap` properties. This node property allows to
  14560. * overwrite the default and define the roughness with a node instead.
  14561. *
  14562. * If you don't want to overwrite the roughness but modify the existing
  14563. * value instead, use {@link module:MaterialNode.materialRoughness}.
  14564. *
  14565. * @type {Node<float>?}
  14566. * @default null
  14567. */
  14568. this.roughnessNode = null;
  14569. this.setDefaultValues( _defaultValues$6 );
  14570. this.setValues( parameters );
  14571. }
  14572. /**
  14573. * Overwritten since this type of material uses {@link EnvironmentNode}
  14574. * to implement the PBR (PMREM based) environment mapping. Besides, the
  14575. * method honors `Scene.environment`.
  14576. *
  14577. * @param {NodeBuilder} builder - The current node builder.
  14578. * @return {EnvironmentNode<vec3>?} The environment node.
  14579. */
  14580. setupEnvironment( builder ) {
  14581. let envNode = super.setupEnvironment( builder );
  14582. if ( envNode === null && builder.environmentNode ) {
  14583. envNode = builder.environmentNode;
  14584. }
  14585. return envNode ? new EnvironmentNode( envNode ) : null;
  14586. }
  14587. /**
  14588. * Setups the lighting model.
  14589. *
  14590. * @return {PhysicalLightingModel} The lighting model.
  14591. */
  14592. setupLightingModel( /*builder*/ ) {
  14593. return new PhysicalLightingModel();
  14594. }
  14595. /**
  14596. * Setups the specular related node variables.
  14597. */
  14598. setupSpecular() {
  14599. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  14600. specularColor.assign( specularColorNode );
  14601. specularF90.assign( 1.0 );
  14602. }
  14603. /**
  14604. * Setups the standard specific node variables.
  14605. *
  14606. * @param {NodeBuilder} builder - The current node builder.
  14607. */
  14608. setupVariants() {
  14609. // METALNESS
  14610. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  14611. metalness.assign( metalnessNode );
  14612. // ROUGHNESS
  14613. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  14614. roughnessNode = getRoughness( { roughness: roughnessNode } );
  14615. roughness.assign( roughnessNode );
  14616. // SPECULAR COLOR
  14617. this.setupSpecular();
  14618. // DIFFUSE COLOR
  14619. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  14620. }
  14621. copy( source ) {
  14622. this.emissiveNode = source.emissiveNode;
  14623. this.metalnessNode = source.metalnessNode;
  14624. this.roughnessNode = source.roughnessNode;
  14625. return super.copy( source );
  14626. }
  14627. }
  14628. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  14629. /**
  14630. * Node material version of `MeshPhysicalMaterial`.
  14631. *
  14632. * @augments MeshStandardNodeMaterial
  14633. */
  14634. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  14635. static get type() {
  14636. return 'MeshPhysicalNodeMaterial';
  14637. }
  14638. /**
  14639. * Constructs a new mesh physical node material.
  14640. *
  14641. * @param {Object?} parameters - The configuration parameter.
  14642. */
  14643. constructor( parameters ) {
  14644. super();
  14645. /**
  14646. * This flag can be used for type testing.
  14647. *
  14648. * @type {Boolean}
  14649. * @readonly
  14650. * @default true
  14651. */
  14652. this.isMeshPhysicalNodeMaterial = true;
  14653. /**
  14654. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  14655. * and `clearcoatMap` properties. This node property allows to overwrite the default
  14656. * and define the clearcoat with a node instead.
  14657. *
  14658. * If you don't want to overwrite the clearcoat but modify the existing
  14659. * value instead, use {@link module:MaterialNode.materialClearcoat}.
  14660. *
  14661. * @type {Node<float>?}
  14662. * @default null
  14663. */
  14664. this.clearcoatNode = null;
  14665. /**
  14666. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  14667. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  14668. * and define the clearcoat roughness with a node instead.
  14669. *
  14670. * If you don't want to overwrite the clearcoat roughness but modify the existing
  14671. * value instead, use {@link module:MaterialNode.materialClearcoatRoughness}.
  14672. *
  14673. * @type {Node<float>?}
  14674. * @default null
  14675. */
  14676. this.clearcoatRoughnessNode = null;
  14677. /**
  14678. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  14679. * property. This node property allows to overwrite the default
  14680. * and define the clearcoat normal with a node instead.
  14681. *
  14682. * If you don't want to overwrite the clearcoat normal but modify the existing
  14683. * value instead, use {@link module:MaterialNode.materialClearcoatNormal}.
  14684. *
  14685. * @type {Node<vec3>?}
  14686. * @default null
  14687. */
  14688. this.clearcoatNormalNode = null;
  14689. /**
  14690. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  14691. * and `sheenColorMap` properties. This node property allows to overwrite the default
  14692. * and define the sheen with a node instead.
  14693. *
  14694. * If you don't want to overwrite the sheen but modify the existing
  14695. * value instead, use {@link module:MaterialNode.materialSheen}.
  14696. *
  14697. * @type {Node<vec3>?}
  14698. * @default null
  14699. */
  14700. this.sheenNode = null;
  14701. /**
  14702. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  14703. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  14704. * and define the sheen roughness with a node instead.
  14705. *
  14706. * If you don't want to overwrite the sheen roughness but modify the existing
  14707. * value instead, use {@link module:MaterialNode.materialSheenRoughness}.
  14708. *
  14709. * @type {Node<float>?}
  14710. * @default null
  14711. */
  14712. this.sheenRoughnessNode = null;
  14713. /**
  14714. * The iridescence of physical materials is by default inferred from the `iridescence`
  14715. * property. This node property allows to overwrite the default
  14716. * and define the iridescence with a node instead.
  14717. *
  14718. * If you don't want to overwrite the iridescence but modify the existing
  14719. * value instead, use {@link module:MaterialNode.materialIridescence}.
  14720. *
  14721. * @type {Node<float>?}
  14722. * @default null
  14723. */
  14724. this.iridescenceNode = null;
  14725. /**
  14726. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  14727. * property. This node property allows to overwrite the default
  14728. * and define the iridescence IOR with a node instead.
  14729. *
  14730. * If you don't want to overwrite the iridescence IOR but modify the existing
  14731. * value instead, use {@link module:MaterialNode.materialIridescenceIOR}.
  14732. *
  14733. * @type {Node<float>?}
  14734. * @default null
  14735. */
  14736. this.iridescenceIORNode = null;
  14737. /**
  14738. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  14739. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  14740. * and define the iridescence thickness with a node instead.
  14741. *
  14742. * If you don't want to overwrite the iridescence thickness but modify the existing
  14743. * value instead, use {@link module:MaterialNode.materialIridescenceThickness}.
  14744. *
  14745. * @type {Node<float>?}
  14746. * @default null
  14747. */
  14748. this.iridescenceThicknessNode = null;
  14749. /**
  14750. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  14751. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  14752. * and define the specular intensity with a node instead.
  14753. *
  14754. * If you don't want to overwrite the specular intensity but modify the existing
  14755. * value instead, use {@link module:MaterialNode.materialSpecularIntensity}.
  14756. *
  14757. * @type {Node<float>?}
  14758. * @default null
  14759. */
  14760. this.specularIntensityNode = null;
  14761. /**
  14762. * The specular color of physical materials is by default inferred from the `specularColor`
  14763. * and `specularColorMap` properties. This node property allows to overwrite the default
  14764. * and define the specular color with a node instead.
  14765. *
  14766. * If you don't want to overwrite the specular color but modify the existing
  14767. * value instead, use {@link module:MaterialNode.materialSpecularColor}.
  14768. *
  14769. * @type {Node<vec3>?}
  14770. * @default null
  14771. */
  14772. this.specularColorNode = null;
  14773. /**
  14774. * The ior of physical materials is by default inferred from the `ior`
  14775. * property. This node property allows to overwrite the default
  14776. * and define the ior with a node instead.
  14777. *
  14778. * If you don't want to overwrite the ior but modify the existing
  14779. * value instead, use {@link module:MaterialNode.materialIOR}.
  14780. *
  14781. * @type {Node<float>?}
  14782. * @default null
  14783. */
  14784. this.iorNode = null;
  14785. /**
  14786. * The transmission of physical materials is by default inferred from the `transmission` and
  14787. * `transmissionMap` properties. This node property allows to overwrite the default
  14788. * and define the transmission with a node instead.
  14789. *
  14790. * If you don't want to overwrite the transmission but modify the existing
  14791. * value instead, use {@link module:MaterialNode.materialTransmission}.
  14792. *
  14793. * @type {Node<float>?}
  14794. * @default null
  14795. */
  14796. this.transmissionNode = null;
  14797. /**
  14798. * The thickness of physical materials is by default inferred from the `thickness` and
  14799. * `thicknessMap` properties. This node property allows to overwrite the default
  14800. * and define the thickness with a node instead.
  14801. *
  14802. * If you don't want to overwrite the thickness but modify the existing
  14803. * value instead, use {@link module:MaterialNode.materialThickness}.
  14804. *
  14805. * @type {Node<float>?}
  14806. * @default null
  14807. */
  14808. this.thicknessNode = null;
  14809. /**
  14810. * The attenuation distance of physical materials is by default inferred from the
  14811. * `attenuationDistance` property. This node property allows to overwrite the default
  14812. * and define the attenuation distance with a node instead.
  14813. *
  14814. * If you don't want to overwrite the attenuation distance but modify the existing
  14815. * value instead, use {@link module:MaterialNode.materialAttenuationDistance}.
  14816. *
  14817. * @type {Node<float>?}
  14818. * @default null
  14819. */
  14820. this.attenuationDistanceNode = null;
  14821. /**
  14822. * The attenuation color of physical materials is by default inferred from the
  14823. * `attenuationColor` property. This node property allows to overwrite the default
  14824. * and define the attenuation color with a node instead.
  14825. *
  14826. * If you don't want to overwrite the attenuation color but modify the existing
  14827. * value instead, use {@link module:MaterialNode.materialAttenuationColor}.
  14828. *
  14829. * @type {Node<vec3>?}
  14830. * @default null
  14831. */
  14832. this.attenuationColorNode = null;
  14833. /**
  14834. * The dispersion of physical materials is by default inferred from the
  14835. * `dispersion` property. This node property allows to overwrite the default
  14836. * and define the dispersion with a node instead.
  14837. *
  14838. * If you don't want to overwrite the dispersion but modify the existing
  14839. * value instead, use {@link module:MaterialNode.materialDispersion}.
  14840. *
  14841. * @type {Node<float>?}
  14842. * @default null
  14843. */
  14844. this.dispersionNode = null;
  14845. /**
  14846. * The anisotropy of physical materials is by default inferred from the
  14847. * `anisotropy` property. This node property allows to overwrite the default
  14848. * and define the anisotropy with a node instead.
  14849. *
  14850. * If you don't want to overwrite the anisotropy but modify the existing
  14851. * value instead, use {@link module:MaterialNode.materialAnisotropy}.
  14852. *
  14853. * @type {Node<float>?}
  14854. * @default null
  14855. */
  14856. this.anisotropyNode = null;
  14857. this.setDefaultValues( _defaultValues$5 );
  14858. this.setValues( parameters );
  14859. }
  14860. /**
  14861. * Whether the lighting model should use clearcoat or not.
  14862. *
  14863. * @type {Boolean}
  14864. * @default true
  14865. */
  14866. get useClearcoat() {
  14867. return this.clearcoat > 0 || this.clearcoatNode !== null;
  14868. }
  14869. /**
  14870. * Whether the lighting model should use iridescence or not.
  14871. *
  14872. * @type {Boolean}
  14873. * @default true
  14874. */
  14875. get useIridescence() {
  14876. return this.iridescence > 0 || this.iridescenceNode !== null;
  14877. }
  14878. /**
  14879. * Whether the lighting model should use sheen or not.
  14880. *
  14881. * @type {Boolean}
  14882. * @default true
  14883. */
  14884. get useSheen() {
  14885. return this.sheen > 0 || this.sheenNode !== null;
  14886. }
  14887. /**
  14888. * Whether the lighting model should use anisotropy or not.
  14889. *
  14890. * @type {Boolean}
  14891. * @default true
  14892. */
  14893. get useAnisotropy() {
  14894. return this.anisotropy > 0 || this.anisotropyNode !== null;
  14895. }
  14896. /**
  14897. * Whether the lighting model should use transmission or not.
  14898. *
  14899. * @type {Boolean}
  14900. * @default true
  14901. */
  14902. get useTransmission() {
  14903. return this.transmission > 0 || this.transmissionNode !== null;
  14904. }
  14905. /**
  14906. * Whether the lighting model should use dispersion or not.
  14907. *
  14908. * @type {Boolean}
  14909. * @default true
  14910. */
  14911. get useDispersion() {
  14912. return this.dispersion > 0 || this.dispersionNode !== null;
  14913. }
  14914. /**
  14915. * Setups the specular related node variables.
  14916. */
  14917. setupSpecular() {
  14918. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  14919. ior.assign( iorNode );
  14920. 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 ) );
  14921. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  14922. }
  14923. /**
  14924. * Setups the lighting model.
  14925. *
  14926. * @return {PhysicalLightingModel} The lighting model.
  14927. */
  14928. setupLightingModel( /*builder*/ ) {
  14929. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  14930. }
  14931. /**
  14932. * Setups the physical specific node variables.
  14933. *
  14934. * @param {NodeBuilder} builder - The current node builder.
  14935. */
  14936. setupVariants( builder ) {
  14937. super.setupVariants( builder );
  14938. // CLEARCOAT
  14939. if ( this.useClearcoat ) {
  14940. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  14941. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  14942. clearcoat.assign( clearcoatNode );
  14943. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  14944. }
  14945. // SHEEN
  14946. if ( this.useSheen ) {
  14947. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  14948. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  14949. sheen.assign( sheenNode );
  14950. sheenRoughness.assign( sheenRoughnessNode );
  14951. }
  14952. // IRIDESCENCE
  14953. if ( this.useIridescence ) {
  14954. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  14955. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  14956. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  14957. iridescence.assign( iridescenceNode );
  14958. iridescenceIOR.assign( iridescenceIORNode );
  14959. iridescenceThickness.assign( iridescenceThicknessNode );
  14960. }
  14961. // ANISOTROPY
  14962. if ( this.useAnisotropy ) {
  14963. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  14964. anisotropy.assign( anisotropyV.length() );
  14965. If( anisotropy.equal( 0.0 ), () => {
  14966. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  14967. } ).Else( () => {
  14968. anisotropyV.divAssign( vec2( anisotropy ) );
  14969. anisotropy.assign( anisotropy.saturate() );
  14970. } );
  14971. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  14972. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  14973. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  14974. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  14975. }
  14976. // TRANSMISSION
  14977. if ( this.useTransmission ) {
  14978. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  14979. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  14980. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  14981. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  14982. transmission.assign( transmissionNode );
  14983. thickness.assign( thicknessNode );
  14984. attenuationDistance.assign( attenuationDistanceNode );
  14985. attenuationColor.assign( attenuationColorNode );
  14986. if ( this.useDispersion ) {
  14987. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  14988. dispersion.assign( dispersionNode );
  14989. }
  14990. }
  14991. }
  14992. /**
  14993. * Setups the clearcoat normal node.
  14994. *
  14995. * @return {Node<vec3>} The clearcoat normal.
  14996. */
  14997. setupClearcoatNormal() {
  14998. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  14999. }
  15000. setup( builder ) {
  15001. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  15002. super.setup( builder );
  15003. }
  15004. copy( source ) {
  15005. this.clearcoatNode = source.clearcoatNode;
  15006. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  15007. this.clearcoatNormalNode = source.clearcoatNormalNode;
  15008. this.sheenNode = source.sheenNode;
  15009. this.sheenRoughnessNode = source.sheenRoughnessNode;
  15010. this.iridescenceNode = source.iridescenceNode;
  15011. this.iridescenceIORNode = source.iridescenceIORNode;
  15012. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  15013. this.specularIntensityNode = source.specularIntensityNode;
  15014. this.specularColorNode = source.specularColorNode;
  15015. this.transmissionNode = source.transmissionNode;
  15016. this.thicknessNode = source.thicknessNode;
  15017. this.attenuationDistanceNode = source.attenuationDistanceNode;
  15018. this.attenuationColorNode = source.attenuationColorNode;
  15019. this.dispersionNode = source.dispersionNode;
  15020. this.anisotropyNode = source.anisotropyNode;
  15021. return super.copy( source );
  15022. }
  15023. }
  15024. /** @module MeshSSSNodeMaterial **/
  15025. /**
  15026. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  15027. *
  15028. * @augments PhysicalLightingModel
  15029. */
  15030. class SSSLightingModel extends PhysicalLightingModel {
  15031. /**
  15032. * Constructs a new physical lighting model.
  15033. *
  15034. * @param {Boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  15035. * @param {Boolean} [sheen=false] - Whether sheen is supported or not.
  15036. * @param {Boolean} [iridescence=false] - Whether iridescence is supported or not.
  15037. * @param {Boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  15038. * @param {Boolean} [transmission=false] - Whether transmission is supported or not.
  15039. * @param {Boolean} [dispersion=false] - Whether dispersion is supported or not.
  15040. * @param {Boolean} [sss=false] - Whether SSS is supported or not.
  15041. */
  15042. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  15043. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  15044. /**
  15045. * Whether the lighting model should use SSS or not.
  15046. *
  15047. * @type {Boolean}
  15048. * @default false
  15049. */
  15050. this.useSSS = sss;
  15051. }
  15052. /**
  15053. * Extends the default implementation with a SSS term.
  15054. *
  15055. * 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/}
  15056. *
  15057. * @param {Object} input - The input data.
  15058. * @param {StackNode} stack - The current stack.
  15059. * @param {NodeBuilder} builder - The current node builder.
  15060. */
  15061. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  15062. if ( this.useSSS === true ) {
  15063. const material = builder.material;
  15064. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  15065. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  15066. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  15067. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  15068. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  15069. }
  15070. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  15071. }
  15072. }
  15073. /**
  15074. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  15075. * that implements a Subsurface scattering (SSS) term.
  15076. *
  15077. * @augments MeshPhysicalNodeMaterial
  15078. */
  15079. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  15080. static get type() {
  15081. return 'MeshSSSNodeMaterial';
  15082. }
  15083. /**
  15084. * Constructs a new mesh SSS node material.
  15085. *
  15086. * @param {Object?} parameters - The configuration parameter.
  15087. */
  15088. constructor( parameters ) {
  15089. super( parameters );
  15090. /**
  15091. * Represents the thickness color.
  15092. *
  15093. * @type {Node<vec3>?}
  15094. * @default null
  15095. */
  15096. this.thicknessColorNode = null;
  15097. /**
  15098. * Represents the distortion factor.
  15099. *
  15100. * @type {Node<float>?}
  15101. */
  15102. this.thicknessDistortionNode = float( 0.1 );
  15103. /**
  15104. * Represents the thickness ambient factor.
  15105. *
  15106. * @type {Node<float>?}
  15107. */
  15108. this.thicknessAmbientNode = float( 0.0 );
  15109. /**
  15110. * Represents the thickness attenuation.
  15111. *
  15112. * @type {Node<float>?}
  15113. */
  15114. this.thicknessAttenuationNode = float( .1 );
  15115. /**
  15116. * Represents the thickness power.
  15117. *
  15118. * @type {Node<float>?}
  15119. */
  15120. this.thicknessPowerNode = float( 2.0 );
  15121. /**
  15122. * Represents the thickness scale.
  15123. *
  15124. * @type {Node<float>?}
  15125. */
  15126. this.thicknessScaleNode = float( 10.0 );
  15127. }
  15128. /**
  15129. * Whether the lighting model should use SSS or not.
  15130. *
  15131. * @type {Boolean}
  15132. * @default true
  15133. */
  15134. get useSSS() {
  15135. return this.thicknessColorNode !== null;
  15136. }
  15137. /**
  15138. * Setups the lighting model.
  15139. *
  15140. * @return {SSSLightingModel} The lighting model.
  15141. */
  15142. setupLightingModel( /*builder*/ ) {
  15143. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  15144. }
  15145. copy( source ) {
  15146. this.thicknessColorNode = source.thicknessColorNode;
  15147. this.thicknessDistortionNode = source.thicknessDistortionNode;
  15148. this.thicknessAmbientNode = source.thicknessAmbientNode;
  15149. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  15150. this.thicknessPowerNode = source.thicknessPowerNode;
  15151. this.thicknessScaleNode = source.thicknessScaleNode;
  15152. return super.copy( source );
  15153. }
  15154. }
  15155. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  15156. // dotNL will be from -1.0 to 1.0
  15157. const dotNL = normal.dot( lightDirection );
  15158. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  15159. if ( builder.material.gradientMap ) {
  15160. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  15161. return vec3( gradientMap.r );
  15162. } else {
  15163. const fw = coord.fwidth().mul( 0.5 );
  15164. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  15165. }
  15166. } );
  15167. /**
  15168. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  15169. *
  15170. * @augments LightingModel
  15171. */
  15172. class ToonLightingModel extends LightingModel {
  15173. /**
  15174. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  15175. * reduced to a small number of discrete shades to create a comic-like, flat look.
  15176. *
  15177. * @param {Object} input - The input data.
  15178. * @param {StackNode} stack - The current stack.
  15179. * @param {NodeBuilder} builder - The current node builder.
  15180. */
  15181. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  15182. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  15183. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  15184. }
  15185. /**
  15186. * Implements the indirect lighting.
  15187. *
  15188. * @param {ContextNode} input - The current node context.
  15189. * @param {StackNode} stack - The current stack.
  15190. * @param {NodeBuilder} builder - The current node builder.
  15191. */
  15192. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  15193. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  15194. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15195. }
  15196. }
  15197. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  15198. /**
  15199. * Node material version of `MeshToonMaterial`.
  15200. *
  15201. * @augments NodeMaterial
  15202. */
  15203. class MeshToonNodeMaterial extends NodeMaterial {
  15204. static get type() {
  15205. return 'MeshToonNodeMaterial';
  15206. }
  15207. /**
  15208. * Constructs a new mesh toon node material.
  15209. *
  15210. * @param {Object?} parameters - The configuration parameter.
  15211. */
  15212. constructor( parameters ) {
  15213. super();
  15214. /**
  15215. * This flag can be used for type testing.
  15216. *
  15217. * @type {Boolean}
  15218. * @readonly
  15219. * @default true
  15220. */
  15221. this.isMeshToonNodeMaterial = true;
  15222. /**
  15223. * Set to `true` because toon materials react on lights.
  15224. *
  15225. * @type {Boolean}
  15226. * @default true
  15227. */
  15228. this.lights = true;
  15229. this.setDefaultValues( _defaultValues$4 );
  15230. this.setValues( parameters );
  15231. }
  15232. /**
  15233. * Setups the lighting model.
  15234. *
  15235. * @return {ToonLightingModel} The lighting model.
  15236. */
  15237. setupLightingModel( /*builder*/ ) {
  15238. return new ToonLightingModel();
  15239. }
  15240. }
  15241. /** @module MatcapUVNode **/
  15242. /**
  15243. * Can be used to compute texture coordinates for projecting a
  15244. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  15245. *
  15246. * @augments TempNode
  15247. */
  15248. class MatcapUVNode extends TempNode {
  15249. static get type() {
  15250. return 'MatcapUVNode';
  15251. }
  15252. /**
  15253. * Constructs a new matcap uv node.
  15254. */
  15255. constructor() {
  15256. super( 'vec2' );
  15257. }
  15258. setup() {
  15259. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  15260. const y = positionViewDirection.cross( x );
  15261. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  15262. }
  15263. }
  15264. /**
  15265. * TSL function for creating a matcap uv node.
  15266. *
  15267. * @function
  15268. * @returns {MatcapUVNode}
  15269. */
  15270. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  15271. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  15272. /**
  15273. * Node material version of `MeshMatcapMaterial`.
  15274. *
  15275. * @augments NodeMaterial
  15276. */
  15277. class MeshMatcapNodeMaterial extends NodeMaterial {
  15278. static get type() {
  15279. return 'MeshMatcapNodeMaterial';
  15280. }
  15281. /**
  15282. * Constructs a new mesh normal node material.
  15283. *
  15284. * @param {Object?} parameters - The configuration parameter.
  15285. */
  15286. constructor( parameters ) {
  15287. super();
  15288. /**
  15289. * This flag can be used for type testing.
  15290. *
  15291. * @type {Boolean}
  15292. * @readonly
  15293. * @default true
  15294. */
  15295. this.isMeshMatcapNodeMaterial = true;
  15296. this.setDefaultValues( _defaultValues$3 );
  15297. this.setValues( parameters );
  15298. }
  15299. /**
  15300. * Setups the matcap specific node variables.
  15301. *
  15302. * @param {NodeBuilder} builder - The current node builder.
  15303. */
  15304. setupVariants( builder ) {
  15305. const uv = matcapUV;
  15306. let matcapColor;
  15307. if ( builder.material.matcap ) {
  15308. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  15309. } else {
  15310. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  15311. }
  15312. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  15313. }
  15314. }
  15315. const _defaultValues$2 = /*@__PURE__*/ new PointsMaterial();
  15316. /**
  15317. * Node material version of `PointsMaterial`.
  15318. *
  15319. * Since WebGPU can render point primitives only with a size of one pixel,
  15320. * this material type does not evaluate the `size` and `sizeAttenuation`
  15321. * property of `PointsMaterial`. Use {@link InstancedPointsNodeMaterial}
  15322. * instead if you need points with a size larger than one pixel.
  15323. *
  15324. * @augments NodeMaterial
  15325. */
  15326. class PointsNodeMaterial extends NodeMaterial {
  15327. static get type() {
  15328. return 'PointsNodeMaterial';
  15329. }
  15330. /**
  15331. * Constructs a new points node material.
  15332. *
  15333. * @param {Object?} parameters - The configuration parameter.
  15334. */
  15335. constructor( parameters ) {
  15336. super();
  15337. /**
  15338. * This flag can be used for type testing.
  15339. *
  15340. * @type {Boolean}
  15341. * @readonly
  15342. * @default true
  15343. */
  15344. this.isPointsNodeMaterial = true;
  15345. this.setDefaultValues( _defaultValues$2 );
  15346. this.setValues( parameters );
  15347. }
  15348. }
  15349. /** @module RotateNode **/
  15350. /**
  15351. * Applies a rotation to the given position node.
  15352. *
  15353. * @augments TempNode
  15354. */
  15355. class RotateNode extends TempNode {
  15356. static get type() {
  15357. return 'RotateNode';
  15358. }
  15359. /**
  15360. * Constructs a new rotate node.
  15361. *
  15362. * @param {Node} positionNode - The position node.
  15363. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  15364. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15365. */
  15366. constructor( positionNode, rotationNode ) {
  15367. super();
  15368. /**
  15369. * The position node.
  15370. *
  15371. * @type {Node}
  15372. */
  15373. this.positionNode = positionNode;
  15374. /**
  15375. * Represents the rotation that is applied to the position node.
  15376. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15377. *
  15378. * @type {Node}
  15379. */
  15380. this.rotationNode = rotationNode;
  15381. }
  15382. /**
  15383. * The type of the {@link RotateNode#positionNode} defines the node's type.
  15384. *
  15385. * @param {NodeBuilder} builder - The current node builder.
  15386. * @return {String} The node's type.
  15387. */
  15388. getNodeType( builder ) {
  15389. return this.positionNode.getNodeType( builder );
  15390. }
  15391. setup( builder ) {
  15392. const { rotationNode, positionNode } = this;
  15393. const nodeType = this.getNodeType( builder );
  15394. if ( nodeType === 'vec2' ) {
  15395. const cosAngle = rotationNode.cos();
  15396. const sinAngle = rotationNode.sin();
  15397. const rotationMatrix = mat2(
  15398. cosAngle, sinAngle,
  15399. sinAngle.negate(), cosAngle
  15400. );
  15401. return rotationMatrix.mul( positionNode );
  15402. } else {
  15403. const rotation = rotationNode;
  15404. 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 ) );
  15405. 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 ) );
  15406. 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 ) );
  15407. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  15408. }
  15409. }
  15410. }
  15411. /**
  15412. * TSL function for creating a rotate node.
  15413. *
  15414. * @function
  15415. * @param {Node} positionNode - The position node.
  15416. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  15417. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15418. * @returns {RotateNode}
  15419. */
  15420. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  15421. const _defaultValues$1 = /*@__PURE__*/ new SpriteMaterial();
  15422. /**
  15423. * Node material version of `SpriteMaterial`.
  15424. *
  15425. * @augments NodeMaterial
  15426. */
  15427. class SpriteNodeMaterial extends NodeMaterial {
  15428. static get type() {
  15429. return 'SpriteNodeMaterial';
  15430. }
  15431. /**
  15432. * Constructs a new sprite node material.
  15433. *
  15434. * @param {Object?} parameters - The configuration parameter.
  15435. */
  15436. constructor( parameters ) {
  15437. super();
  15438. /**
  15439. * This flag can be used for type testing.
  15440. *
  15441. * @type {Boolean}
  15442. * @readonly
  15443. * @default true
  15444. */
  15445. this.isSpriteNodeMaterial = true;
  15446. this._useSizeAttenuation = true;
  15447. /**
  15448. * This property makes it possible to define the position of the sprite with a
  15449. * node. That can be useful when the material is used with instanced rendering
  15450. * and node data are defined with an instanced attribute node:
  15451. * ```js
  15452. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  15453. * material.positionNode = instancedBufferAttribute( positionAttribute );
  15454. * ```
  15455. * Another possibility is to compute the instanced data with a compute shader:
  15456. * ```js
  15457. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  15458. * particleMaterial.positionNode = positionBuffer.toAttribute();
  15459. * ```
  15460. *
  15461. * @type {Node<vec2>?}
  15462. * @default null
  15463. */
  15464. this.positionNode = null;
  15465. /**
  15466. * The rotation of sprite materials is by default inferred from the `rotation`,
  15467. * property. This node property allows to overwrite the default and define
  15468. * the rotation with a node instead.
  15469. *
  15470. * If you don't want to overwrite the rotation but modify the existing
  15471. * value instead, use {@link module:MaterialNode.materialRotation}.
  15472. *
  15473. * @type {Node<float>?}
  15474. * @default null
  15475. */
  15476. this.rotationNode = null;
  15477. /**
  15478. * This node property provides an additional way to scale sprites next to
  15479. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  15480. * is multiplied with the scale value of this node in the vertex shader.
  15481. *
  15482. * @type {Node<vec2>?}
  15483. * @default null
  15484. */
  15485. this.scaleNode = null;
  15486. this.setDefaultValues( _defaultValues$1 );
  15487. this.setValues( parameters );
  15488. }
  15489. /**
  15490. * Setups the position node in view space. This method implements
  15491. * the sprite specific vertex shader.
  15492. *
  15493. * @param {NodeBuilder} builder - The current node builder.
  15494. * @return {Node<vec3>} The position in view space.
  15495. */
  15496. setupPositionView( builder ) {
  15497. const { object, camera } = builder;
  15498. const sizeAttenuation = this.sizeAttenuation;
  15499. const { positionNode, rotationNode, scaleNode } = this;
  15500. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  15501. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  15502. if ( scaleNode !== null ) {
  15503. scale = scale.mul( scaleNode );
  15504. }
  15505. if ( sizeAttenuation === false ) {
  15506. if ( camera.isPerspectiveCamera ) {
  15507. scale = scale.mul( mvPosition.z.negate() );
  15508. } else {
  15509. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  15510. scale = scale.mul( orthoScale.mul( 2 ) );
  15511. }
  15512. }
  15513. let alignedPosition = positionGeometry.xy;
  15514. if ( object.center && object.center.isVector2 === true ) {
  15515. const center = reference$1( 'center', 'vec2', object );
  15516. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  15517. }
  15518. alignedPosition = alignedPosition.mul( scale );
  15519. const rotation = float( rotationNode || materialRotation );
  15520. const rotatedPosition = rotate( alignedPosition, rotation );
  15521. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  15522. }
  15523. copy( source ) {
  15524. this.positionNode = source.positionNode;
  15525. this.rotationNode = source.rotationNode;
  15526. this.scaleNode = source.scaleNode;
  15527. return super.copy( source );
  15528. }
  15529. /**
  15530. * Whether to use size attenuation or not.
  15531. *
  15532. * @type {Boolean}
  15533. * @default true
  15534. */
  15535. get sizeAttenuation() {
  15536. return this._useSizeAttenuation;
  15537. }
  15538. set sizeAttenuation( value ) {
  15539. if ( this._useSizeAttenuation !== value ) {
  15540. this._useSizeAttenuation = value;
  15541. this.needsUpdate = true;
  15542. }
  15543. }
  15544. }
  15545. /**
  15546. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  15547. *
  15548. * @augments LightingModel
  15549. */
  15550. class ShadowMaskModel extends LightingModel {
  15551. /**
  15552. * Constructs a new shadow mask model.
  15553. */
  15554. constructor() {
  15555. super();
  15556. /**
  15557. * The shadow mask node.
  15558. *
  15559. * @type {Node}
  15560. */
  15561. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  15562. }
  15563. /**
  15564. * Only used to save the shadow mask.
  15565. *
  15566. * @param {Object} input - The input data.
  15567. */
  15568. direct( { shadowMask } ) {
  15569. this.shadowNode.mulAssign( shadowMask );
  15570. }
  15571. /**
  15572. * Uses the shadow mask to produce the final color.
  15573. *
  15574. * @param {ContextNode} context - The current node context.
  15575. */
  15576. finish( context ) {
  15577. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  15578. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  15579. }
  15580. }
  15581. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  15582. /**
  15583. * Node material version of `ShadowMaterial`.
  15584. *
  15585. * @augments NodeMaterial
  15586. */
  15587. class ShadowNodeMaterial extends NodeMaterial {
  15588. static get type() {
  15589. return 'ShadowNodeMaterial';
  15590. }
  15591. /**
  15592. * Constructs a new shadow node material.
  15593. *
  15594. * @param {Object?} parameters - The configuration parameter.
  15595. */
  15596. constructor( parameters ) {
  15597. super();
  15598. /**
  15599. * This flag can be used for type testing.
  15600. *
  15601. * @type {Boolean}
  15602. * @readonly
  15603. * @default true
  15604. */
  15605. this.isShadowNodeMaterial = true;
  15606. /**
  15607. * Set to `true` because so it's possible to implement
  15608. * the shadow mask effect.
  15609. *
  15610. * @type {Boolean}
  15611. * @default true
  15612. */
  15613. this.lights = true;
  15614. this.setDefaultValues( _defaultValues );
  15615. this.setValues( parameters );
  15616. }
  15617. /**
  15618. * Setups the lighting model.
  15619. *
  15620. * @return {ShadowMaskModel} The lighting model.
  15621. */
  15622. setupLightingModel( /*builder*/ ) {
  15623. return new ShadowMaskModel();
  15624. }
  15625. }
  15626. /** @module Texture3DNode **/
  15627. const normal = Fn( ( { texture, uv } ) => {
  15628. const epsilon = 0.0001;
  15629. const ret = vec3().toVar();
  15630. If( uv.x.lessThan( epsilon ), () => {
  15631. ret.assign( vec3( 1, 0, 0 ) );
  15632. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  15633. ret.assign( vec3( 0, 1, 0 ) );
  15634. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  15635. ret.assign( vec3( 0, 0, 1 ) );
  15636. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  15637. ret.assign( vec3( - 1, 0, 0 ) );
  15638. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  15639. ret.assign( vec3( 0, - 1, 0 ) );
  15640. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  15641. ret.assign( vec3( 0, 0, - 1 ) );
  15642. } ).Else( () => {
  15643. const step = 0.01;
  15644. 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 );
  15645. 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 );
  15646. 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 );
  15647. ret.assign( vec3( x, y, z ) );
  15648. } );
  15649. return ret.normalize();
  15650. } );
  15651. /**
  15652. * This type of uniform node represents a 3D texture.
  15653. *
  15654. * @augments module:TextureNode~TextureNode
  15655. */
  15656. class Texture3DNode extends TextureNode {
  15657. static get type() {
  15658. return 'Texture3DNode';
  15659. }
  15660. /**
  15661. * Constructs a new 3D texture node.
  15662. *
  15663. * @param {Data3DTexture} value - The 3D texture.
  15664. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  15665. * @param {Node<int>?} [levelNode=null] - The level node.
  15666. */
  15667. constructor( value, uvNode = null, levelNode = null ) {
  15668. super( value, uvNode, levelNode );
  15669. /**
  15670. * This flag can be used for type testing.
  15671. *
  15672. * @type {Boolean}
  15673. * @readonly
  15674. * @default true
  15675. */
  15676. this.isTexture3DNode = true;
  15677. }
  15678. /**
  15679. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  15680. *
  15681. * @param {NodeBuilder} builder - The current node builder.
  15682. * @return {String} The input type.
  15683. */
  15684. getInputType( /*builder*/ ) {
  15685. return 'texture3D';
  15686. }
  15687. /**
  15688. * Returns a default uv node which is in context of 3D textures a three-dimensional
  15689. * uv node.
  15690. *
  15691. * @return {Node<vec3>} The default uv node.
  15692. */
  15693. getDefaultUV() {
  15694. return vec3( 0.5, 0.5, 0.5 );
  15695. }
  15696. /**
  15697. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  15698. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  15699. *
  15700. * @param {Boolean} value - The update toggle.
  15701. */
  15702. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  15703. /**
  15704. * Overwrites the default implementation to return the unmodified uv node.
  15705. *
  15706. * @param {NodeBuilder} builder - The current node builder.
  15707. * @param {Node} uvNode - The uv node to setup.
  15708. * @return {Node} The unmodified uv node.
  15709. */
  15710. setupUV( builder, uvNode ) {
  15711. const texture = this.value;
  15712. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  15713. if ( this.sampler ) {
  15714. uvNode = uvNode.flipY();
  15715. } else {
  15716. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  15717. }
  15718. }
  15719. return uvNode;
  15720. }
  15721. /**
  15722. * Generates the uv code snippet.
  15723. *
  15724. * @param {NodeBuilder} builder - The current node builder.
  15725. * @param {Node} uvNode - The uv node to generate code for.
  15726. * @return {String} The generated code snippet.
  15727. */
  15728. generateUV( builder, uvNode ) {
  15729. return uvNode.build( builder, 'vec3' );
  15730. }
  15731. /**
  15732. * TODO.
  15733. *
  15734. * @param {Node<vec3>} uvNode - The uv node .
  15735. * @return {Node<vec3>} TODO.
  15736. */
  15737. normal( uvNode ) {
  15738. return normal( { texture: this, uv: uvNode } );
  15739. }
  15740. }
  15741. /**
  15742. * TSL function for creating a 3D texture node.
  15743. *
  15744. * @function
  15745. * @param {Data3DTexture} value - The 3D texture.
  15746. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  15747. * @param {Node<int>?} [levelNode=null] - The level node.
  15748. * @returns {Texture3DNode}
  15749. */
  15750. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  15751. /** @module VolumeNodeMaterial **/
  15752. /**
  15753. * Node material intended for volume rendering. The volumetric data are
  15754. * defined with an instance of {@link Data3DTexture}.
  15755. *
  15756. * @augments NodeMaterial
  15757. */
  15758. class VolumeNodeMaterial extends NodeMaterial {
  15759. static get type() {
  15760. return 'VolumeNodeMaterial';
  15761. }
  15762. /**
  15763. * Constructs a new volume node material.
  15764. *
  15765. * @param {Object?} parameters - The configuration parameter.
  15766. */
  15767. constructor( parameters ) {
  15768. super();
  15769. /**
  15770. * This flag can be used for type testing.
  15771. *
  15772. * @type {Boolean}
  15773. * @readonly
  15774. * @default true
  15775. */
  15776. this.isVolumeNodeMaterial = true;
  15777. /**
  15778. * The base color of the volume.
  15779. *
  15780. * @type {Color}
  15781. * @default 100
  15782. */
  15783. this.base = new Color( 0xffffff );
  15784. /**
  15785. * A 3D data texture holding the volumetric data.
  15786. *
  15787. * @type {Data3DTexture?}
  15788. * @default null
  15789. */
  15790. this.map = null;
  15791. /**
  15792. * This number of samples for each ray that hits the mesh's surface
  15793. * and travels through the volume.
  15794. *
  15795. * @type {Number}
  15796. * @default 100
  15797. */
  15798. this.steps = 100;
  15799. /**
  15800. * Callback for {@link VolumeNodeMaterial#testNode}.
  15801. *
  15802. * @callback testNodeCallback
  15803. * @param {Data3DTexture<float>} map - The 3D texture.
  15804. * @param {Node<float>} mapValue - The sampled value inside the volume.
  15805. * @param {Node<vec3>} probe - The probe which is the entry point of the ray on the mesh's surface.
  15806. * @param {Node<vec4>} finalColor - The final color.
  15807. */
  15808. /**
  15809. * The volume rendering of this material works by shooting rays
  15810. * from the camera position through each fragment of the mesh's
  15811. * surface and sample the inner volume in a raymarching fashion
  15812. * multiple times.
  15813. *
  15814. * This node can be used to assign a callback function of type `Fn`
  15815. * that will be executed per sample. The callback receives the
  15816. * texture, the sampled texture value as well as position on the surface
  15817. * where the rays enters the volume. The last parameter is a color
  15818. * that allows the callback to determine the final color.
  15819. *
  15820. * @type {testNodeCallback?}
  15821. * @default null
  15822. */
  15823. this.testNode = null;
  15824. this.setValues( parameters );
  15825. }
  15826. /**
  15827. * Setups the vertex and fragment stage of this node material.
  15828. *
  15829. * @param {NodeBuilder} builder - The current node builder.
  15830. */
  15831. setup( builder ) {
  15832. const map = texture3D( this.map, null, 0 );
  15833. const hitBox = Fn( ( { orig, dir } ) => {
  15834. const box_min = vec3( - 0.5 );
  15835. const box_max = vec3( 0.5 );
  15836. const inv_dir = dir.reciprocal();
  15837. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  15838. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  15839. const tmin = min$1( tmin_tmp, tmax_tmp );
  15840. const tmax = max$1( tmin_tmp, tmax_tmp );
  15841. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  15842. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  15843. return vec2( t0, t1 );
  15844. } );
  15845. this.fragmentNode = Fn( () => {
  15846. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  15847. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  15848. const rayDir = vDirection.normalize();
  15849. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  15850. bounds.x.greaterThan( bounds.y ).discard();
  15851. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  15852. const p = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  15853. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  15854. const delta = float( min$1( inc.x, min$1( inc.y, inc.z ) ) ).toVar( 'delta' ); // used 'delta' name in loop
  15855. delta.divAssign( materialReference( 'steps', 'float' ) );
  15856. const ac = vec4( materialReference( 'base', 'color' ), 0.0 ).toVar();
  15857. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  15858. const d = property( 'float', 'd' ).assign( map.sample( p.add( 0.5 ) ).r );
  15859. if ( this.testNode !== null ) {
  15860. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  15861. } else {
  15862. // default to show surface of mesh
  15863. ac.a.assign( 1 );
  15864. Break();
  15865. }
  15866. p.addAssign( rayDir.mul( delta ) );
  15867. } );
  15868. ac.a.equal( 0 ).discard();
  15869. return vec4( ac );
  15870. } )();
  15871. super.setup( builder );
  15872. }
  15873. }
  15874. /**
  15875. * This module manages the internal animation loop of the renderer.
  15876. *
  15877. * @private
  15878. */
  15879. class Animation {
  15880. /**
  15881. * Constructs a new animation loop management component.
  15882. *
  15883. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  15884. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  15885. */
  15886. constructor( nodes, info ) {
  15887. /**
  15888. * Renderer component for managing nodes related logic.
  15889. *
  15890. * @type {Nodes}
  15891. */
  15892. this.nodes = nodes;
  15893. /**
  15894. * Renderer component for managing metrics and monitoring data.
  15895. *
  15896. * @type {Info}
  15897. */
  15898. this.info = info;
  15899. /**
  15900. * A reference to the context from `requestAnimationFrame()` can
  15901. * be called (usually `window`).
  15902. *
  15903. * @type {Window|XRSession}
  15904. */
  15905. this._context = self;
  15906. /**
  15907. * The user-defined animation loop.
  15908. *
  15909. * @type {Function?}
  15910. * @default null
  15911. */
  15912. this._animationLoop = null;
  15913. /**
  15914. * The requestId which is returned from the `requestAnimationFrame()` call.
  15915. * Can be used to cancel the stop the animation loop.
  15916. *
  15917. * @type {Number?}
  15918. * @default null
  15919. */
  15920. this._requestId = null;
  15921. }
  15922. /**
  15923. * Starts the internal animation loop.
  15924. */
  15925. start() {
  15926. const update = ( time, frame ) => {
  15927. this._requestId = this._context.requestAnimationFrame( update );
  15928. if ( this.info.autoReset === true ) this.info.reset();
  15929. this.nodes.nodeFrame.update();
  15930. this.info.frame = this.nodes.nodeFrame.frameId;
  15931. if ( this._animationLoop !== null ) this._animationLoop( time, frame );
  15932. };
  15933. update();
  15934. }
  15935. /**
  15936. * Stops the internal animation loop.
  15937. */
  15938. stop() {
  15939. this._context.cancelAnimationFrame( this._requestId );
  15940. this._requestId = null;
  15941. }
  15942. /**
  15943. * Defines the user-level animation loop.
  15944. *
  15945. * @param {Function} callback - The animation loop.
  15946. */
  15947. setAnimationLoop( callback ) {
  15948. this._animationLoop = callback;
  15949. }
  15950. /**
  15951. * Defines the context in which `requestAnimationFrame()` is executed.
  15952. *
  15953. * @param {Window|XRSession} context - The context to set.
  15954. */
  15955. setContext( context ) {
  15956. this._context = context;
  15957. }
  15958. /**
  15959. * Frees all internal resources and stops the animation loop.
  15960. */
  15961. dispose() {
  15962. this.stop();
  15963. }
  15964. }
  15965. /**
  15966. * Data structure for the renderer. It allows defining values
  15967. * with chained, hierarchical keys. Keys are meant to be
  15968. * objects since the module internally works with Weak Maps
  15969. * for performance reasons.
  15970. *
  15971. * @private
  15972. */
  15973. class ChainMap {
  15974. /**
  15975. * Constructs a new Chain Map.
  15976. */
  15977. constructor() {
  15978. /**
  15979. * The root Weak Map.
  15980. *
  15981. * @type {WeakMap}
  15982. */
  15983. this.weakMap = new WeakMap();
  15984. }
  15985. /**
  15986. * Returns the value for the given array of keys.
  15987. *
  15988. * @param {Array<Object>} keys - List of keys.
  15989. * @return {Any} The value. Returns `undefined` if no value was found.
  15990. */
  15991. get( keys ) {
  15992. let map = this.weakMap;
  15993. for ( let i = 0; i < keys.length - 1; i ++ ) {
  15994. map = map.get( keys[ i ] );
  15995. if ( map === undefined ) return undefined;
  15996. }
  15997. return map.get( keys[ keys.length - 1 ] );
  15998. }
  15999. /**
  16000. * Sets the value for the given keys.
  16001. *
  16002. * @param {Array<Object>} keys - List of keys.
  16003. * @param {Any} value - The value to set.
  16004. * @return {ChainMap} A reference to this Chain Map.
  16005. */
  16006. set( keys, value ) {
  16007. let map = this.weakMap;
  16008. for ( let i = 0; i < keys.length - 1; i ++ ) {
  16009. const key = keys[ i ];
  16010. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  16011. map = map.get( key );
  16012. }
  16013. map.set( keys[ keys.length - 1 ], value );
  16014. return this;
  16015. }
  16016. /**
  16017. * Deletes a value for the given keys.
  16018. *
  16019. * @param {Array<Object>} keys - The keys.
  16020. * @return {Boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  16021. */
  16022. delete( keys ) {
  16023. let map = this.weakMap;
  16024. for ( let i = 0; i < keys.length - 1; i ++ ) {
  16025. map = map.get( keys[ i ] );
  16026. if ( map === undefined ) return false;
  16027. }
  16028. return map.delete( keys[ keys.length - 1 ] );
  16029. }
  16030. }
  16031. let _id$9 = 0;
  16032. function getKeys( obj ) {
  16033. const keys = Object.keys( obj );
  16034. let proto = Object.getPrototypeOf( obj );
  16035. while ( proto ) {
  16036. const descriptors = Object.getOwnPropertyDescriptors( proto );
  16037. for ( const key in descriptors ) {
  16038. if ( descriptors[ key ] !== undefined ) {
  16039. const descriptor = descriptors[ key ];
  16040. if ( descriptor && typeof descriptor.get === 'function' ) {
  16041. keys.push( key );
  16042. }
  16043. }
  16044. }
  16045. proto = Object.getPrototypeOf( proto );
  16046. }
  16047. return keys;
  16048. }
  16049. /**
  16050. * A render object is the renderer's representation of single entity that gets drawn
  16051. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  16052. * scene since render objects also depend from the used material, the current render context
  16053. * and the current scene's lighting.
  16054. *
  16055. * In general, the basic process of the renderer is:
  16056. *
  16057. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  16058. * - Process the render lists by calling one or more render commands for each render item.
  16059. * - For each render command, request a render object and perform the draw.
  16060. *
  16061. * The module provides an interface to get data required for the draw command like the actual
  16062. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  16063. * creating render objects should only be done when necessary.
  16064. *
  16065. * @private
  16066. */
  16067. class RenderObject {
  16068. /**
  16069. * Constructs a new render object.
  16070. *
  16071. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16072. * @param {Geometries} geometries - Renderer component for managing geometries.
  16073. * @param {Renderer} renderer - The renderer.
  16074. * @param {Object3D} object - The 3D object.
  16075. * @param {Material} material - The 3D object's material.
  16076. * @param {Scene} scene - The scene the 3D object belongs to.
  16077. * @param {Camera} camera - The camera the object should be rendered with.
  16078. * @param {LightsNode} lightsNode - The lights node.
  16079. * @param {RenderContext} renderContext - The render context.
  16080. * @param {ClippingContext} clippingContext - The clipping context.
  16081. */
  16082. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  16083. this.id = _id$9 ++;
  16084. /**
  16085. * Renderer component for managing nodes related logic.
  16086. *
  16087. * @type {Nodes}
  16088. * @private
  16089. */
  16090. this._nodes = nodes;
  16091. /**
  16092. * Renderer component for managing geometries.
  16093. *
  16094. * @type {Geometries}
  16095. * @private
  16096. */
  16097. this._geometries = geometries;
  16098. /**
  16099. * The renderer.
  16100. *
  16101. * @type {Renderer}
  16102. */
  16103. this.renderer = renderer;
  16104. /**
  16105. * The 3D object.
  16106. *
  16107. * @type {Object3D}
  16108. */
  16109. this.object = object;
  16110. /**
  16111. * The 3D object's material.
  16112. *
  16113. * @type {Material}
  16114. */
  16115. this.material = material;
  16116. /**
  16117. * The scene the 3D object belongs to.
  16118. *
  16119. * @type {Scene}
  16120. */
  16121. this.scene = scene;
  16122. /**
  16123. * The camera the 3D object should be rendered with.
  16124. *
  16125. * @type {Camera}
  16126. */
  16127. this.camera = camera;
  16128. /**
  16129. * The lights node.
  16130. *
  16131. * @type {LightsNode}
  16132. */
  16133. this.lightsNode = lightsNode;
  16134. /**
  16135. * The render context.
  16136. *
  16137. * @type {RenderContext}
  16138. */
  16139. this.context = renderContext;
  16140. /**
  16141. * The 3D object's geometry.
  16142. *
  16143. * @type {BufferGeometry}
  16144. */
  16145. this.geometry = object.geometry;
  16146. /**
  16147. * The render object's version.
  16148. *
  16149. * @type {Number}
  16150. */
  16151. this.version = material.version;
  16152. /**
  16153. * The draw range of the geometry.
  16154. *
  16155. * @type {Object?}
  16156. * @default null
  16157. */
  16158. this.drawRange = null;
  16159. /**
  16160. * An array holding the buffer attributes
  16161. * of the render object. This entails attribute
  16162. * definitions on geometry and node level.
  16163. *
  16164. * @type {Array<BufferAttribute>?}
  16165. * @default null
  16166. */
  16167. this.attributes = null;
  16168. /**
  16169. * A reference to a render pipeline the render
  16170. * object is processed with.
  16171. *
  16172. * @type {RenderPipeline}
  16173. * @default null
  16174. */
  16175. this.pipeline = null;
  16176. /**
  16177. * An array holding the vertex buffers which can
  16178. * be buffer attributes but also interleaved buffers.
  16179. *
  16180. * @type {Array<BufferAttribute|InterleavedBuffer>?}
  16181. * @default null
  16182. */
  16183. this.vertexBuffers = null;
  16184. /**
  16185. * The parameters for the draw command.
  16186. *
  16187. * @type {Object?}
  16188. * @default null
  16189. */
  16190. this.drawParams = null;
  16191. /**
  16192. * If this render object is used inside a render bundle,
  16193. * this property points to the respective bundle group.
  16194. *
  16195. * @type {BundleGroup?}
  16196. * @default null
  16197. */
  16198. this.bundle = null;
  16199. /**
  16200. * The clipping context.
  16201. *
  16202. * @type {ClippingContext}
  16203. */
  16204. this.clippingContext = clippingContext;
  16205. /**
  16206. * The clipping context's cache key.
  16207. *
  16208. * @type {String}
  16209. */
  16210. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  16211. /**
  16212. * The initial node cache key.
  16213. *
  16214. * @type {Number}
  16215. */
  16216. this.initialNodesCacheKey = this.getDynamicCacheKey();
  16217. /**
  16218. * The initial cache key.
  16219. *
  16220. * @type {Number}
  16221. */
  16222. this.initialCacheKey = this.getCacheKey();
  16223. /**
  16224. * The node builder state.
  16225. *
  16226. * @type {NodeBuilderState?}
  16227. * @private
  16228. * @default null
  16229. */
  16230. this._nodeBuilderState = null;
  16231. /**
  16232. * An array of bindings.
  16233. *
  16234. * @type {Array<BindGroup>?}
  16235. * @private
  16236. * @default null
  16237. */
  16238. this._bindings = null;
  16239. /**
  16240. * Reference to the node material observer.
  16241. *
  16242. * @type {NodeMaterialObserver?}
  16243. * @private
  16244. * @default null
  16245. */
  16246. this._monitor = null;
  16247. /**
  16248. * An event listener which is defined by `RenderObjects`. It performs
  16249. * clean up tasks when `dispose()` on this render object.
  16250. *
  16251. * @method
  16252. */
  16253. this.onDispose = null;
  16254. /**
  16255. * This flag can be used for type testing.
  16256. *
  16257. * @type {Boolean}
  16258. * @readonly
  16259. * @default true
  16260. */
  16261. this.isRenderObject = true;
  16262. /**
  16263. * An event listener which is executed when `dispose()` is called on
  16264. * the render object's material.
  16265. *
  16266. * @method
  16267. */
  16268. this.onMaterialDispose = () => {
  16269. this.dispose();
  16270. };
  16271. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  16272. }
  16273. /**
  16274. * Updates the clipping context.
  16275. *
  16276. * @param {ClippingContext} context - The clipping context to set.
  16277. */
  16278. updateClipping( context ) {
  16279. this.clippingContext = context;
  16280. }
  16281. /**
  16282. * Whether the clipping requires an update or not.
  16283. *
  16284. * @type {Boolean}
  16285. * @readonly
  16286. */
  16287. get clippingNeedsUpdate() {
  16288. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  16289. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  16290. return true;
  16291. }
  16292. /**
  16293. * The number of clipping planes defined in context of hardware clipping.
  16294. *
  16295. * @type {Number}
  16296. * @readonly
  16297. */
  16298. get hardwareClippingPlanes() {
  16299. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  16300. }
  16301. /**
  16302. * Returns the node builder state of this render object.
  16303. *
  16304. * @return {NodeBuilderState} The node builder state.
  16305. */
  16306. getNodeBuilderState() {
  16307. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  16308. }
  16309. /**
  16310. * Returns the node material observer of this render object.
  16311. *
  16312. * @return {NodeMaterialObserver} The node material observer.
  16313. */
  16314. getMonitor() {
  16315. return this._monitor || ( this._monitor = this.getNodeBuilderState().monitor );
  16316. }
  16317. /**
  16318. * Returns an array of bind groups of this render object.
  16319. *
  16320. * @return {Array<BindGroup>} The bindings.
  16321. */
  16322. getBindings() {
  16323. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  16324. }
  16325. /**
  16326. * Returns the index of the render object's geometry.
  16327. *
  16328. * @return {BufferAttribute?} The index. Returns `null` for non-indexed geometries.
  16329. */
  16330. getIndex() {
  16331. return this._geometries.getIndex( this );
  16332. }
  16333. /**
  16334. * Returns the indirect buffer attribute.
  16335. *
  16336. * @return {BufferAttribute?} The indirect attribute. `null` if no indirect drawing is used.
  16337. */
  16338. getIndirect() {
  16339. return this._geometries.getIndirect( this );
  16340. }
  16341. /**
  16342. * Returns an array that acts as a key for identifying the render object in a chain map.
  16343. *
  16344. * @return {Array<Object>} An array with object references.
  16345. */
  16346. getChainArray() {
  16347. return [ this.object, this.material, this.context, this.lightsNode ];
  16348. }
  16349. /**
  16350. * This method is used when the geometry of a 3D object has been exchanged and the
  16351. * respective render object now requires an update.
  16352. *
  16353. * @param {BufferGeometry} geometry - The geometry to set.
  16354. */
  16355. setGeometry( geometry ) {
  16356. this.geometry = geometry;
  16357. this.attributes = null;
  16358. }
  16359. /**
  16360. * Returns the buffer attributes of the render object. The returned array holds
  16361. * attribute definitions on geometry and node level.
  16362. *
  16363. * @return {Array<BufferAttribute>} An array with buffer attributes.
  16364. */
  16365. getAttributes() {
  16366. if ( this.attributes !== null ) return this.attributes;
  16367. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  16368. const geometry = this.geometry;
  16369. const attributes = [];
  16370. const vertexBuffers = new Set();
  16371. for ( const nodeAttribute of nodeAttributes ) {
  16372. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  16373. if ( attribute === undefined ) continue;
  16374. attributes.push( attribute );
  16375. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  16376. vertexBuffers.add( bufferAttribute );
  16377. }
  16378. this.attributes = attributes;
  16379. this.vertexBuffers = Array.from( vertexBuffers.values() );
  16380. return attributes;
  16381. }
  16382. /**
  16383. * Returns the vertex buffers of the render object.
  16384. *
  16385. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  16386. */
  16387. getVertexBuffers() {
  16388. if ( this.vertexBuffers === null ) this.getAttributes();
  16389. return this.vertexBuffers;
  16390. }
  16391. /**
  16392. * Returns the draw parameters for the render object.
  16393. *
  16394. * @return {{vertexCount: Number, firstVertex: Number, instanceCount: Number, firstInstance: Number}} The draw parameters.
  16395. */
  16396. getDrawParameters() {
  16397. const { object, material, geometry, group, drawRange } = this;
  16398. const drawParams = this.drawParams || ( this.drawParams = {
  16399. vertexCount: 0,
  16400. firstVertex: 0,
  16401. instanceCount: 0,
  16402. firstInstance: 0
  16403. } );
  16404. const index = this.getIndex();
  16405. const hasIndex = ( index !== null );
  16406. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  16407. if ( instanceCount === 0 ) return null;
  16408. drawParams.instanceCount = instanceCount;
  16409. if ( object.isBatchedMesh === true ) return drawParams;
  16410. let rangeFactor = 1;
  16411. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  16412. rangeFactor = 2;
  16413. }
  16414. let firstVertex = drawRange.start * rangeFactor;
  16415. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  16416. if ( group !== null ) {
  16417. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  16418. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  16419. }
  16420. const position = geometry.attributes.position;
  16421. let itemCount = Infinity;
  16422. if ( hasIndex ) {
  16423. itemCount = index.count;
  16424. } else if ( position !== undefined && position !== null ) {
  16425. itemCount = position.count;
  16426. }
  16427. firstVertex = Math.max( firstVertex, 0 );
  16428. lastVertex = Math.min( lastVertex, itemCount );
  16429. const count = lastVertex - firstVertex;
  16430. if ( count < 0 || count === Infinity ) return null;
  16431. drawParams.vertexCount = count;
  16432. drawParams.firstVertex = firstVertex;
  16433. return drawParams;
  16434. }
  16435. /**
  16436. * Returns the render object's geometry cache key.
  16437. *
  16438. * The geometry cache key is part of the material cache key.
  16439. *
  16440. * @return {String} The geometry cache key.
  16441. */
  16442. getGeometryCacheKey() {
  16443. const { geometry } = this;
  16444. let cacheKey = '';
  16445. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  16446. const attribute = geometry.attributes[ name ];
  16447. cacheKey += name + ',';
  16448. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  16449. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  16450. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  16451. if ( attribute.normalized ) cacheKey += 'n,';
  16452. }
  16453. if ( geometry.index ) {
  16454. cacheKey += 'index,';
  16455. }
  16456. return cacheKey;
  16457. }
  16458. /**
  16459. * Returns the render object's material cache key.
  16460. *
  16461. * The material cache key is part of the render object cache key.
  16462. *
  16463. * @return {String} The material cache key.
  16464. */
  16465. getMaterialCacheKey() {
  16466. const { object, material } = this;
  16467. let cacheKey = material.customProgramCacheKey();
  16468. for ( const property of getKeys( material ) ) {
  16469. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  16470. const value = material[ property ];
  16471. let valueKey;
  16472. if ( value !== null ) {
  16473. // some material values require a formatting
  16474. const type = typeof value;
  16475. if ( type === 'number' ) {
  16476. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  16477. } else if ( type === 'object' ) {
  16478. valueKey = '{';
  16479. if ( value.isTexture ) {
  16480. valueKey += value.mapping;
  16481. }
  16482. valueKey += '}';
  16483. } else {
  16484. valueKey = String( value );
  16485. }
  16486. } else {
  16487. valueKey = String( value );
  16488. }
  16489. cacheKey += /*property + ':' +*/ valueKey + ',';
  16490. }
  16491. cacheKey += this.clippingContextCacheKey + ',';
  16492. if ( object.geometry ) {
  16493. cacheKey += this.getGeometryCacheKey();
  16494. }
  16495. if ( object.skeleton ) {
  16496. cacheKey += object.skeleton.bones.length + ',';
  16497. }
  16498. if ( object.morphTargetInfluences ) {
  16499. cacheKey += object.morphTargetInfluences.length + ',';
  16500. }
  16501. if ( object.isBatchedMesh ) {
  16502. cacheKey += object._matricesTexture.uuid + ',';
  16503. if ( object._colorsTexture !== null ) {
  16504. cacheKey += object._colorsTexture.uuid + ',';
  16505. }
  16506. }
  16507. if ( object.count > 1 ) {
  16508. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  16509. cacheKey += object.uuid + ',';
  16510. }
  16511. cacheKey += object.receiveShadow + ',';
  16512. return hashString( cacheKey );
  16513. }
  16514. /**
  16515. * Whether the geometry requires an update or not.
  16516. *
  16517. * @type {Boolean}
  16518. * @readonly
  16519. */
  16520. get needsGeometryUpdate() {
  16521. return this.geometry.id !== this.object.geometry.id;
  16522. }
  16523. /**
  16524. * Whether the render object requires an update or not.
  16525. *
  16526. * Note: There are two distinct places where render objects are checked for an update.
  16527. *
  16528. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  16529. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  16530. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  16531. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  16532. * a need for a refresh due to material, geometry or object related value changes.
  16533. *
  16534. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  16535. * that performs the 'needsUpdate' check.
  16536. *
  16537. * @type {Boolean}
  16538. * @readonly
  16539. */
  16540. get needsUpdate() {
  16541. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  16542. }
  16543. /**
  16544. * Returns the dynamic cache key which represents a key that is computed per draw command.
  16545. *
  16546. * @return {String} The cache key.
  16547. */
  16548. getDynamicCacheKey() {
  16549. // Environment Nodes Cache Key
  16550. let cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  16551. if ( this.object.receiveShadow ) {
  16552. cacheKey += 1;
  16553. }
  16554. return cacheKey;
  16555. }
  16556. /**
  16557. * Returns the render object's cache key.
  16558. *
  16559. * @return {String} The cache key.
  16560. */
  16561. getCacheKey() {
  16562. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  16563. }
  16564. /**
  16565. * Frees internal resources.
  16566. */
  16567. dispose() {
  16568. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  16569. this.onDispose();
  16570. }
  16571. }
  16572. const _chainKeys$5 = [];
  16573. /**
  16574. * This module manages the render objects of the renderer.
  16575. *
  16576. * @private
  16577. */
  16578. class RenderObjects {
  16579. /**
  16580. * Constructs a new render object management component.
  16581. *
  16582. * @param {Renderer} renderer - The renderer.
  16583. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16584. * @param {Geometries} geometries - Renderer component for managing geometries.
  16585. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  16586. * @param {Bindings} bindings - Renderer component for managing bindings.
  16587. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  16588. */
  16589. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  16590. /**
  16591. * The renderer.
  16592. *
  16593. * @type {Renderer}
  16594. */
  16595. this.renderer = renderer;
  16596. /**
  16597. * Renderer component for managing nodes related logic.
  16598. *
  16599. * @type {Nodes}
  16600. */
  16601. this.nodes = nodes;
  16602. /**
  16603. * Renderer component for managing geometries.
  16604. *
  16605. * @type {Geometries}
  16606. */
  16607. this.geometries = geometries;
  16608. /**
  16609. * Renderer component for managing pipelines.
  16610. *
  16611. * @type {Pipelines}
  16612. */
  16613. this.pipelines = pipelines;
  16614. /**
  16615. * Renderer component for managing bindings.
  16616. *
  16617. * @type {Bindings}
  16618. */
  16619. this.bindings = bindings;
  16620. /**
  16621. * Renderer component for managing metrics and monitoring data.
  16622. *
  16623. * @type {Info}
  16624. */
  16625. this.info = info;
  16626. /**
  16627. * A dictionary that manages render contexts in chain maps
  16628. * for each pass ID.
  16629. *
  16630. * @type {Object<String,ChainMap>}
  16631. */
  16632. this.chainMaps = {};
  16633. }
  16634. /**
  16635. * Returns a render object for the given object and state data.
  16636. *
  16637. * @param {Object3D} object - The 3D object.
  16638. * @param {Material} material - The 3D object's material.
  16639. * @param {Scene} scene - The scene the 3D object belongs to.
  16640. * @param {Camera} camera - The camera the 3D object should be rendered with.
  16641. * @param {LightsNode} lightsNode - The lights node.
  16642. * @param {RenderContext} renderContext - The render context.
  16643. * @param {ClippingContext} clippingContext - The clipping context.
  16644. * @param {String?} passId - An optional ID for identifying the pass.
  16645. * @return {RenderObject} The render object.
  16646. */
  16647. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  16648. const chainMap = this.getChainMap( passId );
  16649. // reuse chainArray
  16650. _chainKeys$5[ 0 ] = object;
  16651. _chainKeys$5[ 1 ] = material;
  16652. _chainKeys$5[ 2 ] = renderContext;
  16653. _chainKeys$5[ 3 ] = lightsNode;
  16654. let renderObject = chainMap.get( _chainKeys$5 );
  16655. if ( renderObject === undefined ) {
  16656. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  16657. chainMap.set( _chainKeys$5, renderObject );
  16658. } else {
  16659. renderObject.updateClipping( clippingContext );
  16660. if ( renderObject.needsGeometryUpdate ) {
  16661. renderObject.setGeometry( object.geometry );
  16662. }
  16663. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  16664. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  16665. renderObject.dispose();
  16666. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  16667. } else {
  16668. renderObject.version = material.version;
  16669. }
  16670. }
  16671. }
  16672. _chainKeys$5.length = 0;
  16673. return renderObject;
  16674. }
  16675. /**
  16676. * Returns a chain map for the given pass ID.
  16677. *
  16678. * @param {String} [passId='default'] - The pass ID.
  16679. * @return {ChainMap} The chain map.
  16680. */
  16681. getChainMap( passId = 'default' ) {
  16682. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  16683. }
  16684. /**
  16685. * Frees internal resources.
  16686. */
  16687. dispose() {
  16688. this.chainMaps = {};
  16689. }
  16690. /**
  16691. * Factory method for creating render objects with the given list of parameters.
  16692. *
  16693. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16694. * @param {Geometries} geometries - Renderer component for managing geometries.
  16695. * @param {Renderer} renderer - The renderer.
  16696. * @param {Object3D} object - The 3D object.
  16697. * @param {Material} material - The object's material.
  16698. * @param {Scene} scene - The scene the 3D object belongs to.
  16699. * @param {Camera} camera - The camera the object should be rendered with.
  16700. * @param {LightsNode} lightsNode - The lights node.
  16701. * @param {RenderContext} renderContext - The render context.
  16702. * @param {ClippingContext} clippingContext - The clipping context.
  16703. * @param {String?} passId - An optional ID for identifying the pass.
  16704. * @return {RenderObject} The render object.
  16705. */
  16706. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  16707. const chainMap = this.getChainMap( passId );
  16708. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  16709. renderObject.onDispose = () => {
  16710. this.pipelines.delete( renderObject );
  16711. this.bindings.delete( renderObject );
  16712. this.nodes.delete( renderObject );
  16713. chainMap.delete( renderObject.getChainArray() );
  16714. };
  16715. return renderObject;
  16716. }
  16717. }
  16718. /**
  16719. * Data structure for the renderer. It is intended to manage
  16720. * data of objects in dictionaries.
  16721. *
  16722. * @private
  16723. */
  16724. class DataMap {
  16725. /**
  16726. * Constructs a new data map.
  16727. */
  16728. constructor() {
  16729. /**
  16730. * `DataMap` internally uses a weak map
  16731. * to manage its data.
  16732. *
  16733. * @type {WeakMap}
  16734. */
  16735. this.data = new WeakMap();
  16736. }
  16737. /**
  16738. * Returns the dictionary for the given object.
  16739. *
  16740. * @param {Object} object - The object.
  16741. * @return {Object} The dictionary.
  16742. */
  16743. get( object ) {
  16744. let map = this.data.get( object );
  16745. if ( map === undefined ) {
  16746. map = {};
  16747. this.data.set( object, map );
  16748. }
  16749. return map;
  16750. }
  16751. /**
  16752. * Deletes the dictionary for the given object.
  16753. *
  16754. * @param {Object} object - The object.
  16755. * @return {Object?} The deleted dictionary.
  16756. */
  16757. delete( object ) {
  16758. let map = null;
  16759. if ( this.data.has( object ) ) {
  16760. map = this.data.get( object );
  16761. this.data.delete( object );
  16762. }
  16763. return map;
  16764. }
  16765. /**
  16766. * Returns `true` if the given object has a dictionary defined.
  16767. *
  16768. * @param {Object} object - The object to test.
  16769. * @return {Boolean} Whether a dictionary is defined or not.
  16770. */
  16771. has( object ) {
  16772. return this.data.has( object );
  16773. }
  16774. /**
  16775. * Frees internal resources.
  16776. */
  16777. dispose() {
  16778. this.data = new WeakMap();
  16779. }
  16780. }
  16781. const AttributeType = {
  16782. VERTEX: 1,
  16783. INDEX: 2,
  16784. STORAGE: 3,
  16785. INDIRECT: 4
  16786. };
  16787. // size of a chunk in bytes (STD140 layout)
  16788. const GPU_CHUNK_BYTES = 16;
  16789. // @TODO: Move to src/constants.js
  16790. const BlendColorFactor = 211;
  16791. const OneMinusBlendColorFactor = 212;
  16792. /**
  16793. * This renderer module manages geometry attributes.
  16794. *
  16795. * @private
  16796. * @augments DataMap
  16797. */
  16798. class Attributes extends DataMap {
  16799. /**
  16800. * Constructs a new attribute management component.
  16801. *
  16802. * @param {Backend} backend - The renderer's backend.
  16803. */
  16804. constructor( backend ) {
  16805. super();
  16806. /**
  16807. * The renderer's backend.
  16808. *
  16809. * @type {Backend}
  16810. */
  16811. this.backend = backend;
  16812. }
  16813. /**
  16814. * Deletes the data for the given attribute.
  16815. *
  16816. * @param {BufferAttribute} attribute - The attribute.
  16817. * @return {Object} The deleted attribute data.
  16818. */
  16819. delete( attribute ) {
  16820. const attributeData = super.delete( attribute );
  16821. if ( attributeData !== undefined ) {
  16822. this.backend.destroyAttribute( attribute );
  16823. }
  16824. return attributeData;
  16825. }
  16826. /**
  16827. * Updates the given attribute. This method creates attribute buffers
  16828. * for new attributes and updates data for existing ones.
  16829. *
  16830. * @param {BufferAttribute} attribute - The attribute to update.
  16831. * @param {Number} type - The attribute type.
  16832. */
  16833. update( attribute, type ) {
  16834. const data = this.get( attribute );
  16835. if ( data.version === undefined ) {
  16836. if ( type === AttributeType.VERTEX ) {
  16837. this.backend.createAttribute( attribute );
  16838. } else if ( type === AttributeType.INDEX ) {
  16839. this.backend.createIndexAttribute( attribute );
  16840. } else if ( type === AttributeType.STORAGE ) {
  16841. this.backend.createStorageAttribute( attribute );
  16842. } else if ( type === AttributeType.INDIRECT ) {
  16843. this.backend.createIndirectStorageAttribute( attribute );
  16844. }
  16845. data.version = this._getBufferAttribute( attribute ).version;
  16846. } else {
  16847. const bufferAttribute = this._getBufferAttribute( attribute );
  16848. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  16849. this.backend.updateAttribute( attribute );
  16850. data.version = bufferAttribute.version;
  16851. }
  16852. }
  16853. }
  16854. /**
  16855. * Utility method for handling interleaved buffer attributes correctly.
  16856. * To process them, their `InterleavedBuffer` is returned.
  16857. *
  16858. * @param {BufferAttribute} attribute - The attribute.
  16859. * @return {BufferAttribute|InterleavedBuffer}
  16860. */
  16861. _getBufferAttribute( attribute ) {
  16862. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  16863. return attribute;
  16864. }
  16865. }
  16866. /**
  16867. * Returns `true` if the given array has values that require an Uint32 array type.
  16868. *
  16869. * @private
  16870. * @function
  16871. * @param {Array<Number>} array - The array to test.
  16872. * @return {Boolean} Whether the given array has values that require an Uint32 array type or not.
  16873. */
  16874. function arrayNeedsUint32( array ) {
  16875. // assumes larger values usually on last
  16876. for ( let i = array.length - 1; i >= 0; -- i ) {
  16877. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  16878. }
  16879. return false;
  16880. }
  16881. /**
  16882. * Returns the wireframe version for the given geometry.
  16883. *
  16884. * @private
  16885. * @function
  16886. * @param {BufferGeometry} geometry - The geometry.
  16887. * @return {Number} The version.
  16888. */
  16889. function getWireframeVersion( geometry ) {
  16890. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  16891. }
  16892. /**
  16893. * Returns a wireframe index attribute for the given geometry.
  16894. *
  16895. * @private
  16896. * @function
  16897. * @param {BufferGeometry} geometry - The geometry.
  16898. * @return {BufferAttribute} The wireframe index attribute.
  16899. */
  16900. function getWireframeIndex( geometry ) {
  16901. const indices = [];
  16902. const geometryIndex = geometry.index;
  16903. const geometryPosition = geometry.attributes.position;
  16904. if ( geometryIndex !== null ) {
  16905. const array = geometryIndex.array;
  16906. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  16907. const a = array[ i + 0 ];
  16908. const b = array[ i + 1 ];
  16909. const c = array[ i + 2 ];
  16910. indices.push( a, b, b, c, c, a );
  16911. }
  16912. } else {
  16913. const array = geometryPosition.array;
  16914. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  16915. const a = i + 0;
  16916. const b = i + 1;
  16917. const c = i + 2;
  16918. indices.push( a, b, b, c, c, a );
  16919. }
  16920. }
  16921. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  16922. attribute.version = getWireframeVersion( geometry );
  16923. return attribute;
  16924. }
  16925. /**
  16926. * This renderer module manages geometries.
  16927. *
  16928. * @private
  16929. * @augments DataMap
  16930. */
  16931. class Geometries extends DataMap {
  16932. /**
  16933. * Constructs a new geometry management component.
  16934. *
  16935. * @param {Attributes} attributes - Renderer component for managing attributes.
  16936. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  16937. */
  16938. constructor( attributes, info ) {
  16939. super();
  16940. /**
  16941. * Renderer component for managing attributes.
  16942. *
  16943. * @type {Attributes}
  16944. */
  16945. this.attributes = attributes;
  16946. /**
  16947. * Renderer component for managing metrics and monitoring data.
  16948. *
  16949. * @type {Info}
  16950. */
  16951. this.info = info;
  16952. /**
  16953. * Weak Map for managing attributes for wireframe rendering.
  16954. *
  16955. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  16956. */
  16957. this.wireframes = new WeakMap();
  16958. /**
  16959. * This Weak Map is used to make sure buffer attributes are
  16960. * updated only once per render call.
  16961. *
  16962. * @type {WeakMap<BufferAttribute,Number>}
  16963. */
  16964. this.attributeCall = new WeakMap();
  16965. }
  16966. /**
  16967. * Returns `true` if the given render object has an initialized geometry.
  16968. *
  16969. * @param {RenderObject} renderObject - The render object.
  16970. * @return {Boolean} Whether if the given render object has an initialized geometry or not.
  16971. */
  16972. has( renderObject ) {
  16973. const geometry = renderObject.geometry;
  16974. return super.has( geometry ) && this.get( geometry ).initialized === true;
  16975. }
  16976. /**
  16977. * Prepares the geometry of the given render object for rendering.
  16978. *
  16979. * @param {RenderObject} renderObject - The render object.
  16980. */
  16981. updateForRender( renderObject ) {
  16982. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  16983. this.updateAttributes( renderObject );
  16984. }
  16985. /**
  16986. * Initializes the geometry of the given render object.
  16987. *
  16988. * @param {RenderObject} renderObject - The render object.
  16989. */
  16990. initGeometry( renderObject ) {
  16991. const geometry = renderObject.geometry;
  16992. const geometryData = this.get( geometry );
  16993. geometryData.initialized = true;
  16994. this.info.memory.geometries ++;
  16995. const onDispose = () => {
  16996. this.info.memory.geometries --;
  16997. const index = geometry.index;
  16998. const geometryAttributes = renderObject.getAttributes();
  16999. if ( index !== null ) {
  17000. this.attributes.delete( index );
  17001. }
  17002. for ( const geometryAttribute of geometryAttributes ) {
  17003. this.attributes.delete( geometryAttribute );
  17004. }
  17005. const wireframeAttribute = this.wireframes.get( geometry );
  17006. if ( wireframeAttribute !== undefined ) {
  17007. this.attributes.delete( wireframeAttribute );
  17008. }
  17009. geometry.removeEventListener( 'dispose', onDispose );
  17010. };
  17011. geometry.addEventListener( 'dispose', onDispose );
  17012. }
  17013. /**
  17014. * Updates the geometry attributes of the given render object.
  17015. *
  17016. * @param {RenderObject} renderObject - The render object.
  17017. */
  17018. updateAttributes( renderObject ) {
  17019. // attributes
  17020. const attributes = renderObject.getAttributes();
  17021. for ( const attribute of attributes ) {
  17022. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  17023. this.updateAttribute( attribute, AttributeType.STORAGE );
  17024. } else {
  17025. this.updateAttribute( attribute, AttributeType.VERTEX );
  17026. }
  17027. }
  17028. // indexes
  17029. const index = this.getIndex( renderObject );
  17030. if ( index !== null ) {
  17031. this.updateAttribute( index, AttributeType.INDEX );
  17032. }
  17033. // indirect
  17034. const indirect = renderObject.geometry.indirect;
  17035. if ( indirect !== null ) {
  17036. this.updateAttribute( indirect, AttributeType.INDIRECT );
  17037. }
  17038. }
  17039. /**
  17040. * Updates the given attribute.
  17041. *
  17042. * @param {BufferAttribute} attribute - The attribute to update.
  17043. * @param {Number} type - The attribute type.
  17044. */
  17045. updateAttribute( attribute, type ) {
  17046. const callId = this.info.render.calls;
  17047. if ( ! attribute.isInterleavedBufferAttribute ) {
  17048. if ( this.attributeCall.get( attribute ) !== callId ) {
  17049. this.attributes.update( attribute, type );
  17050. this.attributeCall.set( attribute, callId );
  17051. }
  17052. } else {
  17053. if ( this.attributeCall.get( attribute ) === undefined ) {
  17054. this.attributes.update( attribute, type );
  17055. this.attributeCall.set( attribute, callId );
  17056. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  17057. this.attributes.update( attribute, type );
  17058. this.attributeCall.set( attribute.data, callId );
  17059. this.attributeCall.set( attribute, callId );
  17060. }
  17061. }
  17062. }
  17063. /**
  17064. * Returns the indirect buffer attribute of the given render object.
  17065. *
  17066. * @param {RenderObject} renderObject - The render object.
  17067. * @return {BufferAttribute?} The indirect attribute. `null` if no indirect drawing is used.
  17068. */
  17069. getIndirect( renderObject ) {
  17070. return renderObject.geometry.indirect;
  17071. }
  17072. /**
  17073. * Returns the index of the given render object's geometry. This is implemented
  17074. * in a method to return a wireframe index if necessary.
  17075. *
  17076. * @param {RenderObject} renderObject - The render object.
  17077. * @return {BufferAttribute?} The index. Returns `null` for non-indexed geometries.
  17078. */
  17079. getIndex( renderObject ) {
  17080. const { geometry, material } = renderObject;
  17081. let index = geometry.index;
  17082. if ( material.wireframe === true ) {
  17083. const wireframes = this.wireframes;
  17084. let wireframeAttribute = wireframes.get( geometry );
  17085. if ( wireframeAttribute === undefined ) {
  17086. wireframeAttribute = getWireframeIndex( geometry );
  17087. wireframes.set( geometry, wireframeAttribute );
  17088. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  17089. this.attributes.delete( wireframeAttribute );
  17090. wireframeAttribute = getWireframeIndex( geometry );
  17091. wireframes.set( geometry, wireframeAttribute );
  17092. }
  17093. index = wireframeAttribute;
  17094. }
  17095. return index;
  17096. }
  17097. }
  17098. /**
  17099. * This renderer module provides a series of statistical information
  17100. * about the GPU memory and the rendering process. Useful for debugging
  17101. * and monitoring.
  17102. */
  17103. class Info {
  17104. /**
  17105. * Constructs a new info component.
  17106. */
  17107. constructor() {
  17108. /**
  17109. * Whether frame related metrics should automatically
  17110. * be resetted or not. This property should be set to `false`
  17111. * by apps which manage their own animation loop. They must
  17112. * then call `renderer.info.reset()` once per frame manually.
  17113. *
  17114. * @type {Boolean}
  17115. * @default true
  17116. */
  17117. this.autoReset = true;
  17118. /**
  17119. * The current frame ID. This ID is managed
  17120. * by `NodeFrame`.
  17121. *
  17122. * @type {Number}
  17123. * @readonly
  17124. * @default 0
  17125. */
  17126. this.frame = 0;
  17127. /**
  17128. * The number of render calls since the
  17129. * app has been started.
  17130. *
  17131. * @type {Number}
  17132. * @readonly
  17133. * @default 0
  17134. */
  17135. this.calls = 0;
  17136. /**
  17137. * Render related metrics.
  17138. *
  17139. * @type {Object}
  17140. * @readonly
  17141. * @property {Number} calls - The number of render calls since the app has been started.
  17142. * @property {Number} frameCalls - The number of render calls of the current frame.
  17143. * @property {Number} drawCalls - The number of draw calls of the current frame.
  17144. * @property {Number} triangles - The number of rendered triangle primitives of the current frame.
  17145. * @property {Number} points - The number of rendered point primitives of the current frame.
  17146. * @property {Number} lines - The number of rendered line primitives of the current frame.
  17147. * @property {Number} previousFrameCalls - The number of render calls of the previous frame.
  17148. * @property {Number} timestamp - The timestamp of the frame when using `renderer.renderAsync()`.
  17149. * @property {Number} timestampCalls - The number of render calls using `renderer.renderAsync()`.
  17150. */
  17151. this.render = {
  17152. calls: 0,
  17153. frameCalls: 0,
  17154. drawCalls: 0,
  17155. triangles: 0,
  17156. points: 0,
  17157. lines: 0,
  17158. timestamp: 0,
  17159. previousFrameCalls: 0,
  17160. timestampCalls: 0
  17161. };
  17162. /**
  17163. * Compute related metrics.
  17164. *
  17165. * @type {Object}
  17166. * @readonly
  17167. * @property {Number} calls - The number of compute calls since the app has been started.
  17168. * @property {Number} frameCalls - The number of compute calls of the current frame.
  17169. * @property {Number} previousFrameCalls - The number of compute calls of the previous frame.
  17170. * @property {Number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  17171. * @property {Number} timestampCalls - The number of render calls using `renderer.computeAsync()`.
  17172. */
  17173. this.compute = {
  17174. calls: 0,
  17175. frameCalls: 0,
  17176. timestamp: 0,
  17177. previousFrameCalls: 0,
  17178. timestampCalls: 0
  17179. };
  17180. /**
  17181. * Memory related metrics.
  17182. *
  17183. * @type {Object}
  17184. * @readonly
  17185. * @property {Number} geometries - The number of active geometries.
  17186. * @property {Number} frameCalls - The number of active textures.
  17187. */
  17188. this.memory = {
  17189. geometries: 0,
  17190. textures: 0
  17191. };
  17192. }
  17193. /**
  17194. * This method should be executed per draw call and updates the corresponding metrics.
  17195. *
  17196. * @param {Object3D} object - The 3D object that is going to be rendered.
  17197. * @param {Number} count - The vertex or index count.
  17198. * @param {Number} instanceCount - The instance count.
  17199. */
  17200. update( object, count, instanceCount ) {
  17201. this.render.drawCalls ++;
  17202. if ( object.isMesh || object.isSprite ) {
  17203. this.render.triangles += instanceCount * ( count / 3 );
  17204. } else if ( object.isPoints ) {
  17205. this.render.points += instanceCount * count;
  17206. } else if ( object.isLineSegments ) {
  17207. this.render.lines += instanceCount * ( count / 2 );
  17208. } else if ( object.isLine ) {
  17209. this.render.lines += instanceCount * ( count - 1 );
  17210. } else {
  17211. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  17212. }
  17213. }
  17214. /**
  17215. * Used by async render methods to updated timestamp metrics.
  17216. *
  17217. * @param {('render'|'compute')} type - The type of render call.
  17218. * @param {Number} time - The duration of the compute/render call in milliseconds.
  17219. */
  17220. updateTimestamp( type, time ) {
  17221. if ( this[ type ].timestampCalls === 0 ) {
  17222. this[ type ].timestamp = 0;
  17223. }
  17224. this[ type ].timestamp += time;
  17225. this[ type ].timestampCalls ++;
  17226. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  17227. this[ type ].timestampCalls = 0;
  17228. }
  17229. }
  17230. /**
  17231. * Resets frame related metrics.
  17232. */
  17233. reset() {
  17234. const previousRenderFrameCalls = this.render.frameCalls;
  17235. this.render.previousFrameCalls = previousRenderFrameCalls;
  17236. const previousComputeFrameCalls = this.compute.frameCalls;
  17237. this.compute.previousFrameCalls = previousComputeFrameCalls;
  17238. this.render.drawCalls = 0;
  17239. this.render.frameCalls = 0;
  17240. this.compute.frameCalls = 0;
  17241. this.render.triangles = 0;
  17242. this.render.points = 0;
  17243. this.render.lines = 0;
  17244. }
  17245. /**
  17246. * Performs a complete reset of the object.
  17247. */
  17248. dispose() {
  17249. this.reset();
  17250. this.calls = 0;
  17251. this.render.calls = 0;
  17252. this.compute.calls = 0;
  17253. this.render.timestamp = 0;
  17254. this.compute.timestamp = 0;
  17255. this.memory.geometries = 0;
  17256. this.memory.textures = 0;
  17257. }
  17258. }
  17259. /**
  17260. * Abstract class for representing pipelines.
  17261. *
  17262. * @private
  17263. * @abstract
  17264. */
  17265. class Pipeline {
  17266. /**
  17267. * Constructs a new pipeline.
  17268. *
  17269. * @param {String} cacheKey - The pipeline's cache key.
  17270. */
  17271. constructor( cacheKey ) {
  17272. /**
  17273. * The pipeline's cache key.
  17274. *
  17275. * @type {String}
  17276. */
  17277. this.cacheKey = cacheKey;
  17278. /**
  17279. * How often the pipeline is currently in use.
  17280. *
  17281. * @type {Number}
  17282. * @default 0
  17283. */
  17284. this.usedTimes = 0;
  17285. }
  17286. }
  17287. /**
  17288. * Class for representing render pipelines.
  17289. *
  17290. * @private
  17291. * @augments Pipeline
  17292. */
  17293. class RenderPipeline extends Pipeline {
  17294. /**
  17295. * Constructs a new render pipeline.
  17296. *
  17297. * @param {String} cacheKey - The pipeline's cache key.
  17298. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  17299. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  17300. */
  17301. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  17302. super( cacheKey );
  17303. /**
  17304. * The pipeline's vertex shader.
  17305. *
  17306. * @type {ProgrammableStage}
  17307. */
  17308. this.vertexProgram = vertexProgram;
  17309. /**
  17310. * The pipeline's fragment shader.
  17311. *
  17312. * @type {ProgrammableStage}
  17313. */
  17314. this.fragmentProgram = fragmentProgram;
  17315. }
  17316. }
  17317. /**
  17318. * Class for representing compute pipelines.
  17319. *
  17320. * @private
  17321. * @augments Pipeline
  17322. */
  17323. class ComputePipeline extends Pipeline {
  17324. /**
  17325. * Constructs a new render pipeline.
  17326. *
  17327. * @param {String} cacheKey - The pipeline's cache key.
  17328. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  17329. */
  17330. constructor( cacheKey, computeProgram ) {
  17331. super( cacheKey );
  17332. /**
  17333. * The pipeline's compute shader.
  17334. *
  17335. * @type {ProgrammableStage}
  17336. */
  17337. this.computeProgram = computeProgram;
  17338. /**
  17339. * This flag can be used for type testing.
  17340. *
  17341. * @type {Boolean}
  17342. * @readonly
  17343. * @default true
  17344. */
  17345. this.isComputePipeline = true;
  17346. }
  17347. }
  17348. let _id$8 = 0;
  17349. /**
  17350. * Class for representing programmable stages which are vertex,
  17351. * fragment or compute shaders. Unlike fixed-function states (like blending),
  17352. * they represent the programmable part of a pipeline.
  17353. *
  17354. * @private
  17355. */
  17356. class ProgrammableStage {
  17357. /**
  17358. * Constructs a new programmable stage.
  17359. *
  17360. * @param {String} code - The shader code.
  17361. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  17362. * @param {String} name - The name of the shader.
  17363. * @param {Array<Object>?} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17364. * @param {Array<Object>?} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17365. */
  17366. constructor( code, stage, name, transforms = null, attributes = null ) {
  17367. /**
  17368. * The id of the programmable stage.
  17369. *
  17370. * @type {Number}
  17371. */
  17372. this.id = _id$8 ++;
  17373. /**
  17374. * The shader code.
  17375. *
  17376. * @type {String}
  17377. */
  17378. this.code = code;
  17379. /**
  17380. * The type of stage.
  17381. *
  17382. * @type {String}
  17383. */
  17384. this.stage = stage;
  17385. /**
  17386. * The name of the stage.
  17387. * This is used for debugging purposes.
  17388. *
  17389. * @type {String}
  17390. */
  17391. this.name = name;
  17392. /**
  17393. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17394. *
  17395. * @type {Array<Object>?}
  17396. */
  17397. this.transforms = transforms;
  17398. /**
  17399. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17400. *
  17401. * @type {Array<Object>?}
  17402. */
  17403. this.attributes = attributes;
  17404. /**
  17405. * How often the programmable stage is currently in use.
  17406. *
  17407. * @type {Number}
  17408. * @default 0
  17409. */
  17410. this.usedTimes = 0;
  17411. }
  17412. }
  17413. /**
  17414. * This renderer module manages the pipelines of the renderer.
  17415. *
  17416. * @private
  17417. * @augments DataMap
  17418. */
  17419. class Pipelines extends DataMap {
  17420. /**
  17421. * Constructs a new pipeline management component.
  17422. *
  17423. * @param {Backend} backend - The renderer's backend.
  17424. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17425. */
  17426. constructor( backend, nodes ) {
  17427. super();
  17428. /**
  17429. * The renderer's backend.
  17430. *
  17431. * @type {Backend}
  17432. */
  17433. this.backend = backend;
  17434. /**
  17435. * Renderer component for managing nodes related logic.
  17436. *
  17437. * @type {Nodes}
  17438. */
  17439. this.nodes = nodes;
  17440. /**
  17441. * A references to the bindings management component.
  17442. * This reference will be set inside the `Bindings`
  17443. * constructor.
  17444. *
  17445. * @type {Bindings?}
  17446. * @default null
  17447. */
  17448. this.bindings = null;
  17449. /**
  17450. * Internal cache for maintaining pipelines.
  17451. * The key of the map is a cache key, the value the pipeline.
  17452. *
  17453. * @type {Map<String,Pipeline>}
  17454. */
  17455. this.caches = new Map();
  17456. /**
  17457. * This dictionary maintains for each shader stage type (vertex,
  17458. * fragment and compute) the programmable stage objects which
  17459. * represent the actual shader code.
  17460. *
  17461. * @type {Object<String,Map>}
  17462. */
  17463. this.programs = {
  17464. vertex: new Map(),
  17465. fragment: new Map(),
  17466. compute: new Map()
  17467. };
  17468. }
  17469. /**
  17470. * Returns a compute pipeline for the given compute node.
  17471. *
  17472. * @param {Node} computeNode - The compute node.
  17473. * @param {Array<BindGroup>} bindings - The bindings.
  17474. * @return {ComputePipeline} The compute pipeline.
  17475. */
  17476. getForCompute( computeNode, bindings ) {
  17477. const { backend } = this;
  17478. const data = this.get( computeNode );
  17479. if ( this._needsComputeUpdate( computeNode ) ) {
  17480. const previousPipeline = data.pipeline;
  17481. if ( previousPipeline ) {
  17482. previousPipeline.usedTimes --;
  17483. previousPipeline.computeProgram.usedTimes --;
  17484. }
  17485. // get shader
  17486. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  17487. // programmable stage
  17488. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  17489. if ( stageCompute === undefined ) {
  17490. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  17491. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  17492. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  17493. backend.createProgram( stageCompute );
  17494. }
  17495. // determine compute pipeline
  17496. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  17497. let pipeline = this.caches.get( cacheKey );
  17498. if ( pipeline === undefined ) {
  17499. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  17500. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  17501. }
  17502. // keep track of all used times
  17503. pipeline.usedTimes ++;
  17504. stageCompute.usedTimes ++;
  17505. //
  17506. data.version = computeNode.version;
  17507. data.pipeline = pipeline;
  17508. }
  17509. return data.pipeline;
  17510. }
  17511. /**
  17512. * Returns a render pipeline for the given render object.
  17513. *
  17514. * @param {RenderObject} renderObject - The render object.
  17515. * @param {Array<Promise>?} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  17516. * @return {RenderPipeline} The render pipeline.
  17517. */
  17518. getForRender( renderObject, promises = null ) {
  17519. const { backend } = this;
  17520. const data = this.get( renderObject );
  17521. if ( this._needsRenderUpdate( renderObject ) ) {
  17522. const previousPipeline = data.pipeline;
  17523. if ( previousPipeline ) {
  17524. previousPipeline.usedTimes --;
  17525. previousPipeline.vertexProgram.usedTimes --;
  17526. previousPipeline.fragmentProgram.usedTimes --;
  17527. }
  17528. // get shader
  17529. const nodeBuilderState = renderObject.getNodeBuilderState();
  17530. const name = renderObject.material ? renderObject.material.name : '';
  17531. // programmable stages
  17532. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  17533. if ( stageVertex === undefined ) {
  17534. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  17535. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  17536. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  17537. backend.createProgram( stageVertex );
  17538. }
  17539. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  17540. if ( stageFragment === undefined ) {
  17541. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  17542. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  17543. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  17544. backend.createProgram( stageFragment );
  17545. }
  17546. // determine render pipeline
  17547. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  17548. let pipeline = this.caches.get( cacheKey );
  17549. if ( pipeline === undefined ) {
  17550. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  17551. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  17552. } else {
  17553. renderObject.pipeline = pipeline;
  17554. }
  17555. // keep track of all used times
  17556. pipeline.usedTimes ++;
  17557. stageVertex.usedTimes ++;
  17558. stageFragment.usedTimes ++;
  17559. //
  17560. data.pipeline = pipeline;
  17561. }
  17562. return data.pipeline;
  17563. }
  17564. /**
  17565. * Deletes the pipeline for the given render object.
  17566. *
  17567. * @param {RenderObject} object - The render object.
  17568. * @return {Object?} The deleted dictionary.
  17569. */
  17570. delete( object ) {
  17571. const pipeline = this.get( object ).pipeline;
  17572. if ( pipeline ) {
  17573. // pipeline
  17574. pipeline.usedTimes --;
  17575. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  17576. // programs
  17577. if ( pipeline.isComputePipeline ) {
  17578. pipeline.computeProgram.usedTimes --;
  17579. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  17580. } else {
  17581. pipeline.fragmentProgram.usedTimes --;
  17582. pipeline.vertexProgram.usedTimes --;
  17583. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  17584. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  17585. }
  17586. }
  17587. return super.delete( object );
  17588. }
  17589. /**
  17590. * Frees internal resources.
  17591. */
  17592. dispose() {
  17593. super.dispose();
  17594. this.caches = new Map();
  17595. this.programs = {
  17596. vertex: new Map(),
  17597. fragment: new Map(),
  17598. compute: new Map()
  17599. };
  17600. }
  17601. /**
  17602. * Updates the pipeline for the given render object.
  17603. *
  17604. * @param {RenderObject} renderObject - The render object.
  17605. */
  17606. updateForRender( renderObject ) {
  17607. this.getForRender( renderObject );
  17608. }
  17609. /**
  17610. * Returns a compute pipeline for the given parameters.
  17611. *
  17612. * @private
  17613. * @param {Node} computeNode - The compute node.
  17614. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  17615. * @param {String} cacheKey - The cache key.
  17616. * @param {Array<BindGroup>} bindings - The bindings.
  17617. * @return {ComputePipeline} The compute pipeline.
  17618. */
  17619. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  17620. // check for existing pipeline
  17621. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  17622. let pipeline = this.caches.get( cacheKey );
  17623. if ( pipeline === undefined ) {
  17624. pipeline = new ComputePipeline( cacheKey, stageCompute );
  17625. this.caches.set( cacheKey, pipeline );
  17626. this.backend.createComputePipeline( pipeline, bindings );
  17627. }
  17628. return pipeline;
  17629. }
  17630. /**
  17631. * Returns a render pipeline for the given parameters.
  17632. *
  17633. * @private
  17634. * @param {RenderObject} renderObject - The render object.
  17635. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  17636. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  17637. * @param {String} cacheKey - The cache key.
  17638. * @param {Array} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  17639. * @return {ComputePipeline} The compute pipeline.
  17640. */
  17641. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  17642. // check for existing pipeline
  17643. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  17644. let pipeline = this.caches.get( cacheKey );
  17645. if ( pipeline === undefined ) {
  17646. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  17647. this.caches.set( cacheKey, pipeline );
  17648. renderObject.pipeline = pipeline;
  17649. // The `promises` array is `null` by default and only set to an empty array when
  17650. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  17651. // pending promises that resolve when the render pipelines are ready for rendering.
  17652. this.backend.createRenderPipeline( renderObject, promises );
  17653. }
  17654. return pipeline;
  17655. }
  17656. /**
  17657. * Computes a cache key representing a compute pipeline.
  17658. *
  17659. * @private
  17660. * @param {Node} computeNode - The compute node.
  17661. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  17662. * @return {String} The cache key.
  17663. */
  17664. _getComputeCacheKey( computeNode, stageCompute ) {
  17665. return computeNode.id + ',' + stageCompute.id;
  17666. }
  17667. /**
  17668. * Computes a cache key representing a render pipeline.
  17669. *
  17670. * @private
  17671. * @param {RenderObject} renderObject - The render object.
  17672. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  17673. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  17674. * @return {String} The cache key.
  17675. */
  17676. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  17677. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  17678. }
  17679. /**
  17680. * Releases the given pipeline.
  17681. *
  17682. * @private
  17683. * @param {Pipeline} pipeline - The pipeline to release.
  17684. */
  17685. _releasePipeline( pipeline ) {
  17686. this.caches.delete( pipeline.cacheKey );
  17687. }
  17688. /**
  17689. * Releases the shader program.
  17690. *
  17691. * @private
  17692. * @param {Object} program - The shader program to release.
  17693. */
  17694. _releaseProgram( program ) {
  17695. const code = program.code;
  17696. const stage = program.stage;
  17697. this.programs[ stage ].delete( code );
  17698. }
  17699. /**
  17700. * Returns `true` if the compute pipeline for the given compute node requires an update.
  17701. *
  17702. * @private
  17703. * @param {Node} computeNode - The compute node.
  17704. * @return {Boolean} Whether the compute pipeline for the given compute node requires an update or not.
  17705. */
  17706. _needsComputeUpdate( computeNode ) {
  17707. const data = this.get( computeNode );
  17708. return data.pipeline === undefined || data.version !== computeNode.version;
  17709. }
  17710. /**
  17711. * Returns `true` if the render pipeline for the given render object requires an update.
  17712. *
  17713. * @private
  17714. * @param {RenderObject} renderObject - The render object.
  17715. * @return {Boolean} Whether the render object for the given render object requires an update or not.
  17716. */
  17717. _needsRenderUpdate( renderObject ) {
  17718. const data = this.get( renderObject );
  17719. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  17720. }
  17721. }
  17722. /**
  17723. * This renderer module manages the bindings of the renderer.
  17724. *
  17725. * @private
  17726. * @augments DataMap
  17727. */
  17728. class Bindings extends DataMap {
  17729. /**
  17730. * Constructs a new bindings management component.
  17731. *
  17732. * @param {Backend} backend - The renderer's backend.
  17733. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17734. * @param {Textures} textures - Renderer component for managing textures.
  17735. * @param {Attributes} attributes - Renderer component for managing attributes.
  17736. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  17737. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  17738. */
  17739. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  17740. super();
  17741. /**
  17742. * The renderer's backend.
  17743. *
  17744. * @type {Backend}
  17745. */
  17746. this.backend = backend;
  17747. /**
  17748. * Renderer component for managing textures.
  17749. *
  17750. * @type {Textures}
  17751. */
  17752. this.textures = textures;
  17753. /**
  17754. * Renderer component for managing pipelines.
  17755. *
  17756. * @type {Pipelines}
  17757. */
  17758. this.pipelines = pipelines;
  17759. /**
  17760. * Renderer component for managing attributes.
  17761. *
  17762. * @type {Attributes}
  17763. */
  17764. this.attributes = attributes;
  17765. /**
  17766. * Renderer component for managing nodes related logic.
  17767. *
  17768. * @type {Nodes}
  17769. */
  17770. this.nodes = nodes;
  17771. /**
  17772. * Renderer component for managing metrics and monitoring data.
  17773. *
  17774. * @type {Info}
  17775. */
  17776. this.info = info;
  17777. this.pipelines.bindings = this; // assign bindings to pipelines
  17778. }
  17779. /**
  17780. * Returns the bind groups for the given render object.
  17781. *
  17782. * @param {RenderObject} renderObject - The render object.
  17783. * @return {Array<BindGroup>} The bind groups.
  17784. */
  17785. getForRender( renderObject ) {
  17786. const bindings = renderObject.getBindings();
  17787. for ( const bindGroup of bindings ) {
  17788. const groupData = this.get( bindGroup );
  17789. if ( groupData.bindGroup === undefined ) {
  17790. // each object defines an array of bindings (ubos, textures, samplers etc.)
  17791. this._init( bindGroup );
  17792. this.backend.createBindings( bindGroup, bindings, 0 );
  17793. groupData.bindGroup = bindGroup;
  17794. }
  17795. }
  17796. return bindings;
  17797. }
  17798. /**
  17799. * Returns the bind groups for the given compute node.
  17800. *
  17801. * @param {Node} computeNode - The compute node.
  17802. * @return {Array<BindGroup>} The bind groups.
  17803. */
  17804. getForCompute( computeNode ) {
  17805. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  17806. for ( const bindGroup of bindings ) {
  17807. const groupData = this.get( bindGroup );
  17808. if ( groupData.bindGroup === undefined ) {
  17809. this._init( bindGroup );
  17810. this.backend.createBindings( bindGroup, bindings, 0 );
  17811. groupData.bindGroup = bindGroup;
  17812. }
  17813. }
  17814. return bindings;
  17815. }
  17816. /**
  17817. * Updates the bindings for the given compute node.
  17818. *
  17819. * @param {Node} computeNode - The compute node.
  17820. */
  17821. updateForCompute( computeNode ) {
  17822. this._updateBindings( this.getForCompute( computeNode ) );
  17823. }
  17824. /**
  17825. * Updates the bindings for the given render object.
  17826. *
  17827. * @param {RenderObject} renderObject - The render object.
  17828. */
  17829. updateForRender( renderObject ) {
  17830. this._updateBindings( this.getForRender( renderObject ) );
  17831. }
  17832. /**
  17833. * Updates the given array of bindings.
  17834. *
  17835. * @param {Array<BindGroup>} bindings - The bind groups.
  17836. */
  17837. _updateBindings( bindings ) {
  17838. for ( const bindGroup of bindings ) {
  17839. this._update( bindGroup, bindings );
  17840. }
  17841. }
  17842. /**
  17843. * Initializes the given bind group.
  17844. *
  17845. * @param {BindGroup} bindGroup - The bind group to initialize.
  17846. */
  17847. _init( bindGroup ) {
  17848. for ( const binding of bindGroup.bindings ) {
  17849. if ( binding.isSampledTexture ) {
  17850. this.textures.updateTexture( binding.texture );
  17851. } else if ( binding.isStorageBuffer ) {
  17852. const attribute = binding.attribute;
  17853. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  17854. this.attributes.update( attribute, attributeType );
  17855. }
  17856. }
  17857. }
  17858. /**
  17859. * Updates the given bind group.
  17860. *
  17861. * @param {BindGroup} bindGroup - The bind group to update.
  17862. * @param {Array<BindGroup>} bindings - The bind groups.
  17863. */
  17864. _update( bindGroup, bindings ) {
  17865. const { backend } = this;
  17866. let needsBindingsUpdate = false;
  17867. let cacheBindings = true;
  17868. let cacheIndex = 0;
  17869. let version = 0;
  17870. // iterate over all bindings and check if buffer updates or a new binding group is required
  17871. for ( const binding of bindGroup.bindings ) {
  17872. if ( binding.isNodeUniformsGroup ) {
  17873. const updated = this.nodes.updateGroup( binding );
  17874. // every uniforms group is a uniform buffer. So if no update is required,
  17875. // we move one with the next binding. Otherwise the next if block will update the group.
  17876. if ( updated === false ) continue;
  17877. }
  17878. if ( binding.isUniformBuffer ) {
  17879. const updated = binding.update();
  17880. if ( updated ) {
  17881. backend.updateBinding( binding );
  17882. }
  17883. } else if ( binding.isSampler ) {
  17884. binding.update();
  17885. } else if ( binding.isSampledTexture ) {
  17886. const texturesTextureData = this.textures.get( binding.texture );
  17887. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  17888. const updated = binding.update();
  17889. const texture = binding.texture;
  17890. if ( updated ) {
  17891. this.textures.updateTexture( texture );
  17892. }
  17893. const textureData = backend.get( texture );
  17894. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  17895. cacheBindings = false;
  17896. } else {
  17897. cacheIndex = cacheIndex * 10 + texture.id;
  17898. version += texture.version;
  17899. }
  17900. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  17901. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  17902. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  17903. this.textures.updateTexture( texture );
  17904. needsBindingsUpdate = true;
  17905. }
  17906. if ( texture.isStorageTexture === true ) {
  17907. const textureData = this.get( texture );
  17908. if ( binding.store === true ) {
  17909. textureData.needsMipmap = true;
  17910. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  17911. this.backend.generateMipmaps( texture );
  17912. textureData.needsMipmap = false;
  17913. }
  17914. }
  17915. }
  17916. }
  17917. if ( needsBindingsUpdate === true ) {
  17918. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  17919. }
  17920. }
  17921. }
  17922. /**
  17923. * Default sorting function for opaque render items.
  17924. *
  17925. * @private
  17926. * @function
  17927. * @param {Object} a - The first render item.
  17928. * @param {Object} b - The second render item.
  17929. * @return {Number} A numeric value which defines the sort order.
  17930. */
  17931. function painterSortStable( a, b ) {
  17932. if ( a.groupOrder !== b.groupOrder ) {
  17933. return a.groupOrder - b.groupOrder;
  17934. } else if ( a.renderOrder !== b.renderOrder ) {
  17935. return a.renderOrder - b.renderOrder;
  17936. } else if ( a.material.id !== b.material.id ) {
  17937. return a.material.id - b.material.id;
  17938. } else if ( a.z !== b.z ) {
  17939. return a.z - b.z;
  17940. } else {
  17941. return a.id - b.id;
  17942. }
  17943. }
  17944. /**
  17945. * Default sorting function for transparent render items.
  17946. *
  17947. * @private
  17948. * @function
  17949. * @param {Object} a - The first render item.
  17950. * @param {Object} b - The second render item.
  17951. * @return {Number} A numeric value which defines the sort order.
  17952. */
  17953. function reversePainterSortStable( a, b ) {
  17954. if ( a.groupOrder !== b.groupOrder ) {
  17955. return a.groupOrder - b.groupOrder;
  17956. } else if ( a.renderOrder !== b.renderOrder ) {
  17957. return a.renderOrder - b.renderOrder;
  17958. } else if ( a.z !== b.z ) {
  17959. return b.z - a.z;
  17960. } else {
  17961. return a.id - b.id;
  17962. }
  17963. }
  17964. /**
  17965. * Returns `true` if the given transparent material requires a double pass.
  17966. *
  17967. * @private
  17968. * @function
  17969. * @param {Material} material - The transparent material.
  17970. * @return {Boolean} Whether the given material requires a double pass or not.
  17971. */
  17972. function needsDoublePass( material ) {
  17973. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  17974. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  17975. }
  17976. /**
  17977. * When the renderer analyzes the scene at the beginning of a render call,
  17978. * it stores 3D object for further processing in render lists. Depending on the
  17979. * properties of a 3D objects (like their transformation or material state), the
  17980. * objects are maintained in ordered lists for the actual rendering.
  17981. *
  17982. * Render lists are unique per scene and camera combination.
  17983. *
  17984. * @private
  17985. * @augments Pipeline
  17986. */
  17987. class RenderList {
  17988. /**
  17989. * Constructs a render list.
  17990. *
  17991. * @param {Lighting} lighting - The lighting management component.
  17992. * @param {Scene} scene - The scene.
  17993. * @param {Camera} camera - The camera the scene is rendered with.
  17994. */
  17995. constructor( lighting, scene, camera ) {
  17996. /**
  17997. * 3D objects are transformed into render items and stored in this array.
  17998. *
  17999. * @type {Array<Object>}
  18000. */
  18001. this.renderItems = [];
  18002. /**
  18003. * The current render items index.
  18004. *
  18005. * @type {Number}
  18006. * @default 0
  18007. */
  18008. this.renderItemsIndex = 0;
  18009. /**
  18010. * A list with opaque render items.
  18011. *
  18012. * @type {Array<Object>}
  18013. */
  18014. this.opaque = [];
  18015. /**
  18016. * A list with transparent render items which require
  18017. * double pass rendering (e.g. transmissive objects).
  18018. *
  18019. * @type {Array<Object>}
  18020. */
  18021. this.transparentDoublePass = [];
  18022. /**
  18023. * A list with transparent render items.
  18024. *
  18025. * @type {Array<Object>}
  18026. */
  18027. this.transparent = [];
  18028. /**
  18029. * A list with transparent render bundle data.
  18030. *
  18031. * @type {Array<Object>}
  18032. */
  18033. this.bundles = [];
  18034. /**
  18035. * The render list's lights node. This node is later
  18036. * relevant for the actual analytical light nodes which
  18037. * compute the scene's lighting in the shader.
  18038. *
  18039. * @type {LightsNode}
  18040. */
  18041. this.lightsNode = lighting.getNode( scene, camera );
  18042. /**
  18043. * The scene's lights stored in an array. This array
  18044. * is used to setup the lights node.
  18045. *
  18046. * @type {Array<Light>}
  18047. */
  18048. this.lightsArray = [];
  18049. /**
  18050. * The scene.
  18051. *
  18052. * @type {Scene}
  18053. */
  18054. this.scene = scene;
  18055. /**
  18056. * The camera the scene is rendered with.
  18057. *
  18058. * @type {Camera}
  18059. */
  18060. this.camera = camera;
  18061. /**
  18062. * How many objects perform occlusion query tests.
  18063. *
  18064. * @type {Number}
  18065. * @default 0
  18066. */
  18067. this.occlusionQueryCount = 0;
  18068. }
  18069. /**
  18070. * This method is called right at the beginning of a render call
  18071. * before the scene is analyzed. It prepares the internal data
  18072. * structures for the upcoming render lists generation.
  18073. *
  18074. * @return {RenderList} A reference to this render list.
  18075. */
  18076. begin() {
  18077. this.renderItemsIndex = 0;
  18078. this.opaque.length = 0;
  18079. this.transparentDoublePass.length = 0;
  18080. this.transparent.length = 0;
  18081. this.bundles.length = 0;
  18082. this.lightsArray.length = 0;
  18083. this.occlusionQueryCount = 0;
  18084. return this;
  18085. }
  18086. /**
  18087. * Returns a render item for the giving render item state. The state is defined
  18088. * by a series of object-related parameters.
  18089. *
  18090. * The method avoids object creation by holding render items and reusing them in
  18091. * subsequent render calls (just with different property values).
  18092. *
  18093. * @param {Object3D} object - The 3D object.
  18094. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18095. * @param {Material} material - The 3D object's material.
  18096. * @param {Number} groupOrder - The current group order.
  18097. * @param {Number} z - Th 3D object's depth value (z value in clip space).
  18098. * @param {Number?} group - {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18099. * @param {ClippingContext} clippingContext - The current clipping context.
  18100. * @return {Object} The render item.
  18101. */
  18102. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18103. let renderItem = this.renderItems[ this.renderItemsIndex ];
  18104. if ( renderItem === undefined ) {
  18105. renderItem = {
  18106. id: object.id,
  18107. object: object,
  18108. geometry: geometry,
  18109. material: material,
  18110. groupOrder: groupOrder,
  18111. renderOrder: object.renderOrder,
  18112. z: z,
  18113. group: group,
  18114. clippingContext: clippingContext
  18115. };
  18116. this.renderItems[ this.renderItemsIndex ] = renderItem;
  18117. } else {
  18118. renderItem.id = object.id;
  18119. renderItem.object = object;
  18120. renderItem.geometry = geometry;
  18121. renderItem.material = material;
  18122. renderItem.groupOrder = groupOrder;
  18123. renderItem.renderOrder = object.renderOrder;
  18124. renderItem.z = z;
  18125. renderItem.group = group;
  18126. renderItem.clippingContext = clippingContext;
  18127. }
  18128. this.renderItemsIndex ++;
  18129. return renderItem;
  18130. }
  18131. /**
  18132. * Pushes the given object as a render item to the internal render lists.
  18133. * The selected lists depend on the object properties.
  18134. *
  18135. * @param {Object3D} object - The 3D object.
  18136. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18137. * @param {Material} material - The 3D object's material.
  18138. * @param {Number} groupOrder - The current group order.
  18139. * @param {Number} z - Th 3D object's depth value (z value in clip space).
  18140. * @param {Number?} group - {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18141. * @param {ClippingContext} clippingContext - The current clipping context.
  18142. */
  18143. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18144. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  18145. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  18146. if ( material.transparent === true || material.transmission > 0 ) {
  18147. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  18148. this.transparent.push( renderItem );
  18149. } else {
  18150. this.opaque.push( renderItem );
  18151. }
  18152. }
  18153. /**
  18154. * Inserts the given object as a render item at the start of the internal render lists.
  18155. * The selected lists depend on the object properties.
  18156. *
  18157. * @param {Object3D} object - The 3D object.
  18158. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18159. * @param {Material} material - The 3D object's material.
  18160. * @param {Number} groupOrder - The current group order.
  18161. * @param {Number} z - Th 3D object's depth value (z value in clip space).
  18162. * @param {Number?} group - {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18163. * @param {ClippingContext} clippingContext - The current clipping context.
  18164. */
  18165. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18166. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  18167. if ( material.transparent === true || material.transmission > 0 ) {
  18168. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  18169. this.transparent.unshift( renderItem );
  18170. } else {
  18171. this.opaque.unshift( renderItem );
  18172. }
  18173. }
  18174. /**
  18175. * Pushes render bundle group data into the render list.
  18176. *
  18177. * @param {Object} group - Bundle group data.
  18178. */
  18179. pushBundle( group ) {
  18180. this.bundles.push( group );
  18181. }
  18182. /**
  18183. * Pushes a light into the render list.
  18184. *
  18185. * @param {Light} light - The light.
  18186. */
  18187. pushLight( light ) {
  18188. this.lightsArray.push( light );
  18189. }
  18190. /**
  18191. * Sorts the internal render lists.
  18192. *
  18193. * @param {Function} customOpaqueSort - A custom sort function for opaque objects.
  18194. * @param {Function} customTransparentSort - A custom sort function for transparent objects.
  18195. */
  18196. sort( customOpaqueSort, customTransparentSort ) {
  18197. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  18198. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  18199. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  18200. }
  18201. /**
  18202. * This method performs finalizing tasks right after the render lists
  18203. * have been generated.
  18204. */
  18205. finish() {
  18206. // update lights
  18207. this.lightsNode.setLights( this.lightsArray );
  18208. // Clear references from inactive renderItems in the list
  18209. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  18210. const renderItem = this.renderItems[ i ];
  18211. if ( renderItem.id === null ) break;
  18212. renderItem.id = null;
  18213. renderItem.object = null;
  18214. renderItem.geometry = null;
  18215. renderItem.material = null;
  18216. renderItem.groupOrder = null;
  18217. renderItem.renderOrder = null;
  18218. renderItem.z = null;
  18219. renderItem.group = null;
  18220. renderItem.clippingContext = null;
  18221. }
  18222. }
  18223. }
  18224. const _chainKeys$4 = [];
  18225. /**
  18226. * This renderer module manages the render lists which are unique
  18227. * per scene and camera combination.
  18228. *
  18229. * @private
  18230. */
  18231. class RenderLists {
  18232. /**
  18233. * Constructs a render lists management component.
  18234. *
  18235. * @param {Lighting} lighting - The lighting management component.
  18236. */
  18237. constructor( lighting ) {
  18238. /**
  18239. * The lighting management component.
  18240. *
  18241. * @type {Lighting}
  18242. */
  18243. this.lighting = lighting;
  18244. /**
  18245. * The internal chain map which holds the render lists.
  18246. *
  18247. * @type {ChainMap}
  18248. */
  18249. this.lists = new ChainMap();
  18250. }
  18251. /**
  18252. * Returns a render list for the given scene and camera.
  18253. *
  18254. * @param {Scene} scene - The scene.
  18255. * @param {Camera} camera - The camera.
  18256. * @return {RenderList} The render list.
  18257. */
  18258. get( scene, camera ) {
  18259. const lists = this.lists;
  18260. _chainKeys$4[ 0 ] = scene;
  18261. _chainKeys$4[ 1 ] = camera;
  18262. let list = lists.get( _chainKeys$4 );
  18263. if ( list === undefined ) {
  18264. list = new RenderList( this.lighting, scene, camera );
  18265. lists.set( _chainKeys$4, list );
  18266. }
  18267. _chainKeys$4.length = 0;
  18268. return list;
  18269. }
  18270. /**
  18271. * Frees all internal resources.
  18272. */
  18273. dispose() {
  18274. this.lists = new ChainMap();
  18275. }
  18276. }
  18277. let _id$7 = 0;
  18278. /**
  18279. * Any render or compute command is executed in a specific context that defines
  18280. * the state of the renderer and its backend. Typical examples for such context
  18281. * data are the current clear values or data from the active framebuffer. This
  18282. * module is used to represent these contexts as objects.
  18283. *
  18284. * @private
  18285. */
  18286. class RenderContext {
  18287. /**
  18288. * Constructs a new render context.
  18289. */
  18290. constructor() {
  18291. /**
  18292. * The context's ID.
  18293. *
  18294. * @type {Number}
  18295. */
  18296. this.id = _id$7 ++;
  18297. /**
  18298. * Whether the current active framebuffer has a color attachment.
  18299. *
  18300. * @type {Boolean}
  18301. * @default true
  18302. */
  18303. this.color = true;
  18304. /**
  18305. * Whether the color attachment should be cleared or not.
  18306. *
  18307. * @type {Boolean}
  18308. * @default true
  18309. */
  18310. this.clearColor = true;
  18311. /**
  18312. * The clear color value.
  18313. *
  18314. * @type {Object}
  18315. * @default true
  18316. */
  18317. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  18318. /**
  18319. * Whether the current active framebuffer has a depth attachment.
  18320. *
  18321. * @type {Boolean}
  18322. * @default true
  18323. */
  18324. this.depth = true;
  18325. /**
  18326. * Whether the depth attachment should be cleared or not.
  18327. *
  18328. * @type {Boolean}
  18329. * @default true
  18330. */
  18331. this.clearDepth = true;
  18332. /**
  18333. * The clear depth value.
  18334. *
  18335. * @type {Number}
  18336. * @default 1
  18337. */
  18338. this.clearDepthValue = 1;
  18339. /**
  18340. * Whether the current active framebuffer has a stencil attachment.
  18341. *
  18342. * @type {Boolean}
  18343. * @default false
  18344. */
  18345. this.stencil = false;
  18346. /**
  18347. * Whether the stencil attachment should be cleared or not.
  18348. *
  18349. * @type {Boolean}
  18350. * @default true
  18351. */
  18352. this.clearStencil = true;
  18353. /**
  18354. * The clear stencil value.
  18355. *
  18356. * @type {Number}
  18357. * @default 1
  18358. */
  18359. this.clearStencilValue = 1;
  18360. /**
  18361. * By default the viewport encloses the entire framebuffer If a smaller
  18362. * viewport is manually defined, this property is to `true` by the renderer.
  18363. *
  18364. * @type {Boolean}
  18365. * @default false
  18366. */
  18367. this.viewport = false;
  18368. /**
  18369. * The viewport value. This value is in physical pixels meaning it incorporates
  18370. * the renderer's pixel ratio. The viewport property of render targets or
  18371. * the renderer is in logical pixels.
  18372. *
  18373. * @type {Vector4}
  18374. */
  18375. this.viewportValue = new Vector4();
  18376. /**
  18377. * When the scissor test is active and scissor rectangle smaller than the
  18378. * framebuffers dimensions, this property is to `true` by the renderer.
  18379. *
  18380. * @type {Boolean}
  18381. * @default false
  18382. */
  18383. this.scissor = false;
  18384. /**
  18385. * The scissor rectangle.
  18386. *
  18387. * @type {Vector4}
  18388. */
  18389. this.scissorValue = new Vector4();
  18390. /**
  18391. * The textures of the active render target.
  18392. * `null` when no render target is set.
  18393. *
  18394. * @type {Array<Texture>?}
  18395. * @default null
  18396. */
  18397. this.textures = null;
  18398. /**
  18399. * The depth texture of the active render target.
  18400. * `null` when no render target is set.
  18401. *
  18402. * @type {DepthTexture?}
  18403. * @default null
  18404. */
  18405. this.depthTexture = null;
  18406. /**
  18407. * The active cube face.
  18408. *
  18409. * @type {Number}
  18410. * @default 0
  18411. */
  18412. this.activeCubeFace = 0;
  18413. /**
  18414. * The number of MSAA samples. This value is always `1` when
  18415. * MSAA isn't used.
  18416. *
  18417. * @type {Number}
  18418. * @default 1
  18419. */
  18420. this.sampleCount = 1;
  18421. /**
  18422. * The framebuffers width in physical pixels.
  18423. *
  18424. * @type {Number}
  18425. * @default 0
  18426. */
  18427. this.width = 0;
  18428. /**
  18429. * The framebuffers height in physical pixels.
  18430. *
  18431. * @type {Number}
  18432. * @default 0
  18433. */
  18434. this.height = 0;
  18435. /**
  18436. * This flag can be used for type testing.
  18437. *
  18438. * @type {Boolean}
  18439. * @readonly
  18440. * @default true
  18441. */
  18442. this.isRenderContext = true;
  18443. }
  18444. /**
  18445. * Returns the cache key of this render context.
  18446. *
  18447. * @return {Number} The cache key.
  18448. */
  18449. getCacheKey() {
  18450. return getCacheKey( this );
  18451. }
  18452. }
  18453. /**
  18454. * Computes a cache key for the given render context.
  18455. *
  18456. * @param {RenderContext} renderContext - The render context.
  18457. * @return {Number} The cache key.
  18458. */
  18459. function getCacheKey( renderContext ) {
  18460. const { textures, activeCubeFace } = renderContext;
  18461. const values = [ activeCubeFace ];
  18462. for ( const texture of textures ) {
  18463. values.push( texture.id );
  18464. }
  18465. return hashArray( values );
  18466. }
  18467. const _chainKeys$3 = [];
  18468. const _defaultScene = /*@__PURE__*/ new Scene();
  18469. const _defaultCamera = /*@__PURE__*/ new Camera();
  18470. /**
  18471. * This module manages the render contexts of the renderer.
  18472. *
  18473. * @private
  18474. */
  18475. class RenderContexts {
  18476. /**
  18477. * Constructs a new render context management component.
  18478. */
  18479. constructor() {
  18480. /**
  18481. * A dictionary that manages render contexts in chain maps
  18482. * for each attachment state.
  18483. *
  18484. * @type {Object<String,ChainMap>}
  18485. */
  18486. this.chainMaps = {};
  18487. }
  18488. /**
  18489. * Returns a render context for the given scene, camera and render target.
  18490. *
  18491. * @param {Scene} scene - The scene.
  18492. * @param {Camera} camera - The camera that is used to render the scene.
  18493. * @param {RenderTarget?} [renderTarget=null] - The active render target.
  18494. * @return {RenderContext} The render context.
  18495. */
  18496. get( scene, camera, renderTarget = null ) {
  18497. _chainKeys$3[ 0 ] = scene;
  18498. _chainKeys$3[ 1 ] = camera;
  18499. let attachmentState;
  18500. if ( renderTarget === null ) {
  18501. attachmentState = 'default';
  18502. } else {
  18503. const format = renderTarget.texture.format;
  18504. const count = renderTarget.textures.length;
  18505. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  18506. }
  18507. const chainMap = this._getChainMap( attachmentState );
  18508. let renderState = chainMap.get( _chainKeys$3 );
  18509. if ( renderState === undefined ) {
  18510. renderState = new RenderContext();
  18511. chainMap.set( _chainKeys$3, renderState );
  18512. }
  18513. _chainKeys$3.length = 0;
  18514. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  18515. return renderState;
  18516. }
  18517. /**
  18518. * Returns a render context intended for clear operations.
  18519. *
  18520. * @param {RenderTarget?} [renderTarget=null] - The active render target.
  18521. * @return {RenderContext} The render context.
  18522. */
  18523. getForClear( renderTarget = null ) {
  18524. return this.get( _defaultScene, _defaultCamera, renderTarget );
  18525. }
  18526. /**
  18527. * Returns a chain map for the given attachment state.
  18528. *
  18529. * @private
  18530. * @param {String} attachmentState - The attachment state.
  18531. * @return {ChainMap} The chain map.
  18532. */
  18533. _getChainMap( attachmentState ) {
  18534. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  18535. }
  18536. /**
  18537. * Frees internal resources.
  18538. */
  18539. dispose() {
  18540. this.chainMaps = {};
  18541. }
  18542. }
  18543. const _size$3 = /*@__PURE__*/ new Vector3();
  18544. /**
  18545. * This module manages the textures of the renderer.
  18546. *
  18547. * @private
  18548. * @augments DataMap
  18549. */
  18550. class Textures extends DataMap {
  18551. /**
  18552. * Constructs a new texture management component.
  18553. *
  18554. * @param {Renderer} renderer - The renderer.
  18555. * @param {Backend} backend - The renderer's backend.
  18556. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  18557. */
  18558. constructor( renderer, backend, info ) {
  18559. super();
  18560. /**
  18561. * The renderer.
  18562. *
  18563. * @type {Renderer}
  18564. */
  18565. this.renderer = renderer;
  18566. /**
  18567. * The backend.
  18568. *
  18569. * @type {Backend}
  18570. */
  18571. this.backend = backend;
  18572. /**
  18573. * Renderer component for managing metrics and monitoring data.
  18574. *
  18575. * @type {Info}
  18576. */
  18577. this.info = info;
  18578. }
  18579. /**
  18580. * Updates the given render target. Based on the given render target configuration,
  18581. * it updates the texture states representing the attachments of the framebuffer.
  18582. *
  18583. * @param {RenderTarget} renderTarget - The render target to update.
  18584. * @param {Number} [activeMipmapLevel=0] - The active mipmap level.
  18585. */
  18586. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  18587. const renderTargetData = this.get( renderTarget );
  18588. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  18589. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  18590. const textures = renderTarget.textures;
  18591. const size = this.getSize( textures[ 0 ] );
  18592. const mipWidth = size.width >> activeMipmapLevel;
  18593. const mipHeight = size.height >> activeMipmapLevel;
  18594. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  18595. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  18596. let textureNeedsUpdate = false;
  18597. if ( depthTexture === undefined && useDepthTexture ) {
  18598. depthTexture = new DepthTexture();
  18599. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  18600. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  18601. depthTexture.image.width = mipWidth;
  18602. depthTexture.image.height = mipHeight;
  18603. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  18604. }
  18605. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  18606. textureNeedsUpdate = true;
  18607. if ( depthTexture ) {
  18608. depthTexture.needsUpdate = true;
  18609. depthTexture.image.width = mipWidth;
  18610. depthTexture.image.height = mipHeight;
  18611. }
  18612. }
  18613. renderTargetData.width = size.width;
  18614. renderTargetData.height = size.height;
  18615. renderTargetData.textures = textures;
  18616. renderTargetData.depthTexture = depthTexture || null;
  18617. renderTargetData.depth = renderTarget.depthBuffer;
  18618. renderTargetData.stencil = renderTarget.stencilBuffer;
  18619. renderTargetData.renderTarget = renderTarget;
  18620. if ( renderTargetData.sampleCount !== sampleCount ) {
  18621. textureNeedsUpdate = true;
  18622. if ( depthTexture ) {
  18623. depthTexture.needsUpdate = true;
  18624. }
  18625. renderTargetData.sampleCount = sampleCount;
  18626. }
  18627. //
  18628. const options = { sampleCount };
  18629. for ( let i = 0; i < textures.length; i ++ ) {
  18630. const texture = textures[ i ];
  18631. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  18632. this.updateTexture( texture, options );
  18633. }
  18634. if ( depthTexture ) {
  18635. this.updateTexture( depthTexture, options );
  18636. }
  18637. // dispose handler
  18638. if ( renderTargetData.initialized !== true ) {
  18639. renderTargetData.initialized = true;
  18640. // dispose
  18641. const onDispose = () => {
  18642. renderTarget.removeEventListener( 'dispose', onDispose );
  18643. for ( let i = 0; i < textures.length; i ++ ) {
  18644. this._destroyTexture( textures[ i ] );
  18645. }
  18646. if ( depthTexture ) {
  18647. this._destroyTexture( depthTexture );
  18648. }
  18649. this.delete( renderTarget );
  18650. };
  18651. renderTarget.addEventListener( 'dispose', onDispose );
  18652. }
  18653. }
  18654. /**
  18655. * Updates the given texture. Depending on the texture state, this method
  18656. * triggers the upload of texture data to the GPU memory. If the texture data are
  18657. * not yet ready for the upload, it uses default texture data for as a placeholder.
  18658. *
  18659. * @param {Texture} texture - The texture to update.
  18660. * @param {Object} [options={}] - The options.
  18661. */
  18662. updateTexture( texture, options = {} ) {
  18663. const textureData = this.get( texture );
  18664. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  18665. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  18666. const backend = this.backend;
  18667. if ( isRenderTarget && textureData.initialized === true ) {
  18668. // it's an update
  18669. backend.destroySampler( texture );
  18670. backend.destroyTexture( texture );
  18671. }
  18672. //
  18673. if ( texture.isFramebufferTexture ) {
  18674. const renderTarget = this.renderer.getRenderTarget();
  18675. if ( renderTarget ) {
  18676. texture.type = renderTarget.texture.type;
  18677. } else {
  18678. texture.type = UnsignedByteType;
  18679. }
  18680. }
  18681. //
  18682. const { width, height, depth } = this.getSize( texture );
  18683. options.width = width;
  18684. options.height = height;
  18685. options.depth = depth;
  18686. options.needsMipmaps = this.needsMipmaps( texture );
  18687. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  18688. //
  18689. if ( isRenderTarget || texture.isStorageTexture === true ) {
  18690. backend.createSampler( texture );
  18691. backend.createTexture( texture, options );
  18692. textureData.generation = texture.version;
  18693. } else {
  18694. const needsCreate = textureData.initialized !== true;
  18695. if ( needsCreate ) backend.createSampler( texture );
  18696. if ( texture.version > 0 ) {
  18697. const image = texture.image;
  18698. if ( image === undefined ) {
  18699. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  18700. } else if ( image.complete === false ) {
  18701. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  18702. } else {
  18703. if ( texture.images ) {
  18704. const images = [];
  18705. for ( const image of texture.images ) {
  18706. images.push( image );
  18707. }
  18708. options.images = images;
  18709. } else {
  18710. options.image = image;
  18711. }
  18712. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  18713. backend.createTexture( texture, options );
  18714. textureData.isDefaultTexture = false;
  18715. textureData.generation = texture.version;
  18716. }
  18717. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  18718. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  18719. }
  18720. } else {
  18721. // async update
  18722. backend.createDefaultTexture( texture );
  18723. textureData.isDefaultTexture = true;
  18724. textureData.generation = texture.version;
  18725. }
  18726. }
  18727. // dispose handler
  18728. if ( textureData.initialized !== true ) {
  18729. textureData.initialized = true;
  18730. textureData.generation = texture.version;
  18731. //
  18732. this.info.memory.textures ++;
  18733. // dispose
  18734. const onDispose = () => {
  18735. texture.removeEventListener( 'dispose', onDispose );
  18736. this._destroyTexture( texture );
  18737. this.info.memory.textures --;
  18738. };
  18739. texture.addEventListener( 'dispose', onDispose );
  18740. }
  18741. //
  18742. textureData.version = texture.version;
  18743. }
  18744. /**
  18745. * Computes the size of the given texture and writes the result
  18746. * into the target vector. This vector is also returned by the
  18747. * method.
  18748. *
  18749. * If no texture data are available for the compute yet, the method
  18750. * returns default size values.
  18751. *
  18752. * @param {Texture} texture - The texture to compute the size for.
  18753. * @param {Vector3} target - The target vector.
  18754. * @return {Vector3} The target vector.
  18755. */
  18756. getSize( texture, target = _size$3 ) {
  18757. let image = texture.images ? texture.images[ 0 ] : texture.image;
  18758. if ( image ) {
  18759. if ( image.image !== undefined ) image = image.image;
  18760. target.width = image.width || 1;
  18761. target.height = image.height || 1;
  18762. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  18763. } else {
  18764. target.width = target.height = target.depth = 1;
  18765. }
  18766. return target;
  18767. }
  18768. /**
  18769. * Computes the number of mipmap levels for the given texture.
  18770. *
  18771. * @param {Texture} texture - The texture.
  18772. * @param {Number} width - The texture's width.
  18773. * @param {Number} height - The texture's height.
  18774. * @return {Number} The number of mipmap levels.
  18775. */
  18776. getMipLevels( texture, width, height ) {
  18777. let mipLevelCount;
  18778. if ( texture.isCompressedTexture ) {
  18779. if ( texture.mipmaps ) {
  18780. mipLevelCount = texture.mipmaps.length;
  18781. } else {
  18782. mipLevelCount = 1;
  18783. }
  18784. } else {
  18785. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  18786. }
  18787. return mipLevelCount;
  18788. }
  18789. /**
  18790. * Returns `true` if the given texture requires mipmaps.
  18791. *
  18792. * @param {Texture} texture - The texture.
  18793. * @return {Boolean} Whether mipmaps are required or not.
  18794. */
  18795. needsMipmaps( texture ) {
  18796. return this.isEnvironmentTexture( texture ) || texture.isCompressedTexture === true || texture.generateMipmaps;
  18797. }
  18798. /**
  18799. * Returns `true` if the given texture is an environment map.
  18800. *
  18801. * @param {Texture} texture - The texture.
  18802. * @return {Boolean} Whether the given texture is an environment map or not.
  18803. */
  18804. isEnvironmentTexture( texture ) {
  18805. const mapping = texture.mapping;
  18806. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  18807. }
  18808. /**
  18809. * Frees internal resource when the given texture isn't
  18810. * required anymore.
  18811. *
  18812. * @param {Texture} texture - The texture to destroy.
  18813. */
  18814. _destroyTexture( texture ) {
  18815. this.backend.destroySampler( texture );
  18816. this.backend.destroyTexture( texture );
  18817. this.delete( texture );
  18818. }
  18819. }
  18820. /**
  18821. * A four-component version of {@link Color} which is internally
  18822. * used by the renderer to represents clear color with alpha as
  18823. * one object.
  18824. *
  18825. * @private
  18826. * @augments Color
  18827. */
  18828. class Color4 extends Color {
  18829. /**
  18830. * Constructs a new four-component color.
  18831. *
  18832. * @param {Number|String} r - The red value.
  18833. * @param {Number} g - The green value.
  18834. * @param {Number} b - The blue value.
  18835. * @param {Number} [a=1] - The alpha value.
  18836. */
  18837. constructor( r, g, b, a = 1 ) {
  18838. super( r, g, b );
  18839. this.a = a;
  18840. }
  18841. /**
  18842. * Overwrites the default to honor alpha.
  18843. *
  18844. * @param {Number|String} r - The red value.
  18845. * @param {Number} g - The green value.
  18846. * @param {Number} b - The blue value.
  18847. * @param {Number} [a=1] - The alpha value.
  18848. * @return {Color4} A reference to this object.
  18849. */
  18850. set( r, g, b, a = 1 ) {
  18851. this.a = a;
  18852. return super.set( r, g, b );
  18853. }
  18854. /**
  18855. * Overwrites the default to honor alpha.
  18856. *
  18857. * @param {Color4} color - The color to copy.
  18858. * @return {Color4} A reference to this object.
  18859. */
  18860. copy( color ) {
  18861. if ( color.a !== undefined ) this.a = color.a;
  18862. return super.copy( color );
  18863. }
  18864. /**
  18865. * Overwrites the default to honor alpha.
  18866. *
  18867. * @return {Color4} The cloned color.
  18868. */
  18869. clone() {
  18870. return new this.constructor( this.r, this.g, this.b, this.a );
  18871. }
  18872. }
  18873. /** @module ParameterNode **/
  18874. /**
  18875. * Special version of {@link PropertyNode} which is used for parameters.
  18876. *
  18877. * @augments PropertyNode
  18878. */
  18879. class ParameterNode extends PropertyNode {
  18880. static get type() {
  18881. return 'ParameterNode';
  18882. }
  18883. /**
  18884. * Constructs a new parameter node.
  18885. *
  18886. * @param {String} nodeType - The type of the node.
  18887. * @param {String?} [name=null] - The name of the parameter in the shader.
  18888. */
  18889. constructor( nodeType, name = null ) {
  18890. super( nodeType, name );
  18891. /**
  18892. * This flag can be used for type testing.
  18893. *
  18894. * @type {Boolean}
  18895. * @readonly
  18896. * @default true
  18897. */
  18898. this.isParameterNode = true;
  18899. }
  18900. getHash() {
  18901. return this.uuid;
  18902. }
  18903. generate() {
  18904. return this.name;
  18905. }
  18906. }
  18907. /**
  18908. * TSL function for creating a parameter node.
  18909. *
  18910. * @function
  18911. * @param {String} type - The type of the node.
  18912. * @param {String?} name - The name of the parameter in the shader.
  18913. * @returns {ParameterNode}
  18914. */
  18915. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  18916. /** @module StackNode **/
  18917. /**
  18918. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  18919. * They are usually needed in cases like `If`, `Else`.
  18920. *
  18921. * @augments Node
  18922. */
  18923. class StackNode extends Node {
  18924. static get type() {
  18925. return 'StackNode';
  18926. }
  18927. /**
  18928. * Constructs a new stack node.
  18929. *
  18930. * @param {StackNode?} [parent=null] - The parent stack node.
  18931. */
  18932. constructor( parent = null ) {
  18933. super();
  18934. /**
  18935. * List of nodes.
  18936. *
  18937. * @type {Array<Node>}
  18938. */
  18939. this.nodes = [];
  18940. /**
  18941. * The output node.
  18942. *
  18943. * @type {Node?}
  18944. * @default null
  18945. */
  18946. this.outputNode = null;
  18947. /**
  18948. * The parent stack node.
  18949. *
  18950. * @type {StackNode}
  18951. * @default null
  18952. */
  18953. this.parent = parent;
  18954. /**
  18955. * The current conditional node.
  18956. *
  18957. * @private
  18958. * @type {ConditionalNode}
  18959. * @default null
  18960. */
  18961. this._currentCond = null;
  18962. /**
  18963. * This flag can be used for type testing.
  18964. *
  18965. * @type {Boolean}
  18966. * @readonly
  18967. * @default true
  18968. */
  18969. this.isStackNode = true;
  18970. }
  18971. getNodeType( builder ) {
  18972. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  18973. }
  18974. /**
  18975. * Adds a node to this stack.
  18976. *
  18977. * @param {Node} node - The node to add.
  18978. * @return {StackNode} A reference to this stack node.
  18979. */
  18980. add( node ) {
  18981. this.nodes.push( node );
  18982. return this;
  18983. }
  18984. /**
  18985. * Represent an `if` statement in TSL.
  18986. *
  18987. * @param {Node} boolNode - Represents the condition.
  18988. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  18989. * @return {StackNode} A reference to this stack node.
  18990. */
  18991. If( boolNode, method ) {
  18992. const methodNode = new ShaderNode( method );
  18993. this._currentCond = select( boolNode, methodNode );
  18994. return this.add( this._currentCond );
  18995. }
  18996. /**
  18997. * Represent an `elseif` statement in TSL.
  18998. *
  18999. * @param {Node} boolNode - Represents the condition.
  19000. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  19001. * @return {StackNode} A reference to this stack node.
  19002. */
  19003. ElseIf( boolNode, method ) {
  19004. const methodNode = new ShaderNode( method );
  19005. const ifNode = select( boolNode, methodNode );
  19006. this._currentCond.elseNode = ifNode;
  19007. this._currentCond = ifNode;
  19008. return this;
  19009. }
  19010. /**
  19011. * Represent an `else` statement in TSL.
  19012. *
  19013. * @param {Function} method - TSL code which is executed in the `else` case.
  19014. * @return {StackNode} A reference to this stack node.
  19015. */
  19016. Else( method ) {
  19017. this._currentCond.elseNode = new ShaderNode( method );
  19018. return this;
  19019. }
  19020. build( builder, ...params ) {
  19021. const previousStack = getCurrentStack();
  19022. setCurrentStack( this );
  19023. for ( const node of this.nodes ) {
  19024. node.build( builder, 'void' );
  19025. }
  19026. setCurrentStack( previousStack );
  19027. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  19028. }
  19029. //
  19030. else( ...params ) { // @deprecated, r168
  19031. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  19032. return this.Else( ...params );
  19033. }
  19034. elseif( ...params ) { // @deprecated, r168
  19035. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  19036. return this.ElseIf( ...params );
  19037. }
  19038. }
  19039. /**
  19040. * TSL function for creating a stack node.
  19041. *
  19042. * @function
  19043. * @param {StackNode?} [parent=null] - The parent stack node.
  19044. * @returns {StackNode}
  19045. */
  19046. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  19047. /** @module OutputStructNode **/
  19048. /**
  19049. * This node can be used to define multiple outputs in a shader programs.
  19050. *
  19051. * @augments Node
  19052. */
  19053. class OutputStructNode extends Node {
  19054. static get type() {
  19055. return 'OutputStructNode';
  19056. }
  19057. /**
  19058. * Constructs a new output struct node. The constructor can be invoked with an
  19059. * arbitrary number of nodes representing the members.
  19060. *
  19061. * @param {...Node} members - A parameter list of nodes.
  19062. */
  19063. constructor( ...members ) {
  19064. super();
  19065. /**
  19066. * An array of nodes which defines the output.
  19067. *
  19068. * @type {Array<Node>}
  19069. */
  19070. this.members = members;
  19071. /**
  19072. * This flag can be used for type testing.
  19073. *
  19074. * @type {Boolean}
  19075. * @readonly
  19076. * @default true
  19077. */
  19078. this.isOutputStructNode = true;
  19079. }
  19080. setup( builder ) {
  19081. super.setup( builder );
  19082. const members = this.members;
  19083. const types = [];
  19084. for ( let i = 0; i < members.length; i ++ ) {
  19085. types.push( members[ i ].getNodeType( builder ) );
  19086. }
  19087. this.nodeType = builder.getStructTypeFromNode( this, types ).name;
  19088. }
  19089. generate( builder, output ) {
  19090. const propertyName = builder.getOutputStructName();
  19091. const members = this.members;
  19092. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  19093. for ( let i = 0; i < members.length; i ++ ) {
  19094. const snippet = members[ i ].build( builder, output );
  19095. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  19096. }
  19097. return propertyName;
  19098. }
  19099. }
  19100. /**
  19101. * TSL function for creating an output struct node.
  19102. *
  19103. * @function
  19104. * @param {...Node} members - A parameter list of nodes.
  19105. * @returns {OutputStructNode}
  19106. */
  19107. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  19108. /** @module MRTNode **/
  19109. /**
  19110. * Returns the MRT texture index for the given name.
  19111. *
  19112. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  19113. * @param {String} name - The name of the MRT texture which index is requested.
  19114. * @return {Number} The texture index.
  19115. */
  19116. function getTextureIndex( textures, name ) {
  19117. for ( let i = 0; i < textures.length; i ++ ) {
  19118. if ( textures[ i ].name === name ) {
  19119. return i;
  19120. }
  19121. }
  19122. return - 1;
  19123. }
  19124. /**
  19125. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  19126. * post-processing is shown below:
  19127. * ```js
  19128. * const mrtNode = mrt( {
  19129. * output: output,
  19130. * normal: normalView
  19131. * } ) );
  19132. * ```
  19133. * The MRT output is defined as a dictionary.
  19134. *
  19135. * @augments OutputStructNode
  19136. */
  19137. class MRTNode extends OutputStructNode {
  19138. static get type() {
  19139. return 'MRTNode';
  19140. }
  19141. /**
  19142. * Constructs a new output struct node.
  19143. *
  19144. * @param {Object<String, Node>} outputNodes - The MRT outputs.
  19145. */
  19146. constructor( outputNodes ) {
  19147. super();
  19148. /**
  19149. * A dictionary representing the MRT outputs. The key
  19150. * is the name of the output, the value the node which produces
  19151. * the output result.
  19152. *
  19153. * @type {Object<String, Node>}
  19154. */
  19155. this.outputNodes = outputNodes;
  19156. /**
  19157. * This flag can be used for type testing.
  19158. *
  19159. * @type {Boolean}
  19160. * @readonly
  19161. * @default true
  19162. */
  19163. this.isMRTNode = true;
  19164. }
  19165. /**
  19166. * Returns `true` if the MRT node has an output with the given name.
  19167. *
  19168. * @param {String} name - The name of the output.
  19169. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  19170. */
  19171. has( name ) {
  19172. return this.outputNodes[ name ] !== undefined;
  19173. }
  19174. /**
  19175. * Returns the output node for the given name.
  19176. *
  19177. * @param {String} name - The name of the output.
  19178. * @return {Node} The output node.
  19179. */
  19180. get( name ) {
  19181. return this.outputNodes[ name ];
  19182. }
  19183. /**
  19184. * Merges the outputs of the given MRT node with the outputs of this node.
  19185. *
  19186. * @param {MRTNode} mrtNode - The MRT to merge.
  19187. * @return {MRTNode} A new MRT node with merged outputs..
  19188. */
  19189. merge( mrtNode ) {
  19190. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  19191. return mrt( outputs );
  19192. }
  19193. setup( builder ) {
  19194. const outputNodes = this.outputNodes;
  19195. const mrt = builder.renderer.getRenderTarget();
  19196. const members = [];
  19197. const textures = mrt.textures;
  19198. for ( const name in outputNodes ) {
  19199. const index = getTextureIndex( textures, name );
  19200. members[ index ] = vec4( outputNodes[ name ] );
  19201. }
  19202. this.members = members;
  19203. return super.setup( builder );
  19204. }
  19205. }
  19206. /**
  19207. * TSL function for creating a MRT node.
  19208. *
  19209. * @function
  19210. * @param {Object<String, Node>} outputNodes - The MRT outputs.
  19211. * @returns {MRTNode}
  19212. */
  19213. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  19214. /** @module Hash **/
  19215. /**
  19216. * Generates a hash value in the range `[0, 1]` from the given seed.
  19217. *
  19218. * @method
  19219. * @param {Node<float>} seed - The seed.
  19220. * @return {Node<float>} The hash value.
  19221. */
  19222. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  19223. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  19224. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  19225. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  19226. const result = word.shiftRight( 22 ).bitXor( word );
  19227. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  19228. } );
  19229. /** @module MathUtils **/
  19230. /**
  19231. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  19232. * The corners are mapped to `0` and the center to `1`.
  19233. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19234. *
  19235. * @method
  19236. * @param {Node<float>} x - The value to remap.
  19237. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  19238. * @return {Node<float>} The remapped value.
  19239. */
  19240. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  19241. /**
  19242. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  19243. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  19244. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19245. *
  19246. * @method
  19247. * @param {Node<float>} x - The value to remap.
  19248. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  19249. * @return {Node<float>} The remapped value.
  19250. */
  19251. 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 ) );
  19252. /**
  19253. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  19254. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  19255. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19256. *
  19257. * @method
  19258. * @param {Node<float>} x - The value to remap.
  19259. * @param {Node<float>} a - First control parameter.
  19260. * @param {Node<float>} b - Second control parameter.
  19261. * @return {Node<float>} The remapped value.
  19262. */
  19263. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  19264. /**
  19265. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  19266. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19267. *
  19268. * @method
  19269. * @param {Node<float>} x - The value to compute the sin for.
  19270. * @param {Node<float>} k - Controls the amount of bounces.
  19271. * @return {Node<float>} The result value.
  19272. */
  19273. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  19274. // https://github.com/cabbibo/glsl-tri-noise-3d
  19275. /** @module TriNoise3D **/
  19276. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  19277. return x.fract().sub( .5 ).abs();
  19278. } ).setLayout( {
  19279. name: 'tri',
  19280. type: 'float',
  19281. inputs: [
  19282. { name: 'x', type: 'float' }
  19283. ]
  19284. } );
  19285. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  19286. 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. ) ) ) ) );
  19287. } ).setLayout( {
  19288. name: 'tri3',
  19289. type: 'vec3',
  19290. inputs: [
  19291. { name: 'p', type: 'vec3' }
  19292. ]
  19293. } );
  19294. /**
  19295. * Generates a noise value from the given position, speed and time parameters.
  19296. *
  19297. * @method
  19298. * @param {Node<vec3>} position - The position.
  19299. * @param {Node<float>} speed - The speed.
  19300. * @param {Node<float>} time - The time.
  19301. * @return {Node<float>} The generated noise.
  19302. */
  19303. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  19304. const p = vec3( position ).toVar();
  19305. const z = float( 1.4 ).toVar();
  19306. const rz = float( 0.0 ).toVar();
  19307. const bp = vec3( p ).toVar();
  19308. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  19309. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  19310. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  19311. bp.mulAssign( 1.8 );
  19312. z.mulAssign( 1.5 );
  19313. p.mulAssign( 1.2 );
  19314. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  19315. rz.addAssign( t.div( z ) );
  19316. bp.addAssign( 0.14 );
  19317. } );
  19318. return rz;
  19319. } ).setLayout( {
  19320. name: 'triNoise3D',
  19321. type: 'float',
  19322. inputs: [
  19323. { name: 'position', type: 'vec3' },
  19324. { name: 'speed', type: 'float' },
  19325. { name: 'time', type: 'float' }
  19326. ]
  19327. } );
  19328. /** @module FunctionOverloadingNode **/
  19329. /**
  19330. * This class allows to define multiple overloaded versions
  19331. * of the same function. Depending on the parameters of the function
  19332. * call, the node picks the best-fit overloaded version.
  19333. *
  19334. * @augments Node
  19335. */
  19336. class FunctionOverloadingNode extends Node {
  19337. static get type() {
  19338. return 'FunctionOverloadingNode';
  19339. }
  19340. /**
  19341. * Constructs a new function overloading node.
  19342. *
  19343. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  19344. * @param {...Node} parametersNodes - A list of parameter nodes.
  19345. */
  19346. constructor( functionNodes = [], ...parametersNodes ) {
  19347. super();
  19348. /**
  19349. * Array of `Fn` function definitions.
  19350. *
  19351. * @type {Array<Function>}
  19352. */
  19353. this.functionNodes = functionNodes;
  19354. /**
  19355. * A list of parameter nodes.
  19356. *
  19357. * @type {Array<Node>}
  19358. */
  19359. this.parametersNodes = parametersNodes;
  19360. /**
  19361. * The selected overloaded function call.
  19362. *
  19363. * @private
  19364. * @type {ShaderCallNodeInternal}
  19365. */
  19366. this._candidateFnCall = null;
  19367. /**
  19368. * This node is marked as global.
  19369. *
  19370. * @type {Boolean}
  19371. * @default true
  19372. */
  19373. this.global = true;
  19374. }
  19375. /**
  19376. * This method is overwritten since the node type is inferred from
  19377. * the function's return type.
  19378. *
  19379. * @param {NodeBuilder} builder - The current node builder.
  19380. * @return {String} The node type.
  19381. */
  19382. getNodeType() {
  19383. return this.functionNodes[ 0 ].shaderNode.layout.type;
  19384. }
  19385. setup( builder ) {
  19386. const params = this.parametersNodes;
  19387. let candidateFnCall = this._candidateFnCall;
  19388. if ( candidateFnCall === null ) {
  19389. let candidateFn = null;
  19390. let candidateScore = - 1;
  19391. for ( const functionNode of this.functionNodes ) {
  19392. const shaderNode = functionNode.shaderNode;
  19393. const layout = shaderNode.layout;
  19394. if ( layout === null ) {
  19395. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  19396. }
  19397. const inputs = layout.inputs;
  19398. if ( params.length === inputs.length ) {
  19399. let score = 0;
  19400. for ( let i = 0; i < params.length; i ++ ) {
  19401. const param = params[ i ];
  19402. const input = inputs[ i ];
  19403. if ( param.getNodeType( builder ) === input.type ) {
  19404. score ++;
  19405. } else {
  19406. score = 0;
  19407. }
  19408. }
  19409. if ( score > candidateScore ) {
  19410. candidateFn = functionNode;
  19411. candidateScore = score;
  19412. }
  19413. }
  19414. }
  19415. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  19416. }
  19417. return candidateFnCall;
  19418. }
  19419. }
  19420. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  19421. /**
  19422. * TSL function for creating a function overloading node.
  19423. *
  19424. * @function
  19425. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  19426. * @returns {FunctionOverloadingNode}
  19427. */
  19428. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  19429. /** @module Timer **/
  19430. /**
  19431. * Represents the elapsed time in seconds.
  19432. *
  19433. * @type {UniformNode<float>}
  19434. */
  19435. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  19436. /**
  19437. * Represents the delta time in seconds.
  19438. *
  19439. * @type {UniformNode<float>}
  19440. */
  19441. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  19442. /**
  19443. * Represents the current frame ID.
  19444. *
  19445. * @type {UniformNode<uint>}
  19446. */
  19447. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  19448. // Deprecated
  19449. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  19450. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  19451. return time.mul( timeScale );
  19452. };
  19453. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  19454. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  19455. return time.mul( timeScale );
  19456. };
  19457. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  19458. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  19459. return deltaTime.mul( timeScale );
  19460. };
  19461. /** @module Oscillators **/
  19462. /**
  19463. * Generates a sine 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 oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  19470. /**
  19471. * Generates a square 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 oscSquare = ( t = time ) => t.fract().round();
  19478. /**
  19479. * Generates a triangle wave oscillation based on a timer.
  19480. *
  19481. * @method
  19482. * @param {Node<float>} t - The timer to generate the oscillation with.
  19483. * @return {Node<float>} The oscillation node.
  19484. */
  19485. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  19486. /**
  19487. * Generates a sawtooth wave oscillation based on a timer.
  19488. *
  19489. * @method
  19490. * @param {Node<float>} t - The timer to generate the oscillation with.
  19491. * @return {Node<float>} The oscillation node.
  19492. */
  19493. const oscSawtooth = ( t = time ) => t.fract();
  19494. /** @module UVUtils **/
  19495. /**
  19496. * Rotates the given uv coordinates around a center point
  19497. *
  19498. * @method
  19499. * @param {Node<vec2>} uv - The uv coordinates.
  19500. * @param {Node<float>} rotation - The rotation defined in radians.
  19501. * @param {Node<vec2>} center - The center of rotation
  19502. * @return {Node<vec2>} The rotated uv coordinates.
  19503. */
  19504. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  19505. return rotate( uv.sub( center ), rotation ).add( center );
  19506. } );
  19507. /**
  19508. * Applies a spherical warping effect to the given uv coordinates.
  19509. *
  19510. * @method
  19511. * @param {Node<vec2>} uv - The uv coordinates.
  19512. * @param {Node<float>} strength - The strength of the effect.
  19513. * @param {Node<vec2>} center - The center point
  19514. * @return {Node<vec2>} The updated uv coordinates.
  19515. */
  19516. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  19517. const delta = uv.sub( center );
  19518. const delta2 = delta.dot( delta );
  19519. const delta4 = delta2.mul( delta2 );
  19520. const deltaOffset = delta4.mul( strength );
  19521. return uv.add( delta.mul( deltaOffset ) );
  19522. } );
  19523. /** @module SpriteUtils **/
  19524. /**
  19525. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  19526. * oriented always towards the camera.
  19527. *
  19528. * ```js
  19529. * material.vertexNode = billboarding();
  19530. * ```
  19531. *
  19532. * @method
  19533. * @param {Object} config - The configuration object.
  19534. * @param {Node<vec3>?} [config.position=null] - Can be used to define the vertex positions in world space.
  19535. * @param {Boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  19536. * @param {Boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  19537. * @return {Node<vec3>} The updated vertex position in clip space.
  19538. */
  19539. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  19540. let worldMatrix;
  19541. if ( position !== null ) {
  19542. worldMatrix = modelWorldMatrix.toVar();
  19543. worldMatrix[ 3 ][ 0 ] = position.x;
  19544. worldMatrix[ 3 ][ 1 ] = position.y;
  19545. worldMatrix[ 3 ][ 2 ] = position.z;
  19546. } else {
  19547. worldMatrix = modelWorldMatrix;
  19548. }
  19549. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  19550. if ( defined( horizontal ) ) {
  19551. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  19552. modelViewMatrix[ 0 ][ 1 ] = 0;
  19553. modelViewMatrix[ 0 ][ 2 ] = 0;
  19554. }
  19555. if ( defined( vertical ) ) {
  19556. modelViewMatrix[ 1 ][ 0 ] = 0;
  19557. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  19558. modelViewMatrix[ 1 ][ 2 ] = 0;
  19559. }
  19560. modelViewMatrix[ 2 ][ 0 ] = 0;
  19561. modelViewMatrix[ 2 ][ 1 ] = 0;
  19562. modelViewMatrix[ 2 ][ 2 ] = 1;
  19563. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  19564. } );
  19565. /** @module ViewportUtils **/
  19566. /**
  19567. * A special version of a screen uv function that involves a depth comparison
  19568. * when computing the final uvs. The function mitigates visual errors when
  19569. * using viewport texture nodes for refraction purposes. Without this function
  19570. * objects in front of a refractive surface might appear on the refractive surface
  19571. * which is incorrect.
  19572. *
  19573. * @method
  19574. * @param {Node<vec2>?} uv - Optional uv coordinates. By default `screenUV` is used.
  19575. * @return {Node<vec2>} The update uv coordinates.
  19576. */
  19577. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  19578. const depth = linearDepth();
  19579. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  19580. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  19581. return finalUV;
  19582. } );
  19583. /** @module SpriteSheetUVNode **/
  19584. /**
  19585. * Can be used to compute texture coordinates for animated sprite sheets.
  19586. *
  19587. * ```js
  19588. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  19589. *
  19590. * material.colorNode = texture( spriteSheet, uvNode );
  19591. * ```
  19592. *
  19593. * @augments Node
  19594. */
  19595. class SpriteSheetUVNode extends Node {
  19596. static get type() {
  19597. return 'SpriteSheetUVNode';
  19598. }
  19599. /**
  19600. * Constructs a new sprite sheet uv node.
  19601. *
  19602. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  19603. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  19604. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  19605. */
  19606. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  19607. super( 'vec2' );
  19608. /**
  19609. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  19610. *
  19611. * @type {Node<vec2>}
  19612. */
  19613. this.countNode = countNode;
  19614. /**
  19615. * The uv node.
  19616. *
  19617. * @type {Node<vec2>}
  19618. */
  19619. this.uvNode = uvNode;
  19620. /**
  19621. * The node that defines the current frame/sprite.
  19622. *
  19623. * @type {Node<float>}
  19624. */
  19625. this.frameNode = frameNode;
  19626. }
  19627. setup() {
  19628. const { frameNode, uvNode, countNode } = this;
  19629. const { width, height } = countNode;
  19630. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  19631. const column = frameNum.mod( width );
  19632. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  19633. const scale = countNode.reciprocal();
  19634. const uvFrameOffset = vec2( column, row );
  19635. return uvNode.add( uvFrameOffset ).mul( scale );
  19636. }
  19637. }
  19638. /**
  19639. * TSL function for creating a sprite sheet uv node.
  19640. *
  19641. * @function
  19642. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  19643. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  19644. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  19645. * @returns {SpriteSheetUVNode}
  19646. */
  19647. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  19648. /** @module TriplanarTexturesNode **/
  19649. /**
  19650. * Can be used for triplanar texture mapping.
  19651. *
  19652. * ```js
  19653. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  19654. * ```
  19655. *
  19656. * @augments Node
  19657. */
  19658. class TriplanarTexturesNode extends Node {
  19659. static get type() {
  19660. return 'TriplanarTexturesNode';
  19661. }
  19662. /**
  19663. * Constructs a new triplanar textures node.
  19664. *
  19665. * @param {Node} textureXNode - First texture node.
  19666. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19667. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19668. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  19669. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  19670. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  19671. */
  19672. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  19673. super( 'vec4' );
  19674. /**
  19675. * First texture node.
  19676. *
  19677. * @type {Node}
  19678. */
  19679. this.textureXNode = textureXNode;
  19680. /**
  19681. * Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19682. *
  19683. * @type {Node}
  19684. * @default null
  19685. */
  19686. this.textureYNode = textureYNode;
  19687. /**
  19688. * Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19689. *
  19690. * @type {Node}
  19691. * @default null
  19692. */
  19693. this.textureZNode = textureZNode;
  19694. /**
  19695. * The scale node.
  19696. *
  19697. * @type {Node<float>}
  19698. * @default float(1)
  19699. */
  19700. this.scaleNode = scaleNode;
  19701. /**
  19702. * Vertex positions in local space.
  19703. *
  19704. * @type {Node<vec3>}
  19705. * @default positionLocal
  19706. */
  19707. this.positionNode = positionNode;
  19708. /**
  19709. * Normals in local space.
  19710. *
  19711. * @type {Node<vec3>}
  19712. * @default normalLocal
  19713. */
  19714. this.normalNode = normalNode;
  19715. }
  19716. setup() {
  19717. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  19718. // Ref: https://github.com/keijiro/StandardTriplanar
  19719. // Blending factor of triplanar mapping
  19720. let bf = normalNode.abs().normalize();
  19721. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  19722. // Triplanar mapping
  19723. const tx = positionNode.yz.mul( scaleNode );
  19724. const ty = positionNode.zx.mul( scaleNode );
  19725. const tz = positionNode.xy.mul( scaleNode );
  19726. // Base color
  19727. const textureX = textureXNode.value;
  19728. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  19729. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  19730. const cx = texture( textureX, tx ).mul( bf.x );
  19731. const cy = texture( textureY, ty ).mul( bf.y );
  19732. const cz = texture( textureZ, tz ).mul( bf.z );
  19733. return add( cx, cy, cz );
  19734. }
  19735. }
  19736. /**
  19737. * TSL function for creating a triplanar textures node.
  19738. *
  19739. * @function
  19740. * @param {Node} textureXNode - First texture node.
  19741. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19742. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19743. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  19744. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  19745. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  19746. * @returns {TriplanarTexturesNode}
  19747. */
  19748. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  19749. /**
  19750. * TSL function for creating a triplanar textures node.
  19751. *
  19752. * @function
  19753. * @param {Node} textureXNode - First texture node.
  19754. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19755. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19756. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  19757. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  19758. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  19759. * @returns {TriplanarTexturesNode}
  19760. */
  19761. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  19762. /** @module ReflectorNode **/
  19763. const _reflectorPlane = new Plane();
  19764. const _normal = new Vector3();
  19765. const _reflectorWorldPosition = new Vector3();
  19766. const _cameraWorldPosition = new Vector3();
  19767. const _rotationMatrix = new Matrix4();
  19768. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  19769. const clipPlane = new Vector4();
  19770. const _view = new Vector3();
  19771. const _target = new Vector3();
  19772. const _q = new Vector4();
  19773. const _size$2 = new Vector2();
  19774. const _defaultRT = new RenderTarget();
  19775. const _defaultUV = screenUV.flipX();
  19776. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  19777. let _inReflector = false;
  19778. /**
  19779. * This node can be used to implement mirror-like flat reflective surfaces.
  19780. *
  19781. * ```js
  19782. * const groundReflector = reflector();
  19783. * material.colorNode = groundReflector;
  19784. *
  19785. * const plane = new Mesh( geometry, material );
  19786. * plane.add( groundReflector.target );
  19787. * ```
  19788. *
  19789. * @augments module:TextureNode~TextureNode
  19790. */
  19791. class ReflectorNode extends TextureNode {
  19792. static get type() {
  19793. return 'ReflectorNode';
  19794. }
  19795. /**
  19796. * Constructs a new reflector node.
  19797. *
  19798. * @param {Object} [parameters={}] - An object holding configuration parameters.
  19799. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  19800. * @param {Number} [parameters.resolution=1] - The resolution scale.
  19801. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  19802. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  19803. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  19804. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  19805. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  19806. */
  19807. constructor( parameters = {} ) {
  19808. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  19809. /**
  19810. * A reference to the internal reflector base node which holds the actual implementation.
  19811. *
  19812. * @private
  19813. * @type {ReflectorBaseNode?}
  19814. * @default null
  19815. */
  19816. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  19817. /**
  19818. * A reference to the internal depth node.
  19819. *
  19820. * @private
  19821. * @type {Node?}
  19822. * @default null
  19823. */
  19824. this._depthNode = null;
  19825. this.setUpdateMatrix( false );
  19826. }
  19827. /**
  19828. * A reference to the internal reflector node.
  19829. *
  19830. * @type {ReflectorBaseNode}
  19831. */
  19832. get reflector() {
  19833. return this._reflectorBaseNode;
  19834. }
  19835. /**
  19836. * A reference to 3D object the reflector is linked to.
  19837. *
  19838. * @type {Object3D}
  19839. */
  19840. get target() {
  19841. return this._reflectorBaseNode.target;
  19842. }
  19843. /**
  19844. * Returns a node representing the mirror's depth. That can be used
  19845. * to implement more advanced reflection effects like distance attenuation.
  19846. *
  19847. * @return {Node} The depth node.
  19848. */
  19849. getDepthNode() {
  19850. if ( this._depthNode === null ) {
  19851. if ( this._reflectorBaseNode.depth !== true ) {
  19852. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  19853. }
  19854. this._depthNode = nodeObject( new ReflectorNode( {
  19855. defaultTexture: _defaultRT.depthTexture,
  19856. reflector: this._reflectorBaseNode
  19857. } ) );
  19858. }
  19859. return this._depthNode;
  19860. }
  19861. setup( builder ) {
  19862. // ignore if used in post-processing
  19863. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  19864. return super.setup( builder );
  19865. }
  19866. clone() {
  19867. const texture = new this.constructor( this.reflectorNode );
  19868. texture._reflectorBaseNode = this._reflectorBaseNode;
  19869. return texture;
  19870. }
  19871. }
  19872. /**
  19873. * Holds the actual implementation of the reflector.
  19874. *
  19875. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  19876. * in `ReflectorNode`, see #29619.
  19877. *
  19878. * @private
  19879. * @augments Node
  19880. */
  19881. class ReflectorBaseNode extends Node {
  19882. static get type() {
  19883. return 'ReflectorBaseNode';
  19884. }
  19885. /**
  19886. * Constructs a new reflector base node.
  19887. *
  19888. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  19889. * @param {Object} [parameters={}] - An object holding configuration parameters.
  19890. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  19891. * @param {Number} [parameters.resolution=1] - The resolution scale.
  19892. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  19893. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  19894. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  19895. */
  19896. constructor( textureNode, parameters = {} ) {
  19897. super();
  19898. const {
  19899. target = new Object3D(),
  19900. resolution = 1,
  19901. generateMipmaps = false,
  19902. bounces = true,
  19903. depth = false
  19904. } = parameters;
  19905. /**
  19906. * Represents the rendered reflections as a texture node.
  19907. *
  19908. * @type {TextureNode}
  19909. */
  19910. this.textureNode = textureNode;
  19911. /**
  19912. * The 3D object the reflector is linked to.
  19913. *
  19914. * @type {Object3D}
  19915. * @default {new Object3D()}
  19916. */
  19917. this.target = target;
  19918. /**
  19919. * The resolution scale.
  19920. *
  19921. * @type {Number}
  19922. * @default {1}
  19923. */
  19924. this.resolution = resolution;
  19925. /**
  19926. * Whether mipmaps should be generated or not.
  19927. *
  19928. * @type {Boolean}
  19929. * @default {false}
  19930. */
  19931. this.generateMipmaps = generateMipmaps;
  19932. /**
  19933. * Whether reflectors can render other reflector nodes or not.
  19934. *
  19935. * @type {Boolean}
  19936. * @default {true}
  19937. */
  19938. this.bounces = bounces;
  19939. /**
  19940. * Whether depth data should be generated or not.
  19941. *
  19942. * @type {Boolean}
  19943. * @default {false}
  19944. */
  19945. this.depth = depth;
  19946. /**
  19947. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  19948. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  19949. *
  19950. * @type {String}
  19951. * @default 'render'
  19952. */
  19953. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  19954. /**
  19955. * Weak map for managing virtual cameras.
  19956. *
  19957. * @type {WeakMap<Camera, Camera>}
  19958. */
  19959. this.virtualCameras = new WeakMap();
  19960. /**
  19961. * Weak map for managing render targets.
  19962. *
  19963. * @type {WeakMap<Camera, RenderTarget>}
  19964. */
  19965. this.renderTargets = new WeakMap();
  19966. }
  19967. /**
  19968. * Updates the resolution of the internal render target.
  19969. *
  19970. * @private
  19971. * @param {RenderTarget} renderTarget - The render target to resize.
  19972. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  19973. */
  19974. _updateResolution( renderTarget, renderer ) {
  19975. const resolution = this.resolution;
  19976. renderer.getDrawingBufferSize( _size$2 );
  19977. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  19978. }
  19979. setup( builder ) {
  19980. this._updateResolution( _defaultRT, builder.renderer );
  19981. return super.setup( builder );
  19982. }
  19983. /**
  19984. * Returns a virtual camera for the given camera. The virtual camera is used to
  19985. * render the scene from the reflector's view so correct reflections can be produced.
  19986. *
  19987. * @param {Camera} camera - The scene's camera.
  19988. * @return {Camera} The corresponding virtual camera.
  19989. */
  19990. getVirtualCamera( camera ) {
  19991. let virtualCamera = this.virtualCameras.get( camera );
  19992. if ( virtualCamera === undefined ) {
  19993. virtualCamera = camera.clone();
  19994. this.virtualCameras.set( camera, virtualCamera );
  19995. }
  19996. return virtualCamera;
  19997. }
  19998. /**
  19999. * Returns a render target for the given camera. The reflections are rendered
  20000. * into this render target.
  20001. *
  20002. * @param {Camera} camera - The scene's camera.
  20003. * @return {RenderTarget} The render target.
  20004. */
  20005. getRenderTarget( camera ) {
  20006. let renderTarget = this.renderTargets.get( camera );
  20007. if ( renderTarget === undefined ) {
  20008. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  20009. if ( this.generateMipmaps === true ) {
  20010. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  20011. renderTarget.texture.generateMipmaps = true;
  20012. }
  20013. if ( this.depth === true ) {
  20014. renderTarget.depthTexture = new DepthTexture();
  20015. }
  20016. this.renderTargets.set( camera, renderTarget );
  20017. }
  20018. return renderTarget;
  20019. }
  20020. updateBefore( frame ) {
  20021. if ( this.bounces === false && _inReflector ) return false;
  20022. _inReflector = true;
  20023. const { scene, camera, renderer, material } = frame;
  20024. const { target } = this;
  20025. const virtualCamera = this.getVirtualCamera( camera );
  20026. const renderTarget = this.getRenderTarget( virtualCamera );
  20027. renderer.getDrawingBufferSize( _size$2 );
  20028. this._updateResolution( renderTarget, renderer );
  20029. //
  20030. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  20031. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  20032. _rotationMatrix.extractRotation( target.matrixWorld );
  20033. _normal.set( 0, 0, 1 );
  20034. _normal.applyMatrix4( _rotationMatrix );
  20035. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  20036. // Avoid rendering when reflector is facing away
  20037. if ( _view.dot( _normal ) > 0 ) return;
  20038. _view.reflect( _normal ).negate();
  20039. _view.add( _reflectorWorldPosition );
  20040. _rotationMatrix.extractRotation( camera.matrixWorld );
  20041. _lookAtPosition.set( 0, 0, - 1 );
  20042. _lookAtPosition.applyMatrix4( _rotationMatrix );
  20043. _lookAtPosition.add( _cameraWorldPosition );
  20044. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  20045. _target.reflect( _normal ).negate();
  20046. _target.add( _reflectorWorldPosition );
  20047. //
  20048. virtualCamera.coordinateSystem = camera.coordinateSystem;
  20049. virtualCamera.position.copy( _view );
  20050. virtualCamera.up.set( 0, 1, 0 );
  20051. virtualCamera.up.applyMatrix4( _rotationMatrix );
  20052. virtualCamera.up.reflect( _normal );
  20053. virtualCamera.lookAt( _target );
  20054. virtualCamera.near = camera.near;
  20055. virtualCamera.far = camera.far;
  20056. virtualCamera.updateMatrixWorld();
  20057. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  20058. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  20059. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  20060. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  20061. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  20062. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  20063. const projectionMatrix = virtualCamera.projectionMatrix;
  20064. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  20065. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  20066. _q.z = - 1.0;
  20067. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  20068. // Calculate the scaled plane vector
  20069. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  20070. const clipBias = 0;
  20071. // Replacing the third row of the projection matrix
  20072. projectionMatrix.elements[ 2 ] = clipPlane.x;
  20073. projectionMatrix.elements[ 6 ] = clipPlane.y;
  20074. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  20075. projectionMatrix.elements[ 14 ] = clipPlane.w;
  20076. //
  20077. this.textureNode.value = renderTarget.texture;
  20078. if ( this.depth === true ) {
  20079. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  20080. }
  20081. material.visible = false;
  20082. const currentRenderTarget = renderer.getRenderTarget();
  20083. const currentMRT = renderer.getMRT();
  20084. const currentAutoClear = renderer.autoClear;
  20085. renderer.setMRT( null );
  20086. renderer.setRenderTarget( renderTarget );
  20087. renderer.autoClear = true;
  20088. renderer.render( scene, virtualCamera );
  20089. renderer.setMRT( currentMRT );
  20090. renderer.setRenderTarget( currentRenderTarget );
  20091. renderer.autoClear = currentAutoClear;
  20092. material.visible = true;
  20093. _inReflector = false;
  20094. }
  20095. }
  20096. /**
  20097. * TSL function for creating a reflector node.
  20098. *
  20099. * @function
  20100. * @param {Object} [parameters={}] - An object holding configuration parameters.
  20101. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  20102. * @param {Number} [parameters.resolution=1] - The resolution scale.
  20103. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  20104. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  20105. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  20106. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  20107. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  20108. * @returns {ReflectorNode}
  20109. */
  20110. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  20111. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  20112. /**
  20113. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  20114. *
  20115. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  20116. *
  20117. * @private
  20118. * @augments BufferGeometry
  20119. */
  20120. class QuadGeometry extends BufferGeometry {
  20121. /**
  20122. * Constructs a new quad geometry.
  20123. *
  20124. * @param {Boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  20125. */
  20126. constructor( flipY = false ) {
  20127. super();
  20128. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  20129. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  20130. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  20131. }
  20132. }
  20133. const _geometry = /*@__PURE__*/ new QuadGeometry();
  20134. /**
  20135. * This module is a helper for passes which need to render a full
  20136. * screen effect which is quite common in context of post processing.
  20137. *
  20138. * The intended usage is to reuse a single quad mesh for rendering
  20139. * subsequent passes by just reassigning the `material` reference.
  20140. *
  20141. * @augments BufferGeometry
  20142. */
  20143. class QuadMesh extends Mesh {
  20144. /**
  20145. * Constructs a new quad mesh.
  20146. *
  20147. * @param {Material?} [material=null] - The material to render the quad mesh with.
  20148. */
  20149. constructor( material = null ) {
  20150. super( _geometry, material );
  20151. /**
  20152. * The camera to render the quad mesh with.
  20153. *
  20154. * @type {OrthographicCamera}
  20155. * @readonly
  20156. */
  20157. this.camera = _camera;
  20158. /**
  20159. * This flag can be used for type testing.
  20160. *
  20161. * @type {Boolean}
  20162. * @readonly
  20163. * @default true
  20164. */
  20165. this.isQuadMesh = true;
  20166. }
  20167. /**
  20168. * Async version of `render()`.
  20169. *
  20170. * @async
  20171. * @param {Renderer} renderer - The renderer.
  20172. * @return {Promise} A Promise that resolves when the render has been finished.
  20173. */
  20174. async renderAsync( renderer ) {
  20175. return renderer.renderAsync( this, _camera );
  20176. }
  20177. /**
  20178. * Renders the quad mesh
  20179. *
  20180. * @param {Renderer} renderer - The renderer.
  20181. */
  20182. render( renderer ) {
  20183. renderer.render( this, _camera );
  20184. }
  20185. }
  20186. /** @module RTTNode **/
  20187. const _size$1 = /*@__PURE__*/ new Vector2();
  20188. /**
  20189. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  20190. * This module is especially relevant in context of post processing where certain nodes require
  20191. * texture input for their effects. With the helper function `convertToTexture()` which is based
  20192. * on this module, the node system can automatically ensure texture input if required.
  20193. *
  20194. * @augments module:TextureNode~TextureNode
  20195. */
  20196. class RTTNode extends TextureNode {
  20197. static get type() {
  20198. return 'RTTNode';
  20199. }
  20200. /**
  20201. * Constructs a new RTT node.
  20202. *
  20203. * @param {Node} node - The node to render a texture with.
  20204. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  20205. * @param {Number?} [height=null] - The height of the internal render target.
  20206. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  20207. */
  20208. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  20209. const renderTarget = new RenderTarget( width, height, options );
  20210. super( renderTarget.texture, uv() );
  20211. /**
  20212. * The node to render a texture with.
  20213. *
  20214. * @type {Node}
  20215. */
  20216. this.node = node;
  20217. /**
  20218. * The width of the internal render target.
  20219. * If not width is applied, the render target is automatically resized.
  20220. *
  20221. * @type {Number?}
  20222. * @default null
  20223. */
  20224. this.width = width;
  20225. /**
  20226. * The height of the internal render target.
  20227. *
  20228. * @type {Number?}
  20229. * @default null
  20230. */
  20231. this.height = height;
  20232. /**
  20233. * The pixel ratio
  20234. *
  20235. * @type {Number}
  20236. * @default 1
  20237. */
  20238. this.pixelRatio = 1;
  20239. /**
  20240. * The render target
  20241. *
  20242. * @type {RenderTarget}
  20243. */
  20244. this.renderTarget = renderTarget;
  20245. /**
  20246. * Whether the texture requires an update or not.
  20247. *
  20248. * @type {Boolean}
  20249. * @default true
  20250. */
  20251. this.textureNeedsUpdate = true;
  20252. /**
  20253. * Whether the texture should automatically be updated or not.
  20254. *
  20255. * @type {Boolean}
  20256. * @default true
  20257. */
  20258. this.autoUpdate = true;
  20259. /**
  20260. * The node which is used with the quad mesh for RTT.
  20261. *
  20262. * @private
  20263. * @type {Node}
  20264. * @default null
  20265. */
  20266. this._rttNode = null;
  20267. /**
  20268. * The internal quad mesh for RTT.
  20269. *
  20270. * @private
  20271. * @type {QuadMesh}
  20272. */
  20273. this._quadMesh = new QuadMesh( new NodeMaterial() );
  20274. /**
  20275. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  20276. * the texture once per render in its {@link RTTNode#updateBefore} method.
  20277. *
  20278. * @type {String}
  20279. * @default 'render'
  20280. */
  20281. this.updateBeforeType = NodeUpdateType.RENDER;
  20282. }
  20283. /**
  20284. * Whether the internal render target should automatically be resized or not.
  20285. *
  20286. * @type {Boolean}
  20287. * @readonly
  20288. * @default true
  20289. */
  20290. get autoSize() {
  20291. return this.width === null;
  20292. }
  20293. setup( builder ) {
  20294. this._rttNode = this.node.context( builder.getSharedContext() );
  20295. this._quadMesh.material.name = 'RTT';
  20296. this._quadMesh.material.needsUpdate = true;
  20297. return super.setup( builder );
  20298. }
  20299. /**
  20300. * Sets the size of the internal render target
  20301. *
  20302. * @param {Number} width - The width to set.
  20303. * @param {Number} height - The width to set.
  20304. */
  20305. setSize( width, height ) {
  20306. this.width = width;
  20307. this.height = height;
  20308. const effectiveWidth = width * this.pixelRatio;
  20309. const effectiveHeight = height * this.pixelRatio;
  20310. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  20311. this.textureNeedsUpdate = true;
  20312. }
  20313. /**
  20314. * Sets the pixel ratio. This will also resize the render target.
  20315. *
  20316. * @param {Number} pixelRatio - The pixel ratio to set.
  20317. */
  20318. setPixelRatio( pixelRatio ) {
  20319. this.pixelRatio = pixelRatio;
  20320. this.setSize( this.width, this.height );
  20321. }
  20322. updateBefore( { renderer } ) {
  20323. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  20324. this.textureNeedsUpdate = false;
  20325. //
  20326. if ( this.autoSize === true ) {
  20327. this.pixelRatio = renderer.getPixelRatio();
  20328. const size = renderer.getSize( _size$1 );
  20329. this.setSize( size.width, size.height );
  20330. }
  20331. //
  20332. this._quadMesh.material.fragmentNode = this._rttNode;
  20333. //
  20334. const currentRenderTarget = renderer.getRenderTarget();
  20335. renderer.setRenderTarget( this.renderTarget );
  20336. this._quadMesh.render( renderer );
  20337. renderer.setRenderTarget( currentRenderTarget );
  20338. }
  20339. clone() {
  20340. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  20341. newNode.sampler = this.sampler;
  20342. newNode.referenceNode = this;
  20343. return newNode;
  20344. }
  20345. }
  20346. /**
  20347. * TSL function for creating a RTT node.
  20348. *
  20349. * @function
  20350. * @param {Node} node - The node to render a texture with.
  20351. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  20352. * @param {Number?} [height=null] - The height of the internal render target.
  20353. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  20354. * @returns {RTTNode}
  20355. */
  20356. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  20357. /**
  20358. * TSL function for converting nodes to textures nodes.
  20359. *
  20360. * @function
  20361. * @param {Node} node - The node to render a texture with.
  20362. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  20363. * @param {Number?} [height=null] - The height of the internal render target.
  20364. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  20365. * @returns {RTTNode}
  20366. */
  20367. const convertToTexture = ( node, ...params ) => {
  20368. if ( node.isTextureNode ) return node;
  20369. if ( node.isPassNode ) return node.getTextureNode();
  20370. return rtt( node, ...params );
  20371. };
  20372. /** @module PostProcessingUtils **/
  20373. /**
  20374. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  20375. * depth value and the camera's inverse projection matrix.
  20376. *
  20377. * @method
  20378. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  20379. * @param {Node<float>} depth - The fragment's depth value.
  20380. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  20381. * @return {Node<vec3>} The fragments position in view space.
  20382. */
  20383. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  20384. let clipSpacePosition;
  20385. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  20386. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  20387. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  20388. } else {
  20389. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  20390. }
  20391. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  20392. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  20393. } );
  20394. /**
  20395. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  20396. * and the camera's projection matrix
  20397. *
  20398. * @method
  20399. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  20400. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  20401. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  20402. */
  20403. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  20404. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  20405. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  20406. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  20407. } );
  20408. /**
  20409. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  20410. * target is available or if flat surface normals are required.
  20411. *
  20412. * @method
  20413. * @param {Node<vec2>} uv - The texture coordinate.
  20414. * @param {DepthTexture} depthTexture - The depth texture.
  20415. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  20416. * @return {Node<vec3>} The computed normal vector.
  20417. */
  20418. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  20419. const size = textureSize( textureLoad( depthTexture ) );
  20420. const p = ivec2( uv.mul( size ) ).toVar();
  20421. const c0 = textureLoad( depthTexture, p ).toVar();
  20422. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  20423. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  20424. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  20425. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  20426. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  20427. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  20428. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  20429. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  20430. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  20431. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  20432. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  20433. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  20434. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  20435. 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 ) ) );
  20436. 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 ) ) );
  20437. return normalize( cross( dpdx, dpdy ) );
  20438. } );
  20439. /**
  20440. * This special type of instanced buffer attribute is intended for compute shaders.
  20441. * In earlier three.js versions it was only possible to update attribute data
  20442. * on the CPU via JavaScript and then upload the data to the GPU. With the
  20443. * new material system and renderer it is now possible to use compute shaders
  20444. * to compute the data for an attribute more efficiently on the GPU.
  20445. *
  20446. * The idea is to create an instance of this class and provide it as an input
  20447. * to {@link module:StorageBufferNode}.
  20448. *
  20449. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  20450. *
  20451. * @augments InstancedBufferAttribute
  20452. */
  20453. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  20454. /**
  20455. * Constructs a new storage instanced buffer attribute.
  20456. *
  20457. * @param {Number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  20458. * The subsequent parameters are then obsolete.
  20459. * @param {Number} itemSize - The item size.
  20460. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  20461. */
  20462. constructor( count, itemSize, typeClass = Float32Array ) {
  20463. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  20464. super( array, itemSize );
  20465. /**
  20466. * This flag can be used for type testing.
  20467. *
  20468. * @type {Boolean}
  20469. * @readonly
  20470. * @default true
  20471. */
  20472. this.isStorageInstancedBufferAttribute = true;
  20473. }
  20474. }
  20475. /**
  20476. * This special type of buffer attribute is intended for compute shaders.
  20477. * In earlier three.js versions it was only possible to update attribute data
  20478. * on the CPU via JavaScript and then upload the data to the GPU. With the
  20479. * new material system and renderer it is now possible to use compute shaders
  20480. * to compute the data for an attribute more efficiently on the GPU.
  20481. *
  20482. * The idea is to create an instance of this class and provide it as an input
  20483. * to {@link module:StorageBufferNode}.
  20484. *
  20485. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  20486. *
  20487. * @augments BufferAttribute
  20488. */
  20489. class StorageBufferAttribute extends BufferAttribute {
  20490. /**
  20491. * Constructs a new storage buffer attribute.
  20492. *
  20493. * @param {Number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  20494. * The subsequent parameters are then obsolete.
  20495. * @param {Number} itemSize - The item size.
  20496. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  20497. */
  20498. constructor( count, itemSize, typeClass = Float32Array ) {
  20499. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  20500. super( array, itemSize );
  20501. /**
  20502. * This flag can be used for type testing.
  20503. *
  20504. * @type {Boolean}
  20505. * @readonly
  20506. * @default true
  20507. */
  20508. this.isStorageBufferAttribute = true;
  20509. }
  20510. }
  20511. /** @module StorageArrayElementNode **/
  20512. /**
  20513. * This class enables element access on instances of {@link StorageBufferNode}.
  20514. * In most cases, it is indirectly used when accessing elements with the
  20515. * {@link StorageBufferNode#element} method.
  20516. *
  20517. * ```js
  20518. * const position = positionStorage.element( instanceIndex );
  20519. * ```
  20520. *
  20521. * @augments ArrayElementNode
  20522. */
  20523. class StorageArrayElementNode extends ArrayElementNode {
  20524. static get type() {
  20525. return 'StorageArrayElementNode';
  20526. }
  20527. /**
  20528. * Constructs storage buffer element node.
  20529. *
  20530. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  20531. * @param {Node} indexNode - The index node that defines the element access.
  20532. */
  20533. constructor( storageBufferNode, indexNode ) {
  20534. super( storageBufferNode, indexNode );
  20535. /**
  20536. * This flag can be used for type testing.
  20537. *
  20538. * @type {Boolean}
  20539. * @readonly
  20540. * @default true
  20541. */
  20542. this.isStorageArrayElementNode = true;
  20543. }
  20544. /**
  20545. * The storage buffer node.
  20546. *
  20547. * @param {Node} value
  20548. * @type {StorageBufferNode}
  20549. */
  20550. set storageBufferNode( value ) {
  20551. this.node = value;
  20552. }
  20553. get storageBufferNode() {
  20554. return this.node;
  20555. }
  20556. setup( builder ) {
  20557. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  20558. if ( this.node.isPBO === true ) {
  20559. builder.setupPBO( this.node );
  20560. }
  20561. }
  20562. return super.setup( builder );
  20563. }
  20564. generate( builder, output ) {
  20565. let snippet;
  20566. const isAssignContext = builder.context.assign;
  20567. //
  20568. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  20569. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  20570. snippet = builder.generatePBO( this );
  20571. } else {
  20572. snippet = this.node.build( builder );
  20573. }
  20574. } else {
  20575. snippet = super.generate( builder );
  20576. }
  20577. if ( isAssignContext !== true ) {
  20578. const type = this.getNodeType( builder );
  20579. snippet = builder.format( snippet, type, output );
  20580. }
  20581. return snippet;
  20582. }
  20583. }
  20584. /**
  20585. * TSL function for creating a storage element node.
  20586. *
  20587. * @function
  20588. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  20589. * @param {Node} indexNode - The index node that defines the element access.
  20590. * @returns {StorageArrayElementNode}
  20591. */
  20592. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  20593. /** @module StorageBufferNode **/
  20594. /**
  20595. * This node is used in context of compute shaders and allows to define a
  20596. * storage buffer for data. A typical workflow is to create instances of
  20597. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  20598. * setup up a compute shader that writes into the buffers and then convert
  20599. * the storage buffers to attribute nodes for rendering.
  20600. *
  20601. * ```js
  20602. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  20603. *
  20604. * const computeInit = Fn( () => { // the compute shader
  20605. *
  20606. * const position = positionBuffer.element( instanceIndex );
  20607. *
  20608. * // compute position data
  20609. *
  20610. * position.x = 1;
  20611. * position.y = 1;
  20612. * position.z = 1;
  20613. *
  20614. * } )().compute( particleCount );
  20615. *
  20616. * const particleMaterial = new THREE.SpriteNodeMaterial();
  20617. * particleMaterial.positionNode = positionBuffer.toAttribute();
  20618. *
  20619. * renderer.computeAsync( computeInit );
  20620. *
  20621. * ```
  20622. *
  20623. * @augments BufferNode
  20624. */
  20625. class StorageBufferNode extends BufferNode {
  20626. static get type() {
  20627. return 'StorageBufferNode';
  20628. }
  20629. /**
  20630. * Constructs a new storage buffer node.
  20631. *
  20632. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  20633. * @param {String?} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  20634. * @param {Number} [bufferCount=0] - The buffer count.
  20635. */
  20636. constructor( value, bufferType = null, bufferCount = 0 ) {
  20637. if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  20638. bufferType = getTypeFromLength( value.itemSize );
  20639. bufferCount = value.count;
  20640. }
  20641. super( value, bufferType, bufferCount );
  20642. /**
  20643. * This flag can be used for type testing.
  20644. *
  20645. * @type {Boolean}
  20646. * @readonly
  20647. * @default true
  20648. */
  20649. this.isStorageBufferNode = true;
  20650. /**
  20651. * The access type of the texture node.
  20652. *
  20653. * @type {String}
  20654. * @default 'readWrite'
  20655. */
  20656. this.access = NodeAccess.READ_WRITE;
  20657. /**
  20658. * Whether the node is atomic or not.
  20659. *
  20660. * @type {Boolean}
  20661. * @default false
  20662. */
  20663. this.isAtomic = false;
  20664. /**
  20665. * Whether the node represents a PBO or not.
  20666. * Only relevant for WebGL.
  20667. *
  20668. * @type {Boolean}
  20669. * @default false
  20670. */
  20671. this.isPBO = false;
  20672. /**
  20673. * A reference to the internal buffer attribute node.
  20674. *
  20675. * @type {BufferAttributeNode?}
  20676. * @default null
  20677. */
  20678. this._attribute = null;
  20679. /**
  20680. * A reference to the internal varying node.
  20681. *
  20682. * @type {VaryingNode?}
  20683. * @default null
  20684. */
  20685. this._varying = null;
  20686. /**
  20687. * `StorageBufferNode` sets this property to `true` by default.
  20688. *
  20689. * @type {Boolean}
  20690. * @default true
  20691. */
  20692. this.global = true;
  20693. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  20694. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  20695. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  20696. else value.isStorageBufferAttribute = true;
  20697. }
  20698. }
  20699. /**
  20700. * This method is overwritten since the buffer data might be shared
  20701. * and thus the hash should be shared as well.
  20702. *
  20703. * @param {NodeBuilder} builder - The current node builder.
  20704. * @return {String} The hash.
  20705. */
  20706. getHash( builder ) {
  20707. if ( this.bufferCount === 0 ) {
  20708. let bufferData = builder.globalCache.getData( this.value );
  20709. if ( bufferData === undefined ) {
  20710. bufferData = {
  20711. node: this
  20712. };
  20713. builder.globalCache.setData( this.value, bufferData );
  20714. }
  20715. return bufferData.node.uuid;
  20716. }
  20717. return this.uuid;
  20718. }
  20719. /**
  20720. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  20721. *
  20722. * @param {NodeBuilder} builder - The current node builder.
  20723. * @return {String} The input type.
  20724. */
  20725. getInputType( /*builder*/ ) {
  20726. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  20727. }
  20728. /**
  20729. * Enables element access with the given index node.
  20730. *
  20731. * @param {IndexNode} indexNode - The index node.
  20732. * @return {StorageArrayElementNode} A node representing the element access.
  20733. */
  20734. element( indexNode ) {
  20735. return storageElement( this, indexNode );
  20736. }
  20737. /**
  20738. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  20739. *
  20740. * @param {Boolean} value - The value so set.
  20741. * @return {StorageBufferNode} A reference to this node.
  20742. */
  20743. setPBO( value ) {
  20744. this.isPBO = value;
  20745. return this;
  20746. }
  20747. /**
  20748. * Returns the `isPBO` value.
  20749. *
  20750. * @return {Boolean} Whether the node represents a PBO or not.
  20751. */
  20752. getPBO() {
  20753. return this.isPBO;
  20754. }
  20755. /**
  20756. * Defines the node access.
  20757. *
  20758. * @param {String} value - The node access.
  20759. * @return {StorageBufferNode} A reference to this node.
  20760. */
  20761. setAccess( value ) {
  20762. this.access = value;
  20763. return this;
  20764. }
  20765. /**
  20766. * Convenience method for configuring a read-only node access.
  20767. *
  20768. * @return {StorageBufferNode} A reference to this node.
  20769. */
  20770. toReadOnly() {
  20771. return this.setAccess( NodeAccess.READ_ONLY );
  20772. }
  20773. /**
  20774. * Defines whether the node is atomic or not.
  20775. *
  20776. * @param {Boolean} value - The atomic flag.
  20777. * @return {StorageBufferNode} A reference to this node.
  20778. */
  20779. setAtomic( value ) {
  20780. this.isAtomic = value;
  20781. return this;
  20782. }
  20783. /**
  20784. * Convenience method for making this node atomic.
  20785. *
  20786. * @return {StorageBufferNode} A reference to this node.
  20787. */
  20788. toAtomic() {
  20789. return this.setAtomic( true );
  20790. }
  20791. /**
  20792. * Returns attribute data for this storage buffer node.
  20793. *
  20794. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  20795. */
  20796. getAttributeData() {
  20797. if ( this._attribute === null ) {
  20798. this._attribute = bufferAttribute( this.value );
  20799. this._varying = varying( this._attribute );
  20800. }
  20801. return {
  20802. attribute: this._attribute,
  20803. varying: this._varying
  20804. };
  20805. }
  20806. /**
  20807. * This method is overwritten since the node type from the availability of storage buffers
  20808. * and the attribute data.
  20809. *
  20810. * @param {NodeBuilder} builder - The current node builder.
  20811. * @return {String} The node type.
  20812. */
  20813. getNodeType( builder ) {
  20814. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  20815. return super.getNodeType( builder );
  20816. }
  20817. const { attribute } = this.getAttributeData();
  20818. return attribute.getNodeType( builder );
  20819. }
  20820. /**
  20821. * Generates the code snippet of the storage buffer node.
  20822. *
  20823. * @param {NodeBuilder} builder - The current node builder.
  20824. * @return {String} The generated code snippet.
  20825. */
  20826. generate( builder ) {
  20827. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  20828. return super.generate( builder );
  20829. }
  20830. const { attribute, varying } = this.getAttributeData();
  20831. const output = varying.build( builder );
  20832. builder.registerTransform( output, attribute );
  20833. return output;
  20834. }
  20835. }
  20836. /**
  20837. * TSL function for creating a storage buffer node.
  20838. *
  20839. * @function
  20840. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  20841. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  20842. * @param {Number} [count=0] - The buffer count.
  20843. * @returns {StorageBufferNode}
  20844. */
  20845. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  20846. const storageObject = ( value, type, count ) => { // @deprecated, r171
  20847. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  20848. return storage( value, type, count ).setPBO( true );
  20849. };
  20850. /** @module Arrays **/
  20851. /**
  20852. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  20853. *
  20854. * @function
  20855. * @param {Number} count - The data count.
  20856. * @param {String} [type='float'] - The data type.
  20857. * @returns {StorageBufferNode}
  20858. */
  20859. const attributeArray = ( count, type = 'float' ) => {
  20860. const itemSize = getLengthFromType( type );
  20861. const typedArray = getTypedArrayFromType( type );
  20862. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  20863. const node = storage( buffer, type, count );
  20864. return node;
  20865. };
  20866. /**
  20867. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  20868. *
  20869. * @function
  20870. * @param {Number} count - The data count.
  20871. * @param {String} [type='float'] - The data type.
  20872. * @returns {StorageBufferNode}
  20873. */
  20874. const instancedArray = ( count, type = 'float' ) => {
  20875. const itemSize = getLengthFromType( type );
  20876. const typedArray = getTypedArrayFromType( type );
  20877. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  20878. const node = storage( buffer, type, count );
  20879. return node;
  20880. };
  20881. /** @module VertexColorNode **/
  20882. /**
  20883. * An attribute node for representing vertex colors.
  20884. *
  20885. * @augments module:AttributeNode~AttributeNode
  20886. */
  20887. class VertexColorNode extends AttributeNode {
  20888. static get type() {
  20889. return 'VertexColorNode';
  20890. }
  20891. /**
  20892. * Constructs a new vertex color node.
  20893. *
  20894. * @param {Number} [index=0] - The attribute index.
  20895. */
  20896. constructor( index = 0 ) {
  20897. super( null, 'vec4' );
  20898. /**
  20899. * This flag can be used for type testing.
  20900. *
  20901. * @type {Boolean}
  20902. * @readonly
  20903. * @default true
  20904. */
  20905. this.isVertexColorNode = true;
  20906. /**
  20907. * The attribute index to enable more than one sets of vertex colors.
  20908. *
  20909. * @type {Number}
  20910. * @default 0
  20911. */
  20912. this.index = index;
  20913. }
  20914. /**
  20915. * Overwrites the default implementation by honoring the attribute index.
  20916. *
  20917. * @param {NodeBuilder} builder - The current node builder.
  20918. * @return {String} The attribute name.
  20919. */
  20920. getAttributeName( /*builder*/ ) {
  20921. const index = this.index;
  20922. return 'color' + ( index > 0 ? index : '' );
  20923. }
  20924. generate( builder ) {
  20925. const attributeName = this.getAttributeName( builder );
  20926. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  20927. let result;
  20928. if ( geometryAttribute === true ) {
  20929. result = super.generate( builder );
  20930. } else {
  20931. // Vertex color fallback should be white
  20932. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  20933. }
  20934. return result;
  20935. }
  20936. serialize( data ) {
  20937. super.serialize( data );
  20938. data.index = this.index;
  20939. }
  20940. deserialize( data ) {
  20941. super.deserialize( data );
  20942. this.index = data.index;
  20943. }
  20944. }
  20945. /**
  20946. * TSL function for creating a reference node.
  20947. *
  20948. * @function
  20949. * @param {Number} index - The attribute index.
  20950. * @returns {VertexColorNode}
  20951. */
  20952. const vertexColor = ( index ) => nodeObject( new VertexColorNode( index ) );
  20953. /** @module PointUVNode **/
  20954. /**
  20955. * A node for representing the uv coordinates of points.
  20956. *
  20957. * Can only be used with a WebGL backend. In WebGPU, point
  20958. * primitives always have the size of one pixel and can thus
  20959. * can't be used as sprite-like objects that display textures.
  20960. *
  20961. * @augments Node
  20962. */
  20963. class PointUVNode extends Node {
  20964. static get type() {
  20965. return 'PointUVNode';
  20966. }
  20967. /**
  20968. * Constructs a new point uv node.
  20969. */
  20970. constructor() {
  20971. super( 'vec2' );
  20972. /**
  20973. * This flag can be used for type testing.
  20974. *
  20975. * @type {Boolean}
  20976. * @readonly
  20977. * @default true
  20978. */
  20979. this.isPointUVNode = true;
  20980. }
  20981. generate( /*builder*/ ) {
  20982. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  20983. }
  20984. }
  20985. /**
  20986. * TSL object that represents the uv coordinates of points.
  20987. *
  20988. * @type {PointUVNode}
  20989. */
  20990. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  20991. const _e1 = /*@__PURE__*/ new Euler();
  20992. const _m1 = /*@__PURE__*/ new Matrix4();
  20993. /** @module SceneNode **/
  20994. /**
  20995. * This module allows access to a collection of scene properties. The following predefined TSL objects
  20996. * are available for easier use:
  20997. *
  20998. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  20999. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  21000. * - `backgroundRotation`: A node that represents the scene's background rotation.
  21001. *
  21002. * @augments Node
  21003. */
  21004. class SceneNode extends Node {
  21005. static get type() {
  21006. return 'SceneNode';
  21007. }
  21008. /**
  21009. * Constructs a new scene node.
  21010. *
  21011. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  21012. * @param {Scene?} [scene=null] - A reference to the scene.
  21013. */
  21014. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  21015. super();
  21016. /**
  21017. * The scope defines the type of scene property that is accessed.
  21018. *
  21019. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  21020. */
  21021. this.scope = scope;
  21022. /**
  21023. * A reference to the scene that is going to be accessed.
  21024. *
  21025. * @type {Scene?}
  21026. * @default null
  21027. */
  21028. this.scene = scene;
  21029. }
  21030. /**
  21031. * Depending on the scope, the method returns a different type of node that represents
  21032. * the respective scene property.
  21033. *
  21034. * @param {NodeBuilder} builder - The current node builder.
  21035. * @return {Node} The output node.
  21036. */
  21037. setup( builder ) {
  21038. const scope = this.scope;
  21039. const scene = this.scene !== null ? this.scene : builder.scene;
  21040. let output;
  21041. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  21042. output = reference( 'backgroundBlurriness', 'float', scene );
  21043. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  21044. output = reference( 'backgroundIntensity', 'float', scene );
  21045. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  21046. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  21047. const background = scene.background;
  21048. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  21049. _e1.copy( scene.backgroundRotation );
  21050. // accommodate left-handed frame
  21051. _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1;
  21052. _m1.makeRotationFromEuler( _e1 );
  21053. } else {
  21054. _m1.identity();
  21055. }
  21056. return _m1;
  21057. } );
  21058. } else {
  21059. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  21060. }
  21061. return output;
  21062. }
  21063. }
  21064. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  21065. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  21066. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  21067. /**
  21068. * TSL object that represents the scene's background blurriness.
  21069. *
  21070. * @type {SceneNode}
  21071. */
  21072. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  21073. /**
  21074. * TSL object that represents the scene's background intensity.
  21075. *
  21076. * @type {SceneNode}
  21077. */
  21078. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  21079. /**
  21080. * TSL object that represents the scene's background rotation.
  21081. *
  21082. * @type {SceneNode}
  21083. */
  21084. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  21085. /** @module StorageTextureNode **/
  21086. /**
  21087. * This special version of a texture node can be used to
  21088. * write data into a storage texture with a compute shader.
  21089. *
  21090. * ```js
  21091. * const storageTexture = new THREE.StorageTexture( width, height );
  21092. *
  21093. * const computeTexture = Fn( ( { storageTexture } ) => {
  21094. *
  21095. * const posX = instanceIndex.modInt( width );
  21096. * const posY = instanceIndex.div( width );
  21097. * const indexUV = uvec2( posX, posY );
  21098. *
  21099. * // generate RGB values
  21100. *
  21101. * const r = 1;
  21102. * const g = 1;
  21103. * const b = 1;
  21104. *
  21105. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  21106. *
  21107. * } );
  21108. *
  21109. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  21110. * renderer.computeAsync( computeNode );
  21111. * ```
  21112. *
  21113. * This node can only be used with a WebGPU backend.
  21114. *
  21115. * @augments module:TextureNode~TextureNode
  21116. */
  21117. class StorageTextureNode extends TextureNode {
  21118. static get type() {
  21119. return 'StorageTextureNode';
  21120. }
  21121. /**
  21122. * Constructs a new storage texture node.
  21123. *
  21124. * @param {StorageTexture} value - The storage texture.
  21125. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21126. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  21127. */
  21128. constructor( value, uvNode, storeNode = null ) {
  21129. super( value, uvNode );
  21130. /**
  21131. * The value node that should be stored in the texture.
  21132. *
  21133. * @type {Node?}
  21134. * @default null
  21135. */
  21136. this.storeNode = storeNode;
  21137. /**
  21138. * This flag can be used for type testing.
  21139. *
  21140. * @type {Boolean}
  21141. * @readonly
  21142. * @default true
  21143. */
  21144. this.isStorageTextureNode = true;
  21145. /**
  21146. * The access type of the texture node.
  21147. *
  21148. * @type {String}
  21149. * @default 'writeOnly'
  21150. */
  21151. this.access = NodeAccess.WRITE_ONLY;
  21152. }
  21153. /**
  21154. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  21155. *
  21156. * @param {NodeBuilder} builder - The current node builder.
  21157. * @return {String} The input type.
  21158. */
  21159. getInputType( /*builder*/ ) {
  21160. return 'storageTexture';
  21161. }
  21162. setup( builder ) {
  21163. super.setup( builder );
  21164. const properties = builder.getNodeProperties( this );
  21165. properties.storeNode = this.storeNode;
  21166. }
  21167. /**
  21168. * Defines the node access.
  21169. *
  21170. * @param {String} value - The node access.
  21171. * @return {StorageTextureNode} A reference to this node.
  21172. */
  21173. setAccess( value ) {
  21174. this.access = value;
  21175. return this;
  21176. }
  21177. /**
  21178. * Generates the code snippet of the stroge node. If no `storeNode`
  21179. * is defined, the texture node is generated as normal texture.
  21180. *
  21181. * @param {NodeBuilder} builder - The current node builder.
  21182. * @param {String} output - The current output.
  21183. * @return {String} The generated code snippet.
  21184. */
  21185. generate( builder, output ) {
  21186. let snippet;
  21187. if ( this.storeNode !== null ) {
  21188. snippet = this.generateStore( builder );
  21189. } else {
  21190. snippet = super.generate( builder, output );
  21191. }
  21192. return snippet;
  21193. }
  21194. /**
  21195. * Convenience method for configuring a read/write node access.
  21196. *
  21197. * @return {StorageTextureNode} A reference to this node.
  21198. */
  21199. toReadWrite() {
  21200. return this.setAccess( NodeAccess.READ_WRITE );
  21201. }
  21202. /**
  21203. * Convenience method for configuring a read-only node access.
  21204. *
  21205. * @return {StorageTextureNode} A reference to this node.
  21206. */
  21207. toReadOnly() {
  21208. return this.setAccess( NodeAccess.READ_ONLY );
  21209. }
  21210. /**
  21211. * Convenience method for configuring a write-only node access.
  21212. *
  21213. * @return {StorageTextureNode} A reference to this node.
  21214. */
  21215. toWriteOnly() {
  21216. return this.setAccess( NodeAccess.WRITE_ONLY );
  21217. }
  21218. /**
  21219. * Generates the code snippet of the storage texture node.
  21220. *
  21221. * @param {NodeBuilder} builder - The current node builder.
  21222. */
  21223. generateStore( builder ) {
  21224. const properties = builder.getNodeProperties( this );
  21225. const { uvNode, storeNode } = properties;
  21226. const textureProperty = super.generate( builder, 'property' );
  21227. const uvSnippet = uvNode.build( builder, 'uvec2' );
  21228. const storeSnippet = storeNode.build( builder, 'vec4' );
  21229. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  21230. builder.addLineFlowCode( snippet, this );
  21231. }
  21232. }
  21233. /**
  21234. * TSL function for creating a storage texture node.
  21235. *
  21236. * @function
  21237. * @param {StorageTexture} value - The storage texture.
  21238. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21239. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  21240. * @returns {StorageTextureNode}
  21241. */
  21242. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  21243. /**
  21244. * TODO: Explain difference to `storageTexture()`.
  21245. *
  21246. * @function
  21247. * @param {StorageTexture} value - The storage texture.
  21248. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21249. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  21250. * @returns {StorageTextureNode}
  21251. */
  21252. const textureStore = ( value, uvNode, storeNode ) => {
  21253. const node = storageTexture( value, uvNode, storeNode );
  21254. if ( storeNode !== null ) node.append();
  21255. return node;
  21256. };
  21257. /** @module UserDataNode **/
  21258. /**
  21259. * A special type of reference node that allows to link values in
  21260. * `userData` fields to node objects.
  21261. * ```js
  21262. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  21263. *
  21264. * const material = new THREE.SpriteNodeMaterial();
  21265. * material.rotationNode = userData( 'rotation', 'float' );
  21266. * ```
  21267. * Since `UserDataNode` is extended from {@link module:ReferenceNode~ReferenceNode}, the node value
  21268. * will automatically be updated when the `rotation` user data field changes.
  21269. *
  21270. * @augments module:ReferenceNode~ReferenceNode
  21271. */
  21272. class UserDataNode extends ReferenceNode {
  21273. static get type() {
  21274. return 'UserDataNode';
  21275. }
  21276. /**
  21277. * Constructs a new user data node.
  21278. *
  21279. * @param {String} property - The property name that should be referenced by the node.
  21280. * @param {String} inputType - The node data type of the reference.
  21281. * @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.
  21282. */
  21283. constructor( property, inputType, userData = null ) {
  21284. super( property, inputType, userData );
  21285. /**
  21286. * A reference to the `userData` object. If not provided, the `userData`
  21287. * property of the 3D object that uses the node material is evaluated.
  21288. *
  21289. * @type {Object?}
  21290. * @default null
  21291. */
  21292. this.userData = userData;
  21293. }
  21294. /**
  21295. * Overwritten to make sure {@link module:ReferenceNode~ReferenceNode#reference} points to the correct
  21296. * `userData` field.
  21297. *
  21298. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  21299. * @return {Object} A reference to the `userData` field.
  21300. */
  21301. updateReference( state ) {
  21302. this.reference = this.userData !== null ? this.userData : state.object.userData;
  21303. return this.reference;
  21304. }
  21305. }
  21306. /**
  21307. * TSL function for creating a user data node.
  21308. *
  21309. * @function
  21310. * @param {String} name - The property name that should be referenced by the node.
  21311. * @param {String} inputType - The node data type of the reference.
  21312. * @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.
  21313. * @returns {UserDataNode}
  21314. */
  21315. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  21316. const _objectData = new WeakMap();
  21317. /** @module VelocityNode **/
  21318. /**
  21319. * A node for representing motion or velocity vectors. Foundation
  21320. * for advanced post processing effects like motion blur or TRAA.
  21321. *
  21322. * The node keeps track of the model, view and projection matrices
  21323. * of the previous frame and uses them to compute offsets in NDC space.
  21324. * These offsets represent the final velocity.
  21325. *
  21326. * @augments TempNode
  21327. */
  21328. class VelocityNode extends TempNode {
  21329. static get type() {
  21330. return 'VelocityNode';
  21331. }
  21332. /**
  21333. * Constructs a new vertex color node.
  21334. *
  21335. * @param {Number} [index=0] - The attribute index.
  21336. */
  21337. constructor() {
  21338. super( 'vec2' );
  21339. /**
  21340. * The current projection matrix.
  21341. *
  21342. * @type {Matrix4?}
  21343. * @default null
  21344. */
  21345. this.projectionMatrix = null;
  21346. /**
  21347. * Overwritten since velocity nodes are updated per object.
  21348. *
  21349. * @type {String}
  21350. * @default 'object'
  21351. */
  21352. this.updateType = NodeUpdateType.OBJECT;
  21353. /**
  21354. * Overwritten since velocity nodes save data after the update.
  21355. *
  21356. * @type {String}
  21357. * @default 'object'
  21358. */
  21359. this.updateAfterType = NodeUpdateType.OBJECT;
  21360. /**
  21361. * Uniform node representing the previous model matrix in world space.
  21362. *
  21363. * @type {UniformNode<mat4>}
  21364. * @default null
  21365. */
  21366. this.previousModelWorldMatrix = uniform( new Matrix4() );
  21367. /**
  21368. * Uniform node representing the previous projection matrix.
  21369. *
  21370. * @type {UniformNode<mat4>}
  21371. * @default null
  21372. */
  21373. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  21374. /**
  21375. * Uniform node representing the previous view matrix.
  21376. *
  21377. * @type {UniformNode<mat4>}
  21378. * @default null
  21379. */
  21380. this.previousCameraViewMatrix = uniform( new Matrix4() );
  21381. }
  21382. /**
  21383. * Sets the given projection matrix.
  21384. *
  21385. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  21386. */
  21387. setProjectionMatrix( projectionMatrix ) {
  21388. this.projectionMatrix = projectionMatrix;
  21389. }
  21390. /**
  21391. * Updates velocity specific uniforms.
  21392. *
  21393. * @param {NodeFrame} frame - A reference to the current node frame.
  21394. */
  21395. update( { frameId, camera, object } ) {
  21396. const previousModelMatrix = getPreviousMatrix( object );
  21397. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  21398. //
  21399. const cameraData = getData( camera );
  21400. if ( cameraData.frameId !== frameId ) {
  21401. cameraData.frameId = frameId;
  21402. if ( cameraData.previousProjectionMatrix === undefined ) {
  21403. cameraData.previousProjectionMatrix = new Matrix4();
  21404. cameraData.previousCameraViewMatrix = new Matrix4();
  21405. cameraData.currentProjectionMatrix = new Matrix4();
  21406. cameraData.currentCameraViewMatrix = new Matrix4();
  21407. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  21408. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  21409. } else {
  21410. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  21411. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  21412. }
  21413. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  21414. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  21415. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  21416. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  21417. }
  21418. }
  21419. /**
  21420. * Overwritten to updated velocity specific uniforms.
  21421. *
  21422. * @param {NodeFrame} frame - A reference to the current node frame.
  21423. */
  21424. updateAfter( { object } ) {
  21425. getPreviousMatrix( object ).copy( object.matrixWorld );
  21426. }
  21427. /**
  21428. * Implements the velocity computation based on the previous and current vertex data.
  21429. *
  21430. * @param {NodeBuilder} builder - A reference to the current node builder.
  21431. * @return {Node<vec2>} The motion vector.
  21432. */
  21433. setup( /*builder*/ ) {
  21434. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  21435. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  21436. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  21437. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  21438. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  21439. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  21440. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  21441. return velocity;
  21442. }
  21443. }
  21444. function getData( object ) {
  21445. let objectData = _objectData.get( object );
  21446. if ( objectData === undefined ) {
  21447. objectData = {};
  21448. _objectData.set( object, objectData );
  21449. }
  21450. return objectData;
  21451. }
  21452. function getPreviousMatrix( object, index = 0 ) {
  21453. const objectData = getData( object );
  21454. let matrix = objectData[ index ];
  21455. if ( matrix === undefined ) {
  21456. objectData[ index ] = matrix = new Matrix4();
  21457. }
  21458. return matrix;
  21459. }
  21460. /**
  21461. * TSL object that represents the velocity of a render pass.
  21462. *
  21463. * @type {VelocityNode}
  21464. */
  21465. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  21466. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21467. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  21468. } ).setLayout( {
  21469. name: 'blendBurn',
  21470. type: 'vec3',
  21471. inputs: [
  21472. { name: 'base', type: 'vec3' },
  21473. { name: 'blend', type: 'vec3' }
  21474. ]
  21475. } );
  21476. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21477. return min$1( base.div( blend.oneMinus() ), 1.0 );
  21478. } ).setLayout( {
  21479. name: 'blendDodge',
  21480. type: 'vec3',
  21481. inputs: [
  21482. { name: 'base', type: 'vec3' },
  21483. { name: 'blend', type: 'vec3' }
  21484. ]
  21485. } );
  21486. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21487. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  21488. } ).setLayout( {
  21489. name: 'blendScreen',
  21490. type: 'vec3',
  21491. inputs: [
  21492. { name: 'base', type: 'vec3' },
  21493. { name: 'blend', type: 'vec3' }
  21494. ]
  21495. } );
  21496. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21497. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  21498. } ).setLayout( {
  21499. name: 'blendOverlay',
  21500. type: 'vec3',
  21501. inputs: [
  21502. { name: 'base', type: 'vec3' },
  21503. { name: 'blend', type: 'vec3' }
  21504. ]
  21505. } );
  21506. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21507. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  21508. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  21509. } ).setLayout( {
  21510. name: 'blendColor',
  21511. type: 'vec4',
  21512. inputs: [
  21513. { name: 'base', type: 'vec4' },
  21514. { name: 'blend', type: 'vec4' }
  21515. ]
  21516. } );
  21517. // deprecated
  21518. const burn = ( ...params ) => { // @deprecated, r171
  21519. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  21520. return blendBurn( params );
  21521. };
  21522. const dodge = ( ...params ) => { // @deprecated, r171
  21523. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  21524. return blendDodge( params );
  21525. };
  21526. const screen = ( ...params ) => { // @deprecated, r171
  21527. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  21528. return blendScreen( params );
  21529. };
  21530. const overlay = ( ...params ) => { // @deprecated, r171
  21531. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  21532. return blendOverlay( params );
  21533. };
  21534. /** @module ColorAdjustment **/
  21535. /**
  21536. * Computes a grayscale value for the given RGB color value.
  21537. *
  21538. * @method
  21539. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  21540. * @return {Node<vec3>} The grayscale color.
  21541. */
  21542. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  21543. return luminance( color.rgb );
  21544. } );
  21545. /**
  21546. * Super-saturates or desaturates the given RGB color.
  21547. *
  21548. * @method
  21549. * @param {Node<vec3>} color - The input color.
  21550. * @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.
  21551. * @return {Node<vec3>} The saturated color.
  21552. */
  21553. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  21554. return adjustment.mix( luminance( color.rgb ), color.rgb );
  21555. } );
  21556. /**
  21557. * Selectively enhance the intensity of less saturated RGB colors. Can result
  21558. * in a more natural and visually appealing image with enhanced color depth
  21559. * compared to {@link ColorAdjustment#saturation}.
  21560. *
  21561. * @method
  21562. * @param {Node<vec3>} color - The input color.
  21563. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  21564. * @return {Node<vec3>} The updated color.
  21565. */
  21566. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  21567. const average = add( color.r, color.g, color.b ).div( 3.0 );
  21568. const mx = color.r.max( color.g.max( color.b ) );
  21569. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  21570. return mix( color.rgb, mx, amt );
  21571. } );
  21572. /**
  21573. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  21574. *
  21575. * @method
  21576. * @param {Node<vec3>} color - The input color.
  21577. * @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.
  21578. * @return {Node<vec3>} The updated color.
  21579. */
  21580. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  21581. const k = vec3( 0.57735, 0.57735, 0.57735 );
  21582. const cosAngle = adjustment.cos();
  21583. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  21584. } );
  21585. /**
  21586. * Computes the luminance for the given RGB color value.
  21587. *
  21588. * @method
  21589. * @param {Node<vec3>} color - The color value to compute the luminance for.
  21590. * @param {Node<vec3>?} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  21591. * @return {Node<vec3>} The luminance.
  21592. */
  21593. const luminance = (
  21594. color,
  21595. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  21596. ) => dot( color, luminanceCoefficients );
  21597. /**
  21598. * Color Decision List (CDL) v1.2
  21599. *
  21600. * Compact representation of color grading information, defined by slope, offset, power, and
  21601. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  21602. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  21603. *
  21604. * @method
  21605. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  21606. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  21607. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  21608. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  21609. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  21610. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  21611. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  21612. *
  21613. * References:
  21614. * - ASC CDL v1.2
  21615. * - {@link https://blender.stackexchange.com/a/55239/43930}
  21616. * - {@link https://docs.acescentral.com/specifications/acescc/}
  21617. */
  21618. const cdl = /*@__PURE__*/ Fn( ( [
  21619. color,
  21620. slope = vec3( 1 ),
  21621. offset = vec3( 0 ),
  21622. power = vec3( 1 ),
  21623. saturation = float( 1 ),
  21624. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  21625. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  21626. ] ) => {
  21627. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  21628. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  21629. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  21630. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  21631. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  21632. const pv = v.pow( power ).toVar();
  21633. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  21634. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  21635. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  21636. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  21637. return vec4( v.rgb, color.a );
  21638. } );
  21639. /** @module PosterizeNode **/
  21640. /**
  21641. * Represents a posterize effect which reduces the number of colors
  21642. * in an image, resulting in a more blocky and stylized appearance.
  21643. *
  21644. * @augments TempNode
  21645. */
  21646. class PosterizeNode extends TempNode {
  21647. static get type() {
  21648. return 'PosterizeNode';
  21649. }
  21650. /**
  21651. * Constructs a new posterize node.
  21652. *
  21653. * @param {Node} sourceNode - The input color.
  21654. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  21655. */
  21656. constructor( sourceNode, stepsNode ) {
  21657. super();
  21658. /**
  21659. * The input color.
  21660. *
  21661. * @type {Node}
  21662. */
  21663. this.sourceNode = sourceNode;
  21664. /**
  21665. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  21666. *
  21667. * @type {Node}
  21668. */
  21669. this.stepsNode = stepsNode;
  21670. }
  21671. setup() {
  21672. const { sourceNode, stepsNode } = this;
  21673. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  21674. }
  21675. }
  21676. /**
  21677. * TSL function for creating a posterize node.
  21678. *
  21679. * @function
  21680. * @param {Node} sourceNode - The input color.
  21681. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  21682. * @returns {PosterizeNode}
  21683. */
  21684. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  21685. /** @module PassNode **/
  21686. const _size = /*@__PURE__*/ new Vector2();
  21687. /**
  21688. * Represents the texture of a pass node.
  21689. *
  21690. * @augments module:TextureNode~TextureNode
  21691. */
  21692. class PassTextureNode extends TextureNode {
  21693. static get type() {
  21694. return 'PassTextureNode';
  21695. }
  21696. /**
  21697. * Constructs a new pass texture node.
  21698. *
  21699. * @param {PassNode} passNode - The pass node.
  21700. * @param {Texture} texture - The output texture.
  21701. */
  21702. constructor( passNode, texture ) {
  21703. super( texture );
  21704. /**
  21705. * A reference to the pass node.
  21706. *
  21707. * @type {PassNode}
  21708. */
  21709. this.passNode = passNode;
  21710. this.setUpdateMatrix( false );
  21711. }
  21712. setup( builder ) {
  21713. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  21714. return super.setup( builder );
  21715. }
  21716. clone() {
  21717. return new this.constructor( this.passNode, this.value );
  21718. }
  21719. }
  21720. /**
  21721. * An extension of `PassTextureNode` which allows to manage more than one
  21722. * internal texture. Relevant for the `getPreviousTexture()` related API.
  21723. *
  21724. * @augments module:PassTextureNode~PassTextureNode
  21725. */
  21726. class PassMultipleTextureNode extends PassTextureNode {
  21727. static get type() {
  21728. return 'PassMultipleTextureNode';
  21729. }
  21730. /**
  21731. * Constructs a new pass texture node.
  21732. *
  21733. * @param {PassNode} passNode - The pass node.
  21734. * @param {String} textureName - The output texture name.
  21735. * @param {Boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  21736. */
  21737. constructor( passNode, textureName, previousTexture = false ) {
  21738. // null is passed to the super call since this class does not
  21739. // use an external texture for rendering pass data into. Instead
  21740. // the texture is managed by the pass node itself
  21741. super( passNode, null );
  21742. /**
  21743. * The output texture name.
  21744. *
  21745. * @type {String}
  21746. */
  21747. this.textureName = textureName;
  21748. /**
  21749. * Whether previous frame data should be used or not.
  21750. *
  21751. * @type {Boolean}
  21752. */
  21753. this.previousTexture = previousTexture;
  21754. }
  21755. /**
  21756. * Updates the texture reference of this node.
  21757. */
  21758. updateTexture() {
  21759. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  21760. }
  21761. setup( builder ) {
  21762. this.updateTexture();
  21763. return super.setup( builder );
  21764. }
  21765. clone() {
  21766. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  21767. }
  21768. }
  21769. /**
  21770. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  21771. * This pass produces a render for the given scene and camera and can provide multiple outputs
  21772. * via MRT for further processing.
  21773. *
  21774. * ```js
  21775. * const postProcessing = new PostProcessing( renderer );
  21776. *
  21777. * const scenePass = pass( scene, camera );
  21778. *
  21779. * postProcessing.outputNode = scenePass;
  21780. * ```
  21781. *
  21782. * @augments TempNode
  21783. */
  21784. class PassNode extends TempNode {
  21785. static get type() {
  21786. return 'PassNode';
  21787. }
  21788. /**
  21789. * Constructs a new pass node.
  21790. *
  21791. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  21792. * @param {Scene} scene - A reference to the scene.
  21793. * @param {Camera} camera - A reference to the camera.
  21794. * @param {Object} options - Options for the internal render target.
  21795. */
  21796. constructor( scope, scene, camera, options = {} ) {
  21797. super( 'vec4' );
  21798. /**
  21799. * The scope of the pass. The scope determines whether the node outputs color or depth.
  21800. *
  21801. * @type {('color'|'depth')}
  21802. */
  21803. this.scope = scope;
  21804. /**
  21805. * A reference to the scene.
  21806. *
  21807. * @type {Scene}
  21808. */
  21809. this.scene = scene;
  21810. /**
  21811. * A reference to the camera.
  21812. *
  21813. * @type {Camera}
  21814. */
  21815. this.camera = camera;
  21816. /**
  21817. * Options for the internal render target.
  21818. *
  21819. * @type {Object}
  21820. */
  21821. this.options = options;
  21822. /**
  21823. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  21824. *
  21825. * @private
  21826. * @type {Number}
  21827. * @default 1
  21828. */
  21829. this._pixelRatio = 1;
  21830. /**
  21831. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  21832. * @private
  21833. * @type {Number}
  21834. * @default 1
  21835. */
  21836. this._width = 1;
  21837. /**
  21838. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  21839. * @private
  21840. * @type {Number}
  21841. * @default 1
  21842. */
  21843. this._height = 1;
  21844. const depthTexture = new DepthTexture();
  21845. depthTexture.isRenderTargetTexture = true;
  21846. //depthTexture.type = FloatType;
  21847. depthTexture.name = 'depth';
  21848. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  21849. renderTarget.texture.name = 'output';
  21850. renderTarget.depthTexture = depthTexture;
  21851. /**
  21852. * The pass's render target.
  21853. *
  21854. * @type {RenderTarget}
  21855. */
  21856. this.renderTarget = renderTarget;
  21857. /**
  21858. * A dictionary holding the internal result textures.
  21859. *
  21860. * @private
  21861. * @type {Object<String, Texture>}
  21862. */
  21863. this._textures = {
  21864. output: renderTarget.texture,
  21865. depth: depthTexture
  21866. };
  21867. /**
  21868. * A dictionary holding the internal texture nodes.
  21869. *
  21870. * @private
  21871. * @type {Object<String, TextureNode>}
  21872. */
  21873. this._textureNodes = {};
  21874. /**
  21875. * A dictionary holding the internal depth nodes.
  21876. *
  21877. * @private
  21878. * @type {Object}
  21879. */
  21880. this._linearDepthNodes = {};
  21881. /**
  21882. * A dictionary holding the internal viewZ nodes.
  21883. *
  21884. * @private
  21885. * @type {Object}
  21886. */
  21887. this._viewZNodes = {};
  21888. /**
  21889. * A dictionary holding the texture data of the previous frame.
  21890. * Used for computing velocity/motion vectors.
  21891. *
  21892. * @private
  21893. * @type {Object<String, Texture>}
  21894. */
  21895. this._previousTextures = {};
  21896. /**
  21897. * A dictionary holding the texture nodes of the previous frame.
  21898. * Used for computing velocity/motion vectors.
  21899. *
  21900. * @private
  21901. * @type {Object<String, TextureNode>}
  21902. */
  21903. this._previousTextureNodes = {};
  21904. /**
  21905. * The `near` property of the camera as a uniform.
  21906. *
  21907. * @private
  21908. * @type {UniformNode}
  21909. */
  21910. this._cameraNear = uniform( 0 );
  21911. /**
  21912. * The `far` property of the camera as a uniform.
  21913. *
  21914. * @private
  21915. * @type {UniformNode}
  21916. */
  21917. this._cameraFar = uniform( 0 );
  21918. /**
  21919. * A MRT node configuring the MRT settings.
  21920. *
  21921. * @private
  21922. * @type {MRTNode?}
  21923. * @default null
  21924. */
  21925. this._mrt = null;
  21926. /**
  21927. * This flag can be used for type testing.
  21928. *
  21929. * @type {Boolean}
  21930. * @readonly
  21931. * @default true
  21932. */
  21933. this.isPassNode = true;
  21934. /**
  21935. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  21936. * scene once per frame in its {@link PassNode#updateBefore} method.
  21937. *
  21938. * @type {String}
  21939. * @default 'frame'
  21940. */
  21941. this.updateBeforeType = NodeUpdateType.FRAME;
  21942. }
  21943. /**
  21944. * Sets the given MRT node to setup MRT for this pass.
  21945. *
  21946. * @param {MRTNode} mrt - The MRT object.
  21947. * @return {PassNode} A reference to this pass.
  21948. */
  21949. setMRT( mrt ) {
  21950. this._mrt = mrt;
  21951. return this;
  21952. }
  21953. /**
  21954. * Returns the current MRT node.
  21955. *
  21956. * @return {MRTNode} The current MRT node.
  21957. */
  21958. getMRT() {
  21959. return this._mrt;
  21960. }
  21961. /**
  21962. * The method is overwritten so it always returns `true`.
  21963. *
  21964. * @return {Boolean} Whether this node is global or not.
  21965. */
  21966. isGlobal() {
  21967. return true;
  21968. }
  21969. /**
  21970. * Returns the texture for the given output name.
  21971. *
  21972. * @param {String} name - The output name to get the texture for.
  21973. * @return {Texture} The texture.
  21974. */
  21975. getTexture( name ) {
  21976. let texture = this._textures[ name ];
  21977. if ( texture === undefined ) {
  21978. const refTexture = this.renderTarget.texture;
  21979. texture = refTexture.clone();
  21980. texture.name = name;
  21981. this._textures[ name ] = texture;
  21982. this.renderTarget.textures.push( texture );
  21983. }
  21984. return texture;
  21985. }
  21986. /**
  21987. * Returns the texture holding the data of the previous frame for the given output name.
  21988. *
  21989. * @param {String} name - The output name to get the texture for.
  21990. * @return {Texture} The texture holding the data of the previous frame.
  21991. */
  21992. getPreviousTexture( name ) {
  21993. let texture = this._previousTextures[ name ];
  21994. if ( texture === undefined ) {
  21995. texture = this.getTexture( name ).clone();
  21996. this._previousTextures[ name ] = texture;
  21997. }
  21998. return texture;
  21999. }
  22000. /**
  22001. * Switches current and previous textures for the given output name.
  22002. *
  22003. * @param {String} name - The output name.
  22004. */
  22005. toggleTexture( name ) {
  22006. const prevTexture = this._previousTextures[ name ];
  22007. if ( prevTexture !== undefined ) {
  22008. const texture = this._textures[ name ];
  22009. const index = this.renderTarget.textures.indexOf( texture );
  22010. this.renderTarget.textures[ index ] = prevTexture;
  22011. this._textures[ name ] = prevTexture;
  22012. this._previousTextures[ name ] = texture;
  22013. this._textureNodes[ name ].updateTexture();
  22014. this._previousTextureNodes[ name ].updateTexture();
  22015. }
  22016. }
  22017. /**
  22018. * Returns the texture node for the given output name.
  22019. *
  22020. * @param {String} [name='output'] - The output name to get the texture node for.
  22021. * @return {TextureNode} The texture node.
  22022. */
  22023. getTextureNode( name = 'output' ) {
  22024. let textureNode = this._textureNodes[ name ];
  22025. if ( textureNode === undefined ) {
  22026. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  22027. textureNode.updateTexture();
  22028. this._textureNodes[ name ] = textureNode;
  22029. }
  22030. return textureNode;
  22031. }
  22032. /**
  22033. * Returns the previous texture node for the given output name.
  22034. *
  22035. * @param {String} [name='output'] - The output name to get the previous texture node for.
  22036. * @return {TextureNode} The previous texture node.
  22037. */
  22038. getPreviousTextureNode( name = 'output' ) {
  22039. let textureNode = this._previousTextureNodes[ name ];
  22040. if ( textureNode === undefined ) {
  22041. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  22042. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  22043. textureNode.updateTexture();
  22044. this._previousTextureNodes[ name ] = textureNode;
  22045. }
  22046. return textureNode;
  22047. }
  22048. /**
  22049. * Returns a viewZ node of this pass.
  22050. *
  22051. * @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.
  22052. * @return {Node} The viewZ node.
  22053. */
  22054. getViewZNode( name = 'depth' ) {
  22055. let viewZNode = this._viewZNodes[ name ];
  22056. if ( viewZNode === undefined ) {
  22057. const cameraNear = this._cameraNear;
  22058. const cameraFar = this._cameraFar;
  22059. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  22060. }
  22061. return viewZNode;
  22062. }
  22063. /**
  22064. * Returns a linear depth node of this pass.
  22065. *
  22066. * @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.
  22067. * @return {Node} The linear depth node.
  22068. */
  22069. getLinearDepthNode( name = 'depth' ) {
  22070. let linearDepthNode = this._linearDepthNodes[ name ];
  22071. if ( linearDepthNode === undefined ) {
  22072. const cameraNear = this._cameraNear;
  22073. const cameraFar = this._cameraFar;
  22074. const viewZNode = this.getViewZNode( name );
  22075. // TODO: just if ( builder.camera.isPerspectiveCamera )
  22076. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  22077. }
  22078. return linearDepthNode;
  22079. }
  22080. setup( { renderer } ) {
  22081. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  22082. // Disable MSAA for WebGL backend for now
  22083. if ( renderer.backend.isWebGLBackend === true ) {
  22084. this.renderTarget.samples = 0;
  22085. }
  22086. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  22087. }
  22088. updateBefore( frame ) {
  22089. const { renderer } = frame;
  22090. const { scene, camera } = this;
  22091. this._pixelRatio = renderer.getPixelRatio();
  22092. const size = renderer.getSize( _size );
  22093. this.setSize( size.width, size.height );
  22094. const currentRenderTarget = renderer.getRenderTarget();
  22095. const currentMRT = renderer.getMRT();
  22096. this._cameraNear.value = camera.near;
  22097. this._cameraFar.value = camera.far;
  22098. for ( const name in this._previousTextures ) {
  22099. this.toggleTexture( name );
  22100. }
  22101. renderer.setRenderTarget( this.renderTarget );
  22102. renderer.setMRT( this._mrt );
  22103. renderer.render( scene, camera );
  22104. renderer.setRenderTarget( currentRenderTarget );
  22105. renderer.setMRT( currentMRT );
  22106. }
  22107. /**
  22108. * Sets the size of the pass's render target. Honors the pixel ratio.
  22109. *
  22110. * @param {Number} width - The width to set.
  22111. * @param {Number} height - The height to set.
  22112. */
  22113. setSize( width, height ) {
  22114. this._width = width;
  22115. this._height = height;
  22116. const effectiveWidth = this._width * this._pixelRatio;
  22117. const effectiveHeight = this._height * this._pixelRatio;
  22118. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  22119. }
  22120. /**
  22121. * Sets the pixel ratio the pass's render target and updates the size.
  22122. *
  22123. * @param {Number} pixelRatio - The pixel ratio to set.
  22124. */
  22125. setPixelRatio( pixelRatio ) {
  22126. this._pixelRatio = pixelRatio;
  22127. this.setSize( this._width, this._height );
  22128. }
  22129. /**
  22130. * Frees internal resources. Should be called when the node is no longer in use.
  22131. */
  22132. dispose() {
  22133. this.renderTarget.dispose();
  22134. }
  22135. }
  22136. PassNode.COLOR = 'color';
  22137. PassNode.DEPTH = 'depth';
  22138. /**
  22139. * TSL function for creating a pass node.
  22140. *
  22141. * @function
  22142. * @param {Scene} scene - A reference to the scene.
  22143. * @param {Camera} camera - A reference to the camera.
  22144. * @param {Object} options - Options for the internal render target.
  22145. * @returns {PassNode}
  22146. */
  22147. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  22148. /**
  22149. * TSL function for creating a pass texture node.
  22150. *
  22151. * @function
  22152. * @param {PassNode} pass - The pass node.
  22153. * @param {Texture} texture - The output texture.
  22154. * @returns {PassTextureNode}
  22155. */
  22156. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  22157. /**
  22158. * TSL function for creating a depth pass node.
  22159. *
  22160. * @function
  22161. * @param {Scene} scene - A reference to the scene.
  22162. * @param {Camera} camera - A reference to the camera.
  22163. * @param {Object} options - Options for the internal render target.
  22164. * @returns {PassNode}
  22165. */
  22166. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  22167. /** @module ToonOutlinePassNode **/
  22168. /**
  22169. * Represents a render pass for producing a toon outline effect on compatible objects.
  22170. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  22171. * will receive the outline.
  22172. *
  22173. * ```js
  22174. * const postProcessing = new PostProcessing( renderer );
  22175. *
  22176. * const scenePass = toonOutlinePass( scene, camera );
  22177. *
  22178. * postProcessing.outputNode = scenePass;
  22179. * ```
  22180. * @augments PassNode
  22181. */
  22182. class ToonOutlinePassNode extends PassNode {
  22183. static get type() {
  22184. return 'ToonOutlinePassNode';
  22185. }
  22186. /**
  22187. * Constructs a new outline pass node.
  22188. *
  22189. * @param {Scene} scene - A reference to the scene.
  22190. * @param {Camera} camera - A reference to the camera.
  22191. * @param {Node} colorNode - Defines the outline's color.
  22192. * @param {Node} thicknessNode - Defines the outline's thickness.
  22193. * @param {Node} alphaNode - Defines the outline's alpha.
  22194. */
  22195. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  22196. super( PassNode.COLOR, scene, camera );
  22197. /**
  22198. * Defines the outline's color.
  22199. *
  22200. * @type {Node}
  22201. */
  22202. this.colorNode = colorNode;
  22203. /**
  22204. * Defines the outline's thickness.
  22205. *
  22206. * @type {Node}
  22207. */
  22208. this.thicknessNode = thicknessNode;
  22209. /**
  22210. * Defines the outline's alpha.
  22211. *
  22212. * @type {Node}
  22213. */
  22214. this.alphaNode = alphaNode;
  22215. /**
  22216. * An internal material cache.
  22217. *
  22218. * @private
  22219. * @type {WeakMap<Material, NodeMaterial>}
  22220. */
  22221. this._materialCache = new WeakMap();
  22222. }
  22223. updateBefore( frame ) {
  22224. const { renderer } = frame;
  22225. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  22226. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  22227. // only render outline for supported materials
  22228. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  22229. if ( material.wireframe === false ) {
  22230. const outlineMaterial = this._getOutlineMaterial( material );
  22231. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  22232. }
  22233. }
  22234. // default
  22235. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  22236. } );
  22237. super.updateBefore( frame );
  22238. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  22239. }
  22240. /**
  22241. * Creates the material used for outline rendering.
  22242. *
  22243. * @private
  22244. * @return {NodeMaterial} The outline material.
  22245. */
  22246. _createMaterial() {
  22247. const material = new NodeMaterial();
  22248. material.isMeshToonOutlineMaterial = true;
  22249. material.name = 'Toon_Outline';
  22250. material.side = BackSide;
  22251. // vertex node
  22252. const outlineNormal = normalLocal.negate();
  22253. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  22254. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  22255. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  22256. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  22257. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  22258. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  22259. // color node
  22260. material.colorNode = vec4( this.colorNode, this.alphaNode );
  22261. return material;
  22262. }
  22263. /**
  22264. * For the given toon material, this method returns a corresponding
  22265. * outline material.
  22266. *
  22267. * @private
  22268. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  22269. * @return {NodeMaterial} The outline material.
  22270. */
  22271. _getOutlineMaterial( originalMaterial ) {
  22272. let outlineMaterial = this._materialCache.get( originalMaterial );
  22273. if ( outlineMaterial === undefined ) {
  22274. outlineMaterial = this._createMaterial();
  22275. this._materialCache.set( originalMaterial, outlineMaterial );
  22276. }
  22277. return outlineMaterial;
  22278. }
  22279. }
  22280. /**
  22281. * TSL function for creating a toon outline pass node.
  22282. *
  22283. * @function
  22284. * @param {Scene} scene - A reference to the scene.
  22285. * @param {Camera} camera - A reference to the camera.
  22286. * @param {Color} color - Defines the outline's color.
  22287. * @param {Number} [thickness=0.003] - Defines the outline's thickness.
  22288. * @param {Number} [alpha=1] - Defines the outline's alpha.
  22289. * @returns {ToonOutlinePassNode}
  22290. */
  22291. 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 ) ) );
  22292. /** @module ToneMappingFunctions **/
  22293. /**
  22294. * Linear tone mapping, exposure only.
  22295. *
  22296. * @method
  22297. * @param {Node<vec3>} color - The color that should be tone mapped.
  22298. * @param {Node<float>} exposure - The exposure.
  22299. * @return {Node<vec3>} The tone mapped color.
  22300. */
  22301. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22302. return color.mul( exposure ).clamp();
  22303. } ).setLayout( {
  22304. name: 'linearToneMapping',
  22305. type: 'vec3',
  22306. inputs: [
  22307. { name: 'color', type: 'vec3' },
  22308. { name: 'exposure', type: 'float' }
  22309. ]
  22310. } );
  22311. /**
  22312. * Reinhard tone mapping.
  22313. *
  22314. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  22315. *
  22316. * @method
  22317. * @param {Node<vec3>} color - The color that should be tone mapped.
  22318. * @param {Node<float>} exposure - The exposure.
  22319. * @return {Node<vec3>} The tone mapped color.
  22320. */
  22321. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22322. color = color.mul( exposure );
  22323. return color.div( color.add( 1.0 ) ).clamp();
  22324. } ).setLayout( {
  22325. name: 'reinhardToneMapping',
  22326. type: 'vec3',
  22327. inputs: [
  22328. { name: 'color', type: 'vec3' },
  22329. { name: 'exposure', type: 'float' }
  22330. ]
  22331. } );
  22332. /**
  22333. * Cineon tone mapping.
  22334. *
  22335. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  22336. *
  22337. * @method
  22338. * @param {Node<vec3>} color - The color that should be tone mapped.
  22339. * @param {Node<float>} exposure - The exposure.
  22340. * @return {Node<vec3>} The tone mapped color.
  22341. */
  22342. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22343. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  22344. color = color.mul( exposure );
  22345. color = color.sub( 0.004 ).max( 0.0 );
  22346. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  22347. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  22348. return a.div( b ).pow( 2.2 );
  22349. } ).setLayout( {
  22350. name: 'cineonToneMapping',
  22351. type: 'vec3',
  22352. inputs: [
  22353. { name: 'color', type: 'vec3' },
  22354. { name: 'exposure', type: 'float' }
  22355. ]
  22356. } );
  22357. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  22358. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  22359. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  22360. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  22361. return a.div( b );
  22362. } );
  22363. /**
  22364. * ACESFilmic tone mapping.
  22365. *
  22366. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  22367. *
  22368. * @method
  22369. * @param {Node<vec3>} color - The color that should be tone mapped.
  22370. * @param {Node<float>} exposure - The exposure.
  22371. * @return {Node<vec3>} The tone mapped color.
  22372. */
  22373. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22374. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  22375. const ACESInputMat = mat3(
  22376. 0.59719, 0.35458, 0.04823,
  22377. 0.07600, 0.90834, 0.01566,
  22378. 0.02840, 0.13383, 0.83777
  22379. );
  22380. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  22381. const ACESOutputMat = mat3(
  22382. 1.60475, - 0.53108, - 0.07367,
  22383. - 0.10208, 1.10813, - 0.00605,
  22384. - 0.00327, - 0.07276, 1.07602
  22385. );
  22386. color = color.mul( exposure ).div( 0.6 );
  22387. color = ACESInputMat.mul( color );
  22388. // Apply RRT and ODT
  22389. color = RRTAndODTFit( color );
  22390. color = ACESOutputMat.mul( color );
  22391. // Clamp to [0, 1]
  22392. return color.clamp();
  22393. } ).setLayout( {
  22394. name: 'acesFilmicToneMapping',
  22395. type: 'vec3',
  22396. inputs: [
  22397. { name: 'color', type: 'vec3' },
  22398. { name: 'exposure', type: 'float' }
  22399. ]
  22400. } );
  22401. 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 ) );
  22402. 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 ) );
  22403. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  22404. const x = vec3( x_immutable ).toVar();
  22405. const x2 = vec3( x.mul( x ) ).toVar();
  22406. const x4 = vec3( x2.mul( x2 ) ).toVar();
  22407. 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 ) ) ) );
  22408. } );
  22409. /**
  22410. * AgX tone mapping.
  22411. *
  22412. * @method
  22413. * @param {Node<vec3>} color - The color that should be tone mapped.
  22414. * @param {Node<float>} exposure - The exposure.
  22415. * @return {Node<vec3>} The tone mapped color.
  22416. */
  22417. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22418. const colortone = vec3( color ).toVar();
  22419. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  22420. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  22421. const AgxMinEv = float( - 12.47393 );
  22422. const AgxMaxEv = float( 4.026069 );
  22423. colortone.mulAssign( exposure );
  22424. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  22425. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  22426. colortone.assign( max$1( colortone, 1e-10 ) );
  22427. colortone.assign( log2( colortone ) );
  22428. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  22429. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  22430. colortone.assign( agxDefaultContrastApprox( colortone ) );
  22431. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  22432. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  22433. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  22434. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  22435. return colortone;
  22436. } ).setLayout( {
  22437. name: 'agxToneMapping',
  22438. type: 'vec3',
  22439. inputs: [
  22440. { name: 'color', type: 'vec3' },
  22441. { name: 'exposure', type: 'float' }
  22442. ]
  22443. } );
  22444. /**
  22445. * Neutral tone mapping.
  22446. *
  22447. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  22448. *
  22449. * @method
  22450. * @param {Node<vec3>} color - The color that should be tone mapped.
  22451. * @param {Node<float>} exposure - The exposure.
  22452. * @return {Node<vec3>} The tone mapped color.
  22453. */
  22454. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22455. const StartCompression = float( 0.8 - 0.04 );
  22456. const Desaturation = float( 0.15 );
  22457. color = color.mul( exposure );
  22458. const x = min$1( color.r, min$1( color.g, color.b ) );
  22459. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  22460. color.subAssign( offset );
  22461. const peak = max$1( color.r, max$1( color.g, color.b ) );
  22462. If( peak.lessThan( StartCompression ), () => {
  22463. return color;
  22464. } );
  22465. const d = sub( 1, StartCompression );
  22466. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  22467. color.mulAssign( newPeak.div( peak ) );
  22468. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  22469. return mix( color, vec3( newPeak ), g );
  22470. } ).setLayout( {
  22471. name: 'neutralToneMapping',
  22472. type: 'vec3',
  22473. inputs: [
  22474. { name: 'color', type: 'vec3' },
  22475. { name: 'exposure', type: 'float' }
  22476. ]
  22477. } );
  22478. /** @module CodeNode **/
  22479. /**
  22480. * This class represents native code sections. It is the base
  22481. * class for modules like {@link FunctionNode} which allows to implement
  22482. * functions with native shader languages.
  22483. *
  22484. * @augments Node
  22485. */
  22486. class CodeNode extends Node {
  22487. static get type() {
  22488. return 'CodeNode';
  22489. }
  22490. /**
  22491. * Constructs a new code node.
  22492. *
  22493. * @param {String} [code=''] - The native code.
  22494. * @param {Array<Node>} [includes=[]] - An array of includes.
  22495. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  22496. */
  22497. constructor( code = '', includes = [], language = '' ) {
  22498. super( 'code' );
  22499. /**
  22500. * This flag can be used for type testing.
  22501. *
  22502. * @type {Boolean}
  22503. * @readonly
  22504. * @default true
  22505. */
  22506. this.isCodeNode = true;
  22507. /**
  22508. * The native code.
  22509. *
  22510. * @type {String}
  22511. * @default ''
  22512. */
  22513. this.code = code;
  22514. /**
  22515. * An array of includes
  22516. *
  22517. * @type {Array<Node>}
  22518. * @default []
  22519. */
  22520. this.includes = includes;
  22521. /**
  22522. * The used language.
  22523. *
  22524. * @type {('js'|'wgsl'|'glsl')}
  22525. * @default ''
  22526. */
  22527. this.language = language;
  22528. }
  22529. /**
  22530. * The method is overwritten so it always returns `true`.
  22531. *
  22532. * @return {Boolean} Whether this node is global or not.
  22533. */
  22534. isGlobal() {
  22535. return true;
  22536. }
  22537. /**
  22538. * Sets the includes of this code node.
  22539. *
  22540. * @param {Array<Node>} includes - The includes to set.
  22541. * @return {CodeNode} A reference to this node.
  22542. */
  22543. setIncludes( includes ) {
  22544. this.includes = includes;
  22545. return this;
  22546. }
  22547. /**
  22548. * Returns the includes of this code node.
  22549. *
  22550. * @param {NodeBuilder} builder - The current node builder.
  22551. * @return {Array<Node>} The includes.
  22552. */
  22553. getIncludes( /*builder*/ ) {
  22554. return this.includes;
  22555. }
  22556. generate( builder ) {
  22557. const includes = this.getIncludes( builder );
  22558. for ( const include of includes ) {
  22559. include.build( builder );
  22560. }
  22561. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  22562. nodeCode.code = this.code;
  22563. return nodeCode.code;
  22564. }
  22565. serialize( data ) {
  22566. super.serialize( data );
  22567. data.code = this.code;
  22568. data.language = this.language;
  22569. }
  22570. deserialize( data ) {
  22571. super.deserialize( data );
  22572. this.code = data.code;
  22573. this.language = data.language;
  22574. }
  22575. }
  22576. /**
  22577. * TSL function for creating a code node.
  22578. *
  22579. * @function
  22580. * @param {String} [code=''] - The native code.
  22581. * @param {Array<Node>} [includes=[]] - An array of includes.
  22582. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  22583. * @returns {CodeNode}
  22584. */
  22585. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  22586. /**
  22587. * TSL function for creating a JS code node.
  22588. *
  22589. * @function
  22590. * @param {String} src - The native code.
  22591. * @param {Array<Node>} includes - An array of includes.
  22592. * @returns {CodeNode}
  22593. */
  22594. const js = ( src, includes ) => code( src, includes, 'js' );
  22595. /**
  22596. * TSL function for creating a WGSL code node.
  22597. *
  22598. * @function
  22599. * @param {String} src - The native code.
  22600. * @param {Array<Node>} includes - An array of includes.
  22601. * @returns {CodeNode}
  22602. */
  22603. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  22604. /**
  22605. * TSL function for creating a GLSL code node.
  22606. *
  22607. * @function
  22608. * @param {String} src - The native code.
  22609. * @param {Array<Node>} includes - An array of includes.
  22610. * @returns {CodeNode}
  22611. */
  22612. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  22613. /**
  22614. * This class represents a native shader function. It can be used to implement
  22615. * certain aspects of a node material with native shader code. There are two predefined
  22616. * TSL functions for easier usage.
  22617. *
  22618. * - `wgslFn`: Creates a WGSL function node.
  22619. * - `glslFn`: Creates a GLSL function node.
  22620. *
  22621. * A basic example with one include looks like so:
  22622. *
  22623. * ```js
  22624. * const desaturateWGSLFn = wgslFn( `
  22625. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  22626. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  22627. * return vec3<f32>( dot( lum, color ) );
  22628. * }`
  22629. *);
  22630. * const someWGSLFn = wgslFn( `
  22631. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  22632. * return desaturate( color );
  22633. * }
  22634. * `, [ desaturateWGSLFn ] );
  22635. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  22636. *```
  22637. * @augments CodeNode
  22638. */
  22639. class FunctionNode extends CodeNode {
  22640. static get type() {
  22641. return 'FunctionNode';
  22642. }
  22643. /**
  22644. * Constructs a new function node.
  22645. *
  22646. * @param {String} [code=''] - The native code.
  22647. * @param {Array<Node>} [includes=[]] - An array of includes.
  22648. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  22649. */
  22650. constructor( code = '', includes = [], language = '' ) {
  22651. super( code, includes, language );
  22652. }
  22653. getNodeType( builder ) {
  22654. return this.getNodeFunction( builder ).type;
  22655. }
  22656. /**
  22657. * Returns the inputs of this function node.
  22658. *
  22659. * @param {NodeBuilder} builder - The current node builder.
  22660. * @return {Array<NodeFunctionInput>} The inputs.
  22661. */
  22662. getInputs( builder ) {
  22663. return this.getNodeFunction( builder ).inputs;
  22664. }
  22665. /**
  22666. * Returns the node function for this function node.
  22667. *
  22668. * @param {NodeBuilder} builder - The current node builder.
  22669. * @return {NodeFunction} The node function.
  22670. */
  22671. getNodeFunction( builder ) {
  22672. const nodeData = builder.getDataFromNode( this );
  22673. let nodeFunction = nodeData.nodeFunction;
  22674. if ( nodeFunction === undefined ) {
  22675. nodeFunction = builder.parser.parseFunction( this.code );
  22676. nodeData.nodeFunction = nodeFunction;
  22677. }
  22678. return nodeFunction;
  22679. }
  22680. generate( builder, output ) {
  22681. super.generate( builder );
  22682. const nodeFunction = this.getNodeFunction( builder );
  22683. const name = nodeFunction.name;
  22684. const type = nodeFunction.type;
  22685. const nodeCode = builder.getCodeFromNode( this, type );
  22686. if ( name !== '' ) {
  22687. // use a custom property name
  22688. nodeCode.name = name;
  22689. }
  22690. const propertyName = builder.getPropertyName( nodeCode );
  22691. const code = this.getNodeFunction( builder ).getCode( propertyName );
  22692. nodeCode.code = code + '\n';
  22693. if ( output === 'property' ) {
  22694. return propertyName;
  22695. } else {
  22696. return builder.format( `${ propertyName }()`, type, output );
  22697. }
  22698. }
  22699. }
  22700. const nativeFn = ( code, includes = [], language = '' ) => {
  22701. for ( let i = 0; i < includes.length; i ++ ) {
  22702. const include = includes[ i ];
  22703. // TSL Function: glslFn, wgslFn
  22704. if ( typeof include === 'function' ) {
  22705. includes[ i ] = include.functionNode;
  22706. }
  22707. }
  22708. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  22709. const fn = ( ...params ) => functionNode.call( ...params );
  22710. fn.functionNode = functionNode;
  22711. return fn;
  22712. };
  22713. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  22714. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  22715. /** @module ScriptableValueNode **/
  22716. /**
  22717. * `ScriptableNode` uses this class to manage script inputs and outputs.
  22718. *
  22719. * @augments Node
  22720. */
  22721. class ScriptableValueNode extends Node {
  22722. static get type() {
  22723. return 'ScriptableValueNode';
  22724. }
  22725. /**
  22726. * Constructs a new scriptable node.
  22727. *
  22728. * @param {Any} [value=null] - The value.
  22729. */
  22730. constructor( value = null ) {
  22731. super();
  22732. /**
  22733. * A reference to the value.
  22734. *
  22735. * @private
  22736. * @default null
  22737. */
  22738. this._value = value;
  22739. /**
  22740. * Depending on the type of `_value`, this property might cache parsed data.
  22741. *
  22742. * @private
  22743. * @default null
  22744. */
  22745. this._cache = null;
  22746. /**
  22747. * If this node represents an input, this property represents the input type.
  22748. *
  22749. * @type {String?}
  22750. * @default null
  22751. */
  22752. this.inputType = null;
  22753. /**
  22754. * If this node represents an output, this property represents the output type.
  22755. *
  22756. * @type {String?}
  22757. * @default null
  22758. */
  22759. this.outputType = null;
  22760. /**
  22761. * An event dispatcher for managing events.
  22762. *
  22763. * @type {EventDispatcher}
  22764. */
  22765. this.events = new EventDispatcher();
  22766. /**
  22767. * This flag can be used for type testing.
  22768. *
  22769. * @type {Boolean}
  22770. * @readonly
  22771. * @default true
  22772. */
  22773. this.isScriptableValueNode = true;
  22774. }
  22775. /**
  22776. * Whether this node represents an output or not.
  22777. *
  22778. * @type {Boolean}
  22779. * @readonly
  22780. * @default true
  22781. */
  22782. get isScriptableOutputNode() {
  22783. return this.outputType !== null;
  22784. }
  22785. set value( val ) {
  22786. if ( this._value === val ) return;
  22787. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  22788. URL.revokeObjectURL( this._cache );
  22789. this._cache = null;
  22790. }
  22791. this._value = val;
  22792. this.events.dispatchEvent( { type: 'change' } );
  22793. this.refresh();
  22794. }
  22795. /**
  22796. * The node's value.
  22797. *
  22798. * @type {Any}
  22799. */
  22800. get value() {
  22801. return this._value;
  22802. }
  22803. /**
  22804. * Dispatches the `refresh` event.
  22805. */
  22806. refresh() {
  22807. this.events.dispatchEvent( { type: 'refresh' } );
  22808. }
  22809. /**
  22810. * The `value` property usually represents a node or even binary data in form of array buffers.
  22811. * In this case, this method tries to return the actual value behind the complex type.
  22812. *
  22813. * @return {Any} The value.
  22814. */
  22815. getValue() {
  22816. const value = this.value;
  22817. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  22818. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  22819. } else if ( value && value.value !== null && value.value !== undefined && (
  22820. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  22821. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  22822. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  22823. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  22824. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  22825. ( this.inputType === 'Color' && value.value.isColor ) ||
  22826. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  22827. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  22828. ) ) {
  22829. return value.value;
  22830. }
  22831. return this._cache || value;
  22832. }
  22833. /**
  22834. * Overwritten since the node type is inferred from the value.
  22835. *
  22836. * @param {NodeBuilder} builder - The current node builder.
  22837. * @return {String} The node type.
  22838. */
  22839. getNodeType( builder ) {
  22840. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  22841. }
  22842. setup() {
  22843. return this.value && this.value.isNode ? this.value : float();
  22844. }
  22845. serialize( data ) {
  22846. super.serialize( data );
  22847. if ( this.value !== null ) {
  22848. if ( this.inputType === 'ArrayBuffer' ) {
  22849. data.value = arrayBufferToBase64( this.value );
  22850. } else {
  22851. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  22852. }
  22853. } else {
  22854. data.value = null;
  22855. }
  22856. data.inputType = this.inputType;
  22857. data.outputType = this.outputType;
  22858. }
  22859. deserialize( data ) {
  22860. super.deserialize( data );
  22861. let value = null;
  22862. if ( data.value !== null ) {
  22863. if ( data.inputType === 'ArrayBuffer' ) {
  22864. value = base64ToArrayBuffer( data.value );
  22865. } else if ( data.inputType === 'Texture' ) {
  22866. value = data.meta.textures[ data.value ];
  22867. } else {
  22868. value = data.meta.nodes[ data.value ] || null;
  22869. }
  22870. }
  22871. this.value = value;
  22872. this.inputType = data.inputType;
  22873. this.outputType = data.outputType;
  22874. }
  22875. }
  22876. /**
  22877. * TSL function for creating a scriptable value node.
  22878. *
  22879. * @function
  22880. * @param {Any} [value=null] - The value.
  22881. * @returns {ScriptableValueNode}
  22882. */
  22883. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  22884. /** @module ScriptableNode **/
  22885. /**
  22886. * A Map-like data structure for managing resources of scriptable nodes.
  22887. *
  22888. * @augments Map
  22889. */
  22890. class Resources extends Map {
  22891. get( key, callback = null, ...params ) {
  22892. if ( this.has( key ) ) return super.get( key );
  22893. if ( callback !== null ) {
  22894. const value = callback( ...params );
  22895. this.set( key, value );
  22896. return value;
  22897. }
  22898. }
  22899. }
  22900. class Parameters {
  22901. constructor( scriptableNode ) {
  22902. this.scriptableNode = scriptableNode;
  22903. }
  22904. get parameters() {
  22905. return this.scriptableNode.parameters;
  22906. }
  22907. get layout() {
  22908. return this.scriptableNode.getLayout();
  22909. }
  22910. getInputLayout( id ) {
  22911. return this.scriptableNode.getInputLayout( id );
  22912. }
  22913. get( name ) {
  22914. const param = this.parameters[ name ];
  22915. const value = param ? param.getValue() : null;
  22916. return value;
  22917. }
  22918. }
  22919. /**
  22920. * Defines the resources (e.g. namespaces) of scriptable nodes.
  22921. *
  22922. * @type {Resources}
  22923. */
  22924. const ScriptableNodeResources = new Resources();
  22925. /**
  22926. * This type of node allows to implement nodes with custom scripts. The script
  22927. * section is represented as an instance of `CodeNode` written with JavaScript.
  22928. * The script itself must adhere to a specific structure.
  22929. *
  22930. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  22931. * - layout: The layout object defines the script's interface (inputs and outputs).
  22932. *
  22933. * ```js
  22934. * ScriptableNodeResources.set( 'TSL', TSL );
  22935. *
  22936. * const scriptableNode = scriptable( js( `
  22937. * layout = {
  22938. * outputType: 'node',
  22939. * elements: [
  22940. * { name: 'source', inputType: 'node' },
  22941. * ]
  22942. * };
  22943. *
  22944. * const { mul, oscSine } = TSL;
  22945. *
  22946. * function main() {
  22947. * const source = parameters.get( 'source' ) || float();
  22948. * return mul( source, oscSine() ) );
  22949. * }
  22950. *
  22951. * ` ) );
  22952. *
  22953. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  22954. *
  22955. * const material = new THREE.MeshBasicNodeMaterial();
  22956. * material.colorNode = scriptableNode;
  22957. * ```
  22958. *
  22959. * @augments Node
  22960. */
  22961. class ScriptableNode extends Node {
  22962. static get type() {
  22963. return 'ScriptableNode';
  22964. }
  22965. /**
  22966. * Constructs a new scriptable node.
  22967. *
  22968. * @param {CodeNode?} [codeNode=null] - The code node.
  22969. * @param {Object} [parameters={}] - The parameters definition.
  22970. */
  22971. constructor( codeNode = null, parameters = {} ) {
  22972. super();
  22973. /**
  22974. * The code node.
  22975. *
  22976. * @type {CodeNode?}
  22977. * @default null
  22978. */
  22979. this.codeNode = codeNode;
  22980. /**
  22981. * The parameters definition.
  22982. *
  22983. * @type {Object}
  22984. * @default {}
  22985. */
  22986. this.parameters = parameters;
  22987. this._local = new Resources();
  22988. this._output = scriptableValue();
  22989. this._outputs = {};
  22990. this._source = this.source;
  22991. this._method = null;
  22992. this._object = null;
  22993. this._value = null;
  22994. this._needsOutputUpdate = true;
  22995. this.onRefresh = this.onRefresh.bind( this );
  22996. /**
  22997. * This flag can be used for type testing.
  22998. *
  22999. * @type {Boolean}
  23000. * @readonly
  23001. * @default true
  23002. */
  23003. this.isScriptableNode = true;
  23004. }
  23005. /**
  23006. * The source code of the scriptable node.
  23007. *
  23008. * @type {String}
  23009. */
  23010. get source() {
  23011. return this.codeNode ? this.codeNode.code : '';
  23012. }
  23013. /**
  23014. * Sets the reference of a local script variable.
  23015. *
  23016. * @param {String} name - The variable name.
  23017. * @param {Object} value - The reference to set.
  23018. * @return {Resources} The resource map
  23019. */
  23020. setLocal( name, value ) {
  23021. return this._local.set( name, value );
  23022. }
  23023. /**
  23024. * Gets the value of a local script variable.
  23025. *
  23026. * @param {String} name - The variable name.
  23027. * @return {Object} The value.
  23028. */
  23029. getLocal( name ) {
  23030. return this._local.get( name );
  23031. }
  23032. /**
  23033. * Event listener for the `refresh` event.
  23034. */
  23035. onRefresh() {
  23036. this._refresh();
  23037. }
  23038. /**
  23039. * Returns an input from the layout with the given id/name.
  23040. *
  23041. * @param {String} id - The id/name of the input.
  23042. * @return {Object} The element entry.
  23043. */
  23044. getInputLayout( id ) {
  23045. for ( const element of this.getLayout() ) {
  23046. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  23047. return element;
  23048. }
  23049. }
  23050. }
  23051. /**
  23052. * Returns an output from the layout with the given id/name.
  23053. *
  23054. * @param {String} id - The id/name of the output.
  23055. * @return {Object} The element entry.
  23056. */
  23057. getOutputLayout( id ) {
  23058. for ( const element of this.getLayout() ) {
  23059. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  23060. return element;
  23061. }
  23062. }
  23063. }
  23064. /**
  23065. * Defines a script output for the given name and value.
  23066. *
  23067. * @param {String} name - The name of the output.
  23068. * @param {Node} value - The node value.
  23069. * @return {ScriptableNode} A reference to this node.
  23070. */
  23071. setOutput( name, value ) {
  23072. const outputs = this._outputs;
  23073. if ( outputs[ name ] === undefined ) {
  23074. outputs[ name ] = scriptableValue( value );
  23075. } else {
  23076. outputs[ name ].value = value;
  23077. }
  23078. return this;
  23079. }
  23080. /**
  23081. * Returns a script output for the given name.
  23082. *
  23083. * @param {String} name - The name of the output.
  23084. * @return {ScriptableValueNode} The node value.
  23085. */
  23086. getOutput( name ) {
  23087. return this._outputs[ name ];
  23088. }
  23089. /**
  23090. * Returns a parameter for the given name
  23091. *
  23092. * @param {String} name - The name of the parameter.
  23093. * @return {ScriptableValueNode} The node value.
  23094. */
  23095. getParameter( name ) {
  23096. return this.parameters[ name ];
  23097. }
  23098. /**
  23099. * Sets a value for the given parameter name.
  23100. *
  23101. * @param {String} name - The parameter name.
  23102. * @param {Any} value - The parameter value.
  23103. * @return {ScriptableNode} A reference to this node.
  23104. */
  23105. setParameter( name, value ) {
  23106. const parameters = this.parameters;
  23107. if ( value && value.isScriptableNode ) {
  23108. this.deleteParameter( name );
  23109. parameters[ name ] = value;
  23110. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  23111. } else if ( value && value.isScriptableValueNode ) {
  23112. this.deleteParameter( name );
  23113. parameters[ name ] = value;
  23114. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  23115. } else if ( parameters[ name ] === undefined ) {
  23116. parameters[ name ] = scriptableValue( value );
  23117. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  23118. } else {
  23119. parameters[ name ].value = value;
  23120. }
  23121. return this;
  23122. }
  23123. /**
  23124. * Returns the value of this node which is the value of
  23125. * the default output.
  23126. *
  23127. * @return {Node} The value.
  23128. */
  23129. getValue() {
  23130. return this.getDefaultOutput().getValue();
  23131. }
  23132. /**
  23133. * Deletes a parameter from the script.
  23134. *
  23135. * @param {String} name - The parameter to remove.
  23136. * @return {ScriptableNode} A reference to this node.
  23137. */
  23138. deleteParameter( name ) {
  23139. let valueNode = this.parameters[ name ];
  23140. if ( valueNode ) {
  23141. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  23142. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  23143. }
  23144. return this;
  23145. }
  23146. /**
  23147. * Deletes all parameters from the script.
  23148. *
  23149. * @return {ScriptableNode} A reference to this node.
  23150. */
  23151. clearParameters() {
  23152. for ( const name of Object.keys( this.parameters ) ) {
  23153. this.deleteParameter( name );
  23154. }
  23155. this.needsUpdate = true;
  23156. return this;
  23157. }
  23158. /**
  23159. * Calls a function from the script.
  23160. *
  23161. * @param {String} name - The function name.
  23162. * @param {...Any} params - A list of parameters.
  23163. * @return {Any} The result of the function call.
  23164. */
  23165. call( name, ...params ) {
  23166. const object = this.getObject();
  23167. const method = object[ name ];
  23168. if ( typeof method === 'function' ) {
  23169. return method( ...params );
  23170. }
  23171. }
  23172. /**
  23173. * Asynchronously calls a function from the script.
  23174. *
  23175. * @param {String} name - The function name.
  23176. * @param {...Any} params - A list of parameters.
  23177. * @return {Any} The result of the function call.
  23178. */
  23179. async callAsync( name, ...params ) {
  23180. const object = this.getObject();
  23181. const method = object[ name ];
  23182. if ( typeof method === 'function' ) {
  23183. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  23184. }
  23185. }
  23186. /**
  23187. * Overwritten since the node types is inferred from the script's output.
  23188. *
  23189. * @param {NodeBuilder} builder - The current node builder
  23190. * @return {String} The node type.
  23191. */
  23192. getNodeType( builder ) {
  23193. return this.getDefaultOutputNode().getNodeType( builder );
  23194. }
  23195. /**
  23196. * Refreshes the script node.
  23197. *
  23198. * @param {String?} [output=null] - An optional output.
  23199. */
  23200. refresh( output = null ) {
  23201. if ( output !== null ) {
  23202. this.getOutput( output ).refresh();
  23203. } else {
  23204. this._refresh();
  23205. }
  23206. }
  23207. /**
  23208. * Returns an object representation of the script.
  23209. *
  23210. * @return {Object} The result object.
  23211. */
  23212. getObject() {
  23213. if ( this.needsUpdate ) this.dispose();
  23214. if ( this._object !== null ) return this._object;
  23215. //
  23216. const refresh = () => this.refresh();
  23217. const setOutput = ( id, value ) => this.setOutput( id, value );
  23218. const parameters = new Parameters( this );
  23219. const THREE = ScriptableNodeResources.get( 'THREE' );
  23220. const TSL = ScriptableNodeResources.get( 'TSL' );
  23221. const method = this.getMethod();
  23222. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  23223. this._object = method( ...params );
  23224. const layout = this._object.layout;
  23225. if ( layout ) {
  23226. if ( layout.cache === false ) {
  23227. this._local.clear();
  23228. }
  23229. // default output
  23230. this._output.outputType = layout.outputType || null;
  23231. if ( Array.isArray( layout.elements ) ) {
  23232. for ( const element of layout.elements ) {
  23233. const id = element.id || element.name;
  23234. if ( element.inputType ) {
  23235. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  23236. this.getParameter( id ).inputType = element.inputType;
  23237. }
  23238. if ( element.outputType ) {
  23239. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  23240. this.getOutput( id ).outputType = element.outputType;
  23241. }
  23242. }
  23243. }
  23244. }
  23245. return this._object;
  23246. }
  23247. deserialize( data ) {
  23248. super.deserialize( data );
  23249. for ( const name in this.parameters ) {
  23250. let valueNode = this.parameters[ name ];
  23251. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  23252. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  23253. }
  23254. }
  23255. /**
  23256. * Returns the layout of the script.
  23257. *
  23258. * @return {Object} The script's layout.
  23259. */
  23260. getLayout() {
  23261. return this.getObject().layout;
  23262. }
  23263. /**
  23264. * Returns default node output of the script.
  23265. *
  23266. * @return {Node} The default node output.
  23267. */
  23268. getDefaultOutputNode() {
  23269. const output = this.getDefaultOutput().value;
  23270. if ( output && output.isNode ) {
  23271. return output;
  23272. }
  23273. return float();
  23274. }
  23275. /**
  23276. * Returns default output of the script.
  23277. *
  23278. * @return {ScriptableValueNode} The default output.
  23279. */
  23280. getDefaultOutput() {
  23281. return this._exec()._output;
  23282. }
  23283. /**
  23284. * Returns a function created from the node's script.
  23285. *
  23286. * @return {Function} The function representing the node's code.
  23287. */
  23288. getMethod() {
  23289. if ( this.needsUpdate ) this.dispose();
  23290. if ( this._method !== null ) return this._method;
  23291. //
  23292. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  23293. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  23294. const properties = interfaceProps.join( ', ' );
  23295. const declarations = 'var ' + properties + '; var output = {};\n';
  23296. const returns = '\nreturn { ...output, ' + properties + ' };';
  23297. const code = declarations + this.codeNode.code + returns;
  23298. //
  23299. this._method = new Function( ...parametersProps, code );
  23300. return this._method;
  23301. }
  23302. /**
  23303. * Frees all internal resources.
  23304. */
  23305. dispose() {
  23306. if ( this._method === null ) return;
  23307. if ( this._object && typeof this._object.dispose === 'function' ) {
  23308. this._object.dispose();
  23309. }
  23310. this._method = null;
  23311. this._object = null;
  23312. this._source = null;
  23313. this._value = null;
  23314. this._needsOutputUpdate = true;
  23315. this._output.value = null;
  23316. this._outputs = {};
  23317. }
  23318. setup() {
  23319. return this.getDefaultOutputNode();
  23320. }
  23321. getCacheKey( force ) {
  23322. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  23323. for ( const param in this.parameters ) {
  23324. values.push( this.parameters[ param ].getCacheKey( force ) );
  23325. }
  23326. return hashArray( values );
  23327. }
  23328. set needsUpdate( value ) {
  23329. if ( value === true ) this.dispose();
  23330. }
  23331. get needsUpdate() {
  23332. return this.source !== this._source;
  23333. }
  23334. /**
  23335. * Executes the `main` function of the script.
  23336. *
  23337. * @private
  23338. * @return {ScriptableNode} A reference to this node.
  23339. */
  23340. _exec() {
  23341. if ( this.codeNode === null ) return this;
  23342. if ( this._needsOutputUpdate === true ) {
  23343. this._value = this.call( 'main' );
  23344. this._needsOutputUpdate = false;
  23345. }
  23346. this._output.value = this._value;
  23347. return this;
  23348. }
  23349. /**
  23350. * Executes the refresh.
  23351. *
  23352. * @private
  23353. */
  23354. _refresh() {
  23355. this.needsUpdate = true;
  23356. this._exec();
  23357. this._output.refresh();
  23358. }
  23359. }
  23360. /**
  23361. * TSL function for creating a scriptable node.
  23362. *
  23363. * @function
  23364. * @param {CodeNode?} [codeNode=null] - The code node.
  23365. * @param {Object} [parameters={}] - The parameters definition.
  23366. * @returns {ScriptableNode}
  23367. */
  23368. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  23369. /** @module Fog **/
  23370. /**
  23371. * Returns a node that represents the `z` coordinate in view space
  23372. * for the current fragment. It's a different representation of the
  23373. * default depth value.
  23374. *
  23375. * This value can be part of a computation that defines how the fog
  23376. * density increases when moving away from the camera.
  23377. *
  23378. * @param {NodeBuilder} builder - The current node builder.
  23379. * @return {Node} The viewZ node.
  23380. */
  23381. function getViewZNode( builder ) {
  23382. let viewZ;
  23383. const getViewZ = builder.context.getViewZ;
  23384. if ( getViewZ !== undefined ) {
  23385. viewZ = getViewZ( this );
  23386. }
  23387. return ( viewZ || positionView.z ).negate();
  23388. }
  23389. /**
  23390. * Constructs a new range factor node.
  23391. *
  23392. * @function
  23393. * @param {Node} near - Defines the near value.
  23394. * @param {Node} far - Defines the far value.
  23395. */
  23396. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  23397. const viewZ = getViewZNode( builder );
  23398. return smoothstep( near, far, viewZ );
  23399. } );
  23400. /**
  23401. * Represents an exponential squared fog. This type of fog gives
  23402. * a clear view near the camera and a faster than exponentially
  23403. * densening fog farther from the camera.
  23404. *
  23405. * @function
  23406. * @param {Node} density - Defines the fog density.
  23407. */
  23408. const densityFogFactor = Fn( ( [ density ], builder ) => {
  23409. const viewZ = getViewZNode( builder );
  23410. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  23411. } );
  23412. /**
  23413. * This class can be used to configure a fog for the scene.
  23414. * Nodes of this type are assigned to `Scene.fogNode`.
  23415. *
  23416. * @function
  23417. * @param {Node} color - Defines the color of the fog.
  23418. * @param {Node} factor - Defines how the fog is factored in the scene.
  23419. */
  23420. const fog = Fn( ( [ color, factor ] ) => {
  23421. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  23422. } );
  23423. // Deprecated
  23424. function rangeFog( color, near, far ) { // @deprecated, r171
  23425. console.warn( 'THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  23426. return fog( color, rangeFogFactor( near, far ) );
  23427. }
  23428. function densityFog( color, density ) { // @deprecated, r171
  23429. console.warn( 'THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  23430. return fog( color, densityFogFactor( density ) );
  23431. }
  23432. /** @module RangeNode **/
  23433. let min = null;
  23434. let max = null;
  23435. /**
  23436. * `RangeNode` generates random instanced attribute data in a defined range.
  23437. * An exemplary use case for this utility node is to generate random per-instance
  23438. * colors:
  23439. * ```js
  23440. * const material = new MeshBasicNodeMaterial();
  23441. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  23442. * const mesh = new InstancedMesh( geometry, material, count );
  23443. * ```
  23444. * @augments Node
  23445. */
  23446. class RangeNode extends Node {
  23447. static get type() {
  23448. return 'RangeNode';
  23449. }
  23450. /**
  23451. * Constructs a new range node.
  23452. *
  23453. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  23454. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  23455. */
  23456. constructor( minNode = float(), maxNode = float() ) {
  23457. super();
  23458. /**
  23459. * A node defining the lower bound of the range.
  23460. *
  23461. * @type {Node<any>}
  23462. * @default float()
  23463. */
  23464. this.minNode = minNode;
  23465. /**
  23466. * A node defining the upper bound of the range.
  23467. *
  23468. * @type {Node<any>}
  23469. * @default float()
  23470. */
  23471. this.maxNode = maxNode;
  23472. }
  23473. /**
  23474. * Returns the vector length which is computed based on the range definition.
  23475. *
  23476. * @param {NodeBuilder} builder - The current node builder.
  23477. * @return {Number} The vector length.
  23478. */
  23479. getVectorLength( builder ) {
  23480. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  23481. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  23482. return minLength > maxLength ? minLength : maxLength;
  23483. }
  23484. /**
  23485. * This method is overwritten since the node type is inferred from range definition.
  23486. *
  23487. * @param {NodeBuilder} builder - The current node builder.
  23488. * @return {String} The node type.
  23489. */
  23490. getNodeType( builder ) {
  23491. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  23492. }
  23493. setup( builder ) {
  23494. const object = builder.object;
  23495. let output = null;
  23496. if ( object.count > 1 ) {
  23497. const minValue = this.minNode.value;
  23498. const maxValue = this.maxNode.value;
  23499. const minLength = builder.getTypeLength( getValueType( minValue ) );
  23500. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  23501. min = min || new Vector4();
  23502. max = max || new Vector4();
  23503. min.setScalar( 0 );
  23504. max.setScalar( 0 );
  23505. if ( minLength === 1 ) min.setScalar( minValue );
  23506. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  23507. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  23508. if ( maxLength === 1 ) max.setScalar( maxValue );
  23509. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  23510. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  23511. const stride = 4;
  23512. const length = stride * object.count;
  23513. const array = new Float32Array( length );
  23514. for ( let i = 0; i < length; i ++ ) {
  23515. const index = i % stride;
  23516. const minElementValue = min.getComponent( index );
  23517. const maxElementValue = max.getComponent( index );
  23518. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  23519. }
  23520. const nodeType = this.getNodeType( builder );
  23521. if ( object.count <= 4096 ) {
  23522. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  23523. } else {
  23524. // TODO: Improve anonymous buffer attribute creation removing this part
  23525. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  23526. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  23527. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  23528. }
  23529. } else {
  23530. output = float( 0 );
  23531. }
  23532. return output;
  23533. }
  23534. }
  23535. /**
  23536. * TSL function for creating a range node.
  23537. *
  23538. * @function
  23539. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  23540. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  23541. * @returns {RangeNode}
  23542. */
  23543. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  23544. /** @module ComputeBuiltinNode **/
  23545. /**
  23546. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  23547. * about the currently running dispatch and/or the device it is running on.
  23548. *
  23549. * This node can only be used with a WebGPU backend.
  23550. *
  23551. * @augments Node
  23552. */
  23553. class ComputeBuiltinNode extends Node {
  23554. static get type() {
  23555. return 'ComputeBuiltinNode';
  23556. }
  23557. /**
  23558. * Constructs a new compute builtin node.
  23559. *
  23560. * @param {String} builtinName - The built-in name.
  23561. * @param {String} nodeType - The node type.
  23562. */
  23563. constructor( builtinName, nodeType ) {
  23564. super( nodeType );
  23565. /**
  23566. * The built-in name.
  23567. *
  23568. * @private
  23569. * @type {String}
  23570. */
  23571. this._builtinName = builtinName;
  23572. }
  23573. /**
  23574. * This method is overwritten since hash is derived from the built-in name.
  23575. *
  23576. * @param {NodeBuilder} builder - The current node builder.
  23577. * @return {String} The hash.
  23578. */
  23579. getHash( builder ) {
  23580. return this.getBuiltinName( builder );
  23581. }
  23582. /**
  23583. * This method is overwritten since the node type is simply derived from `nodeType`..
  23584. *
  23585. * @param {NodeBuilder} builder - The current node builder.
  23586. * @return {String} The node type.
  23587. */
  23588. getNodeType( /*builder*/ ) {
  23589. return this.nodeType;
  23590. }
  23591. /**
  23592. * Sets the builtin name.
  23593. *
  23594. * @param {String} builtinName - The built-in name.
  23595. * @return {ComputeBuiltinNode} A reference to this node.
  23596. */
  23597. setBuiltinName( builtinName ) {
  23598. this._builtinName = builtinName;
  23599. return this;
  23600. }
  23601. /**
  23602. * Returns the builtin name.
  23603. *
  23604. * @param {NodeBuilder} builder - The current node builder.
  23605. * @return {String} The builtin name.
  23606. */
  23607. getBuiltinName( /*builder*/ ) {
  23608. return this._builtinName;
  23609. }
  23610. /**
  23611. * Whether the current node builder has the builtin or not.
  23612. *
  23613. * @param {NodeBuilder} builder - The current node builder.
  23614. */
  23615. hasBuiltin( builder ) {
  23616. builder.hasBuiltin( this._builtinName );
  23617. }
  23618. generate( builder, output ) {
  23619. const builtinName = this.getBuiltinName( builder );
  23620. const nodeType = this.getNodeType( builder );
  23621. if ( builder.shaderStage === 'compute' ) {
  23622. return builder.format( builtinName, nodeType, output );
  23623. } else {
  23624. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  23625. return builder.generateConst( nodeType );
  23626. }
  23627. }
  23628. serialize( data ) {
  23629. super.serialize( data );
  23630. data.global = this.global;
  23631. data._builtinName = this._builtinName;
  23632. }
  23633. deserialize( data ) {
  23634. super.deserialize( data );
  23635. this.global = data.global;
  23636. this._builtinName = data._builtinName;
  23637. }
  23638. }
  23639. /**
  23640. * TSL function for creating a compute builtin node.
  23641. *
  23642. * @function
  23643. * @param {String} name - The built-in name.
  23644. * @param {String} nodeType - The node type.
  23645. * @returns {ComputeBuiltinNode}
  23646. */
  23647. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  23648. /**
  23649. * TSL function for creating a `numWorkgroups` builtin node.
  23650. * Represents the number of workgroups dispatched by the compute shader.
  23651. * ```js
  23652. * // Run 512 invocations/threads with a workgroup size of 128.
  23653. * const computeFn = Fn(() => {
  23654. *
  23655. * // numWorkgroups.x = 4
  23656. * storageBuffer.element(0).assign(numWorkgroups.x)
  23657. *
  23658. * })().compute(512, [128]);
  23659. *
  23660. * // Run 512 invocations/threads with the default workgroup size of 64.
  23661. * const computeFn = Fn(() => {
  23662. *
  23663. * // numWorkgroups.x = 8
  23664. * storageBuffer.element(0).assign(numWorkgroups.x)
  23665. *
  23666. * })().compute(512);
  23667. * ```
  23668. *
  23669. * @function
  23670. * @returns {ComputeBuiltinNode<uvec3>}
  23671. */
  23672. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  23673. /**
  23674. * TSL function for creating a `workgroupId` builtin node.
  23675. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  23676. * ```js
  23677. * // Execute 12 compute threads with a workgroup size of 3.
  23678. * const computeFn = Fn( () => {
  23679. *
  23680. * If( workgroupId.x.modInt( 2 ).equal( 0 ), () => {
  23681. *
  23682. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  23683. *
  23684. * } ).Else( () => {
  23685. *
  23686. * storageBuffer.element( instanceIndex ).assign( 0 );
  23687. *
  23688. * } );
  23689. *
  23690. * } )().compute( 12, [ 3 ] );
  23691. *
  23692. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  23693. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  23694. * ```
  23695. *
  23696. * @function
  23697. * @returns {ComputeBuiltinNode<uvec3>}
  23698. */
  23699. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  23700. /**
  23701. * TSL function for creating a `localId` builtin node. A non-linearized 3-dimensional
  23702. * representation of the current invocation's position within a 3D workgroup grid.
  23703. *
  23704. * @function
  23705. * @returns {ComputeBuiltinNode<uvec3>}
  23706. */
  23707. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  23708. /**
  23709. * TSL function for creating a `subgroupSize` builtin node. A device dependent variable
  23710. * that exposes the size of the current invocation's subgroup.
  23711. *
  23712. * @function
  23713. * @returns {ComputeBuiltinNode<uint>}
  23714. */
  23715. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  23716. /** @module BarrierNode **/
  23717. /**
  23718. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  23719. *
  23720. * This node can only be used with a WebGPU backend.
  23721. *
  23722. * @augments Node
  23723. */
  23724. class BarrierNode extends Node {
  23725. /**
  23726. * Constructs a new barrier node.
  23727. *
  23728. * @param {String} scope - The scope defines the behavior of the node.
  23729. */
  23730. constructor( scope ) {
  23731. super();
  23732. this.scope = scope;
  23733. }
  23734. generate( builder ) {
  23735. const { scope } = this;
  23736. const { renderer } = builder;
  23737. if ( renderer.backend.isWebGLBackend === true ) {
  23738. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  23739. } else {
  23740. builder.addLineFlowCode( `${scope}Barrier()`, this );
  23741. }
  23742. }
  23743. }
  23744. /**
  23745. * TSL function for creating a barrier node.
  23746. *
  23747. * @function
  23748. * @param {String} scope - The scope defines the behavior of the node..
  23749. * @returns {BarrierNode}
  23750. */
  23751. const barrier = nodeProxy( BarrierNode );
  23752. /**
  23753. * TSL function for creating a workgroup barrier. All compute shader
  23754. * invocations must wait for each invocation within a workgroup to
  23755. * complete before the barrier can be surpassed.
  23756. *
  23757. * @function
  23758. * @returns {BarrierNode}
  23759. */
  23760. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  23761. /**
  23762. * TSL function for creating a storage barrier. All invocations must
  23763. * wait for each access to variables within the 'storage' address space
  23764. * to complete before the barrier can be passed.
  23765. *
  23766. * @function
  23767. * @returns {BarrierNode}
  23768. */
  23769. const storageBarrier = () => barrier( 'storage' ).append();
  23770. /**
  23771. * TSL function for creating a texture barrier. All invocations must
  23772. * wait for each access to variables within the 'texture' address space
  23773. * to complete before the barrier can be passed.
  23774. *
  23775. * @function
  23776. * @returns {BarrierNode}
  23777. */
  23778. const textureBarrier = () => barrier( 'texture' ).append();
  23779. /** @module WorkgroupInfoNode **/
  23780. /**
  23781. * Represents an element of a 'workgroup' scoped buffer.
  23782. *
  23783. * @augments ArrayElementNode
  23784. */
  23785. class WorkgroupInfoElementNode extends ArrayElementNode {
  23786. /**
  23787. * Constructs a new workgroup info element node.
  23788. *
  23789. * @param {Node} workgroupInfoNode - The workgroup info node.
  23790. * @param {Node} indexNode - The index node that defines the element access.
  23791. */
  23792. constructor( workgroupInfoNode, indexNode ) {
  23793. super( workgroupInfoNode, indexNode );
  23794. /**
  23795. * This flag can be used for type testing.
  23796. *
  23797. * @type {Boolean}
  23798. * @readonly
  23799. * @default true
  23800. */
  23801. this.isWorkgroupInfoElementNode = true;
  23802. }
  23803. generate( builder, output ) {
  23804. let snippet;
  23805. const isAssignContext = builder.context.assign;
  23806. snippet = super.generate( builder );
  23807. if ( isAssignContext !== true ) {
  23808. const type = this.getNodeType( builder );
  23809. snippet = builder.format( snippet, type, output );
  23810. }
  23811. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  23812. return snippet;
  23813. }
  23814. }
  23815. /**
  23816. * A node allowing the user to create a 'workgroup' scoped buffer within the
  23817. * context of a compute shader. Typically, workgroup scoped buffers are
  23818. * created to hold data that is transferred from a global storage scope into
  23819. * a local workgroup scope. For invocations within a workgroup, data
  23820. * access speeds on 'workgroup' scoped buffers can be significantly faster
  23821. * than similar access operations on globally accessible storage buffers.
  23822. *
  23823. * This node can only be used with a WebGPU backend.
  23824. *
  23825. * @augments Node
  23826. */
  23827. class WorkgroupInfoNode extends Node {
  23828. /**
  23829. * Constructs a new buffer scoped to type scope.
  23830. *
  23831. * @param {String} scope - TODO.
  23832. * @param {String} bufferType - The data type of a 'workgroup' scoped buffer element.
  23833. * @param {Number} [bufferCount=0] - The number of elements in the buffer.
  23834. */
  23835. constructor( scope, bufferType, bufferCount = 0 ) {
  23836. super( bufferType );
  23837. /**
  23838. * The buffer type.
  23839. *
  23840. * @type {String}
  23841. */
  23842. this.bufferType = bufferType;
  23843. /**
  23844. * The buffer count.
  23845. *
  23846. * @type {Number}
  23847. * @default 0
  23848. */
  23849. this.bufferCount = bufferCount;
  23850. /**
  23851. * This flag can be used for type testing.
  23852. *
  23853. * @type {Boolean}
  23854. * @readonly
  23855. * @default true
  23856. */
  23857. this.isWorkgroupInfoNode = true;
  23858. /**
  23859. * The data type of the array buffer.
  23860. *
  23861. * @type {String}
  23862. */
  23863. this.elementType = bufferType;
  23864. /**
  23865. * TODO.
  23866. *
  23867. * @type {String}
  23868. */
  23869. this.scope = scope;
  23870. }
  23871. /**
  23872. * Sets the name/label of this node.
  23873. *
  23874. * @param {String} name - The name to set.
  23875. * @return {WorkgroupInfoNode} A reference to this node.
  23876. */
  23877. label( name ) {
  23878. this.name = name;
  23879. return this;
  23880. }
  23881. /**
  23882. * Sets the scope of this node.
  23883. *
  23884. * @param {String} scope - The scope to set.
  23885. * @return {WorkgroupInfoNode} A reference to this node.
  23886. */
  23887. setScope( scope ) {
  23888. this.scope = scope;
  23889. return this;
  23890. }
  23891. /**
  23892. * The data type of the array buffer.
  23893. *
  23894. * @return {String} The element type.
  23895. */
  23896. getElementType() {
  23897. return this.elementType;
  23898. }
  23899. /**
  23900. * Overwrites the default implementation since the input type
  23901. * is inferred from the scope.
  23902. *
  23903. * @param {NodeBuilder} builder - The current node builder.
  23904. * @return {String} The input type.
  23905. */
  23906. getInputType( /*builder*/ ) {
  23907. return `${this.scope}Array`;
  23908. }
  23909. /**
  23910. * This method can be used to access elements via an index node.
  23911. *
  23912. * @param {IndexNode} indexNode - indexNode.
  23913. * @return {WorkgroupInfoElementNode} A reference to an element.
  23914. */
  23915. element( indexNode ) {
  23916. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  23917. }
  23918. generate( builder ) {
  23919. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  23920. }
  23921. }
  23922. /**
  23923. * TSL function for creating a workgroup info node.
  23924. * Creates a new 'workgroup' scoped array buffer.
  23925. *
  23926. * @function
  23927. * @param {String} type - The data type of a 'workgroup' scoped buffer element.
  23928. * @param {Number} [count=0] - The number of elements in the buffer.
  23929. * @returns {WorkgroupInfoNode}
  23930. */
  23931. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  23932. /** @module AtomicFunctionNode **/
  23933. /**
  23934. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  23935. * within a shader. In an atomic function, any modification to an atomic variable will
  23936. * occur as an indivisible step with a defined order relative to other modifications.
  23937. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  23938. * atomic operations will not interfere with each other.
  23939. *
  23940. * This node can only be used with a WebGPU backend.
  23941. *
  23942. * @augments TempNode
  23943. */
  23944. class AtomicFunctionNode extends TempNode {
  23945. static get type() {
  23946. return 'AtomicFunctionNode';
  23947. }
  23948. /**
  23949. * Constructs a new atomic function node.
  23950. *
  23951. * @param {String} method - The signature of the atomic function to construct.
  23952. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  23953. * @param {Node} valueNode - The value that mutates the atomic variable.
  23954. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  23955. */
  23956. constructor( method, pointerNode, valueNode, storeNode = null ) {
  23957. super( 'uint' );
  23958. /**
  23959. * The signature of the atomic function to construct.
  23960. *
  23961. * @type {String}
  23962. */
  23963. this.method = method;
  23964. /**
  23965. * An atomic variable or element of an atomic buffer.
  23966. *
  23967. * @type {Node}
  23968. */
  23969. this.pointerNode = pointerNode;
  23970. /**
  23971. * A value that modifies the atomic variable.
  23972. *
  23973. * @type {Node}
  23974. */
  23975. this.valueNode = valueNode;
  23976. /**
  23977. * A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  23978. *
  23979. * @type {Node?}
  23980. * @default null
  23981. */
  23982. this.storeNode = storeNode;
  23983. }
  23984. /**
  23985. * Overwrites the default implementation to return the type of
  23986. * the pointer node.
  23987. *
  23988. * @param {NodeBuilder} builder - The current node builder.
  23989. * @return {String} The input type.
  23990. */
  23991. getInputType( builder ) {
  23992. return this.pointerNode.getNodeType( builder );
  23993. }
  23994. /**
  23995. * Overwritten since the node type is inferred from the input type.
  23996. *
  23997. * @param {NodeBuilder} builder - The current node builder.
  23998. * @return {String} The node type.
  23999. */
  24000. getNodeType( builder ) {
  24001. return this.getInputType( builder );
  24002. }
  24003. generate( builder ) {
  24004. const method = this.method;
  24005. const type = this.getNodeType( builder );
  24006. const inputType = this.getInputType( builder );
  24007. const a = this.pointerNode;
  24008. const b = this.valueNode;
  24009. const params = [];
  24010. params.push( `&${ a.build( builder, inputType ) }` );
  24011. params.push( b.build( builder, inputType ) );
  24012. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  24013. if ( this.storeNode !== null ) {
  24014. const varSnippet = this.storeNode.build( builder, inputType );
  24015. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this );
  24016. } else {
  24017. builder.addLineFlowCode( methodSnippet, this );
  24018. }
  24019. }
  24020. }
  24021. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  24022. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  24023. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  24024. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  24025. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  24026. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  24027. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  24028. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  24029. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  24030. /**
  24031. * TSL function for creating an atomic function node.
  24032. *
  24033. * @function
  24034. * @param {String} method - The signature of the atomic function to construct.
  24035. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24036. * @param {Node} valueNode - The value that mutates the atomic variable.
  24037. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24038. * @returns {AtomicFunctionNode}
  24039. */
  24040. const atomicNode = nodeProxy( AtomicFunctionNode );
  24041. /**
  24042. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  24043. *
  24044. * @function
  24045. * @param {String} method - The signature of the atomic function to construct.
  24046. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24047. * @param {Node} valueNode - The value that mutates the atomic variable.
  24048. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24049. * @returns {AtomicFunctionNode}
  24050. */
  24051. const atomicFunc = ( method, pointerNode, valueNode, storeNode = null ) => {
  24052. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  24053. node.append();
  24054. return node;
  24055. };
  24056. /**
  24057. * Stores a value in the atomic variable.
  24058. *
  24059. * @function
  24060. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24061. * @param {Node} valueNode - The value that mutates the atomic variable.
  24062. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24063. * @returns {AtomicFunctionNode}
  24064. */
  24065. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  24066. /**
  24067. * Increments the value stored in the atomic variable.
  24068. *
  24069. * @function
  24070. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24071. * @param {Node} valueNode - The value that mutates the atomic variable.
  24072. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24073. * @returns {AtomicFunctionNode}
  24074. */
  24075. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  24076. /**
  24077. * Decrements the value stored in the atomic variable.
  24078. *
  24079. * @function
  24080. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24081. * @param {Node} valueNode - The value that mutates the atomic variable.
  24082. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24083. * @returns {AtomicFunctionNode}
  24084. */
  24085. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  24086. /**
  24087. * Stores in an atomic variable the maximum between its current value and a parameter.
  24088. *
  24089. * @function
  24090. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24091. * @param {Node} valueNode - The value that mutates the atomic variable.
  24092. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24093. * @returns {AtomicFunctionNode}
  24094. */
  24095. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  24096. /**
  24097. * Stores in an atomic variable the minimum between its current value and a parameter.
  24098. *
  24099. * @function
  24100. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24101. * @param {Node} valueNode - The value that mutates the atomic variable.
  24102. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24103. * @returns {AtomicFunctionNode}
  24104. */
  24105. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  24106. /**
  24107. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  24108. *
  24109. * @function
  24110. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24111. * @param {Node} valueNode - The value that mutates the atomic variable.
  24112. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24113. * @returns {AtomicFunctionNode}
  24114. */
  24115. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  24116. /**
  24117. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  24118. *
  24119. * @function
  24120. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24121. * @param {Node} valueNode - The value that mutates the atomic variable.
  24122. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24123. * @returns {AtomicFunctionNode}
  24124. */
  24125. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  24126. /**
  24127. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  24128. *
  24129. * @function
  24130. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24131. * @param {Node} valueNode - The value that mutates the atomic variable.
  24132. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24133. * @returns {AtomicFunctionNode}
  24134. */
  24135. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  24136. /** @module Lights **/
  24137. let uniformsLib;
  24138. function getLightData( light ) {
  24139. uniformsLib = uniformsLib || new WeakMap();
  24140. let uniforms = uniformsLib.get( light );
  24141. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  24142. return uniforms;
  24143. }
  24144. /**
  24145. * TSL function for getting a shadow matrix uniform node for the given light.
  24146. *
  24147. * @function
  24148. * @param {Light} light -The light source.
  24149. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  24150. */
  24151. function lightShadowMatrix( light ) {
  24152. const data = getLightData( light );
  24153. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( () => {
  24154. if ( light.castShadow !== true ) {
  24155. light.shadow.updateMatrices( light );
  24156. }
  24157. return light.shadow.matrix;
  24158. } ) );
  24159. }
  24160. /**
  24161. * TSL function for getting projected uv coordinates for the given light.
  24162. * Relevant when using maps with spot lights.
  24163. *
  24164. * @function
  24165. * @param {Light} light -The light source.
  24166. * @returns {Node<vec3>} The projected uvs.
  24167. */
  24168. function lightProjectionUV( light ) {
  24169. const data = getLightData( light );
  24170. if ( data.projectionUV === undefined ) {
  24171. const spotLightCoord = lightShadowMatrix( light ).mul( positionWorld );
  24172. data.projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  24173. }
  24174. return data.projectionUV;
  24175. }
  24176. /**
  24177. * TSL function for getting the position in world space for the given light.
  24178. *
  24179. * @function
  24180. * @param {Light} light -The light source.
  24181. * @returns {UniformNode<vec3>} The light's position in world space.
  24182. */
  24183. function lightPosition( light ) {
  24184. const data = getLightData( light );
  24185. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  24186. }
  24187. /**
  24188. * TSL function for getting the light target position in world space for the given light.
  24189. *
  24190. * @function
  24191. * @param {Light} light -The light source.
  24192. * @returns {UniformNode<vec3>} The light target position in world space.
  24193. */
  24194. function lightTargetPosition( light ) {
  24195. const data = getLightData( light );
  24196. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  24197. }
  24198. /**
  24199. * TSL function for getting the position in view space for the given light.
  24200. *
  24201. * @function
  24202. * @param {Light} light -The light source.
  24203. * @returns {UniformNode<vec3>} The light's position in view space.
  24204. */
  24205. function lightViewPosition( light ) {
  24206. const data = getLightData( light );
  24207. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  24208. self.value = self.value || new Vector3();
  24209. self.value.setFromMatrixPosition( light.matrixWorld );
  24210. self.value.applyMatrix4( camera.matrixWorldInverse );
  24211. } ) );
  24212. }
  24213. /**
  24214. * TSL function for getting the light target direction for the given light.
  24215. *
  24216. * @function
  24217. * @param {Light} light -The light source.
  24218. * @returns {Node<vec3>} The light's target direction.
  24219. */
  24220. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  24221. /** @module LightsNode **/
  24222. const sortLights = ( lights ) => {
  24223. return lights.sort( ( a, b ) => a.id - b.id );
  24224. };
  24225. const getLightNodeById = ( id, lightNodes ) => {
  24226. for ( const lightNode of lightNodes ) {
  24227. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  24228. return lightNode;
  24229. }
  24230. }
  24231. return null;
  24232. };
  24233. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  24234. /**
  24235. * This node represents the scene's lighting and manages the lighting model's life cycle
  24236. * for the current build 3D object. It is responsible for computing the total outgoing
  24237. * light in a given lighting context.
  24238. *
  24239. * @augments Node
  24240. */
  24241. class LightsNode extends Node {
  24242. static get type() {
  24243. return 'LightsNode';
  24244. }
  24245. /**
  24246. * Constructs a new lights node.
  24247. */
  24248. constructor() {
  24249. super( 'vec3' );
  24250. /**
  24251. * A node representing the total diffuse light.
  24252. *
  24253. * @type {Node<vec3>}
  24254. */
  24255. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  24256. /**
  24257. * A node representing the total specular light.
  24258. *
  24259. * @type {Node<vec3>}
  24260. */
  24261. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  24262. /**
  24263. * A node representing the outgoing light.
  24264. *
  24265. * @type {Node<vec3>}
  24266. */
  24267. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  24268. /**
  24269. * An array representing the lights in the scene.
  24270. *
  24271. * @private
  24272. * @type {Array<Light>}
  24273. */
  24274. this._lights = [];
  24275. /**
  24276. * For each light in the scene, this node will create a
  24277. * corresponding light node.
  24278. *
  24279. * @private
  24280. * @type {Array<LightingNode>?}
  24281. * @default null
  24282. */
  24283. this._lightNodes = null;
  24284. /**
  24285. * A hash for identifying the current light nodes setup.
  24286. *
  24287. * @private
  24288. * @type {String?}
  24289. * @default null
  24290. */
  24291. this._lightNodesHash = null;
  24292. /**
  24293. * `LightsNode` sets this property to `true` by default.
  24294. *
  24295. * @type {Boolean}
  24296. * @default true
  24297. */
  24298. this.global = true;
  24299. }
  24300. /**
  24301. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  24302. * light IDs into the cache key.
  24303. *
  24304. * @return {Number} The custom cache key.
  24305. */
  24306. customCacheKey() {
  24307. const lightIDs = [];
  24308. const lights = this._lights;
  24309. for ( let i = 0; i < lights.length; i ++ ) {
  24310. lightIDs.push( lights[ i ].id );
  24311. }
  24312. return hashArray( lightIDs );
  24313. }
  24314. /**
  24315. * Computes a hash value for identifying the current light nodes setup.
  24316. *
  24317. * @param {NodeBuilder} builder - A reference to the current node builder.
  24318. * @return {String} The computed hash.
  24319. */
  24320. getHash( builder ) {
  24321. if ( this._lightNodesHash === null ) {
  24322. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  24323. const hash = [];
  24324. for ( const lightNode of this._lightNodes ) {
  24325. hash.push( lightNode.getSelf().getHash() );
  24326. }
  24327. this._lightNodesHash = 'lights-' + hash.join( ',' );
  24328. }
  24329. return this._lightNodesHash;
  24330. }
  24331. analyze( builder ) {
  24332. const properties = builder.getDataFromNode( this );
  24333. for ( const node of properties.nodes ) {
  24334. node.build( builder );
  24335. }
  24336. }
  24337. /**
  24338. * Creates lighting nodes for each scene light. This makes it possible to further
  24339. * process lights in the node system.
  24340. *
  24341. * @param {NodeBuilder} builder - A reference to the current node builder.
  24342. */
  24343. setupLightsNode( builder ) {
  24344. const lightNodes = [];
  24345. const previousLightNodes = this._lightNodes;
  24346. const lights = sortLights( this._lights );
  24347. const nodeLibrary = builder.renderer.library;
  24348. for ( const light of lights ) {
  24349. if ( light.isNode ) {
  24350. lightNodes.push( nodeObject( light ) );
  24351. } else {
  24352. let lightNode = null;
  24353. if ( previousLightNodes !== null ) {
  24354. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  24355. }
  24356. if ( lightNode === null ) {
  24357. // find the corresponding node type for a given light
  24358. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  24359. if ( lightNodeClass === null ) {
  24360. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  24361. continue;
  24362. }
  24363. let lightNode = null;
  24364. if ( ! _lightsNodeRef.has( light ) ) {
  24365. lightNode = nodeObject( new lightNodeClass( light ) );
  24366. _lightsNodeRef.set( light, lightNode );
  24367. } else {
  24368. lightNode = _lightsNodeRef.get( light );
  24369. }
  24370. lightNodes.push( lightNode );
  24371. }
  24372. }
  24373. }
  24374. this._lightNodes = lightNodes;
  24375. }
  24376. /**
  24377. * Setups the internal lights by building all respective
  24378. * light nodes.
  24379. *
  24380. * @param {NodeBuilder} builder - A reference to the current node builder.
  24381. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  24382. */
  24383. setupLights( builder, lightNodes ) {
  24384. for ( const lightNode of lightNodes ) {
  24385. lightNode.build( builder );
  24386. }
  24387. }
  24388. /**
  24389. * The implementation makes sure that for each light in the scene
  24390. * there is a corresponding light node. By building the light nodes
  24391. * and evaluating the lighting model the outgoing light is computed.
  24392. *
  24393. * @param {NodeBuilder} builder - A reference to the current node builder.
  24394. * @return {Node<vec3>} A node representing the outgoing light.
  24395. */
  24396. setup( builder ) {
  24397. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  24398. const context = builder.context;
  24399. const lightingModel = context.lightingModel;
  24400. let outgoingLightNode = this.outgoingLightNode;
  24401. if ( lightingModel ) {
  24402. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  24403. context.outgoingLight = outgoingLightNode;
  24404. const stack = builder.addStack();
  24405. //
  24406. const properties = builder.getDataFromNode( this );
  24407. properties.nodes = stack.nodes;
  24408. //
  24409. lightingModel.start( context, stack, builder );
  24410. // lights
  24411. this.setupLights( builder, _lightNodes );
  24412. //
  24413. lightingModel.indirect( context, stack, builder );
  24414. //
  24415. const { backdrop, backdropAlpha } = context;
  24416. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  24417. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  24418. if ( backdrop !== null ) {
  24419. if ( backdropAlpha !== null ) {
  24420. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  24421. } else {
  24422. totalDiffuse = vec3( backdrop );
  24423. }
  24424. context.material.transparent = true;
  24425. }
  24426. totalDiffuseNode.assign( totalDiffuse );
  24427. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  24428. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  24429. //
  24430. lightingModel.finish( context, stack, builder );
  24431. //
  24432. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  24433. }
  24434. return outgoingLightNode;
  24435. }
  24436. /**
  24437. * Configures this node with an array of lights.
  24438. *
  24439. * @param {Array<Light>} lights - An array of lights.
  24440. * @return {LightsNode} A reference to this node.
  24441. */
  24442. setLights( lights ) {
  24443. this._lights = lights;
  24444. this._lightNodes = null;
  24445. this._lightNodesHash = null;
  24446. return this;
  24447. }
  24448. /**
  24449. * Returns an array of the scene's lights.
  24450. *
  24451. * @return {Array<Light>} The scene's lights.
  24452. */
  24453. getLights() {
  24454. return this._lights;
  24455. }
  24456. /**
  24457. * Whether the scene has lights or not.
  24458. *
  24459. * @type {Boolean}
  24460. */
  24461. get hasLights() {
  24462. return this._lights.length > 0;
  24463. }
  24464. }
  24465. /**
  24466. * TSL function for creating an instance of `LightsNode` and configuring
  24467. * it with the given array of lights.
  24468. *
  24469. * @function
  24470. * @param {Array<Light>} lights - An array of lights.
  24471. * @return {LightsNode} The created lights node.
  24472. */
  24473. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  24474. /** @module ShadowBaseNode **/
  24475. /**
  24476. * Base class for all shadow nodes.
  24477. *
  24478. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  24479. * Lighting nodes might share the same shadow node type or use specific ones depending on
  24480. * their requirements.
  24481. *
  24482. * @augments Node
  24483. */
  24484. class ShadowBaseNode extends Node {
  24485. static get type() {
  24486. return 'ShadowBaseNode';
  24487. }
  24488. /**
  24489. * Constructs a new shadow base node.
  24490. *
  24491. * @param {Light} light - The shadow casting light.
  24492. */
  24493. constructor( light ) {
  24494. super();
  24495. /**
  24496. * The shadow casting light.
  24497. *
  24498. * @type {Light}
  24499. */
  24500. this.light = light;
  24501. /**
  24502. * Overwritten since shadows are updated by default per render.
  24503. *
  24504. * @type {String}
  24505. * @default 'render'
  24506. */
  24507. this.updateBeforeType = NodeUpdateType.RENDER;
  24508. /**
  24509. * This flag can be used for type testing.
  24510. *
  24511. * @type {Boolean}
  24512. * @readonly
  24513. * @default true
  24514. */
  24515. this.isShadowBaseNode = true;
  24516. }
  24517. /**
  24518. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  24519. *
  24520. * @param {(NodeBuilder|{Material})} object - A configuration object that must at least hold a material reference.
  24521. */
  24522. setupShadowPosition( { material } ) {
  24523. // Use assign inside an Fn()
  24524. shadowPositionWorld.assign( material.shadowPositionNode || positionWorld );
  24525. }
  24526. /**
  24527. * Can be called when the shadow isn't required anymore. That can happen when
  24528. * a lighting node stops casting shadows by setting {@link Object3D#castShadow}
  24529. * to `false`.
  24530. */
  24531. dispose() {
  24532. this.updateBeforeType = NodeUpdateType.NONE;
  24533. }
  24534. }
  24535. /**
  24536. * TSL object that represents the vertex position in world space during the shadow pass.
  24537. *
  24538. * @type {Node<vec3>}
  24539. */
  24540. const shadowPositionWorld = /*@__PURE__*/ vec3().toVar( 'shadowPositionWorld' );
  24541. /** @module RendererUtils **/
  24542. /**
  24543. * Saves the state of the given renderer and stores it into the given state object.
  24544. *
  24545. * If not state object is provided, the function creates one.
  24546. *
  24547. * @function
  24548. * @param {Renderer} renderer - The renderer.
  24549. * @param {Object} [state={}] - The state.
  24550. * @return {Object} The state.
  24551. */
  24552. function saveRendererState( renderer, state = {} ) {
  24553. state.toneMapping = renderer.toneMapping;
  24554. state.toneMappingExposure = renderer.toneMappingExposure;
  24555. state.outputColorSpace = renderer.outputColorSpace;
  24556. state.renderTarget = renderer.getRenderTarget();
  24557. state.activeCubeFace = renderer.getActiveCubeFace();
  24558. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  24559. state.renderObjectFunction = renderer.getRenderObjectFunction();
  24560. state.pixelRatio = renderer.getPixelRatio();
  24561. state.mrt = renderer.getMRT();
  24562. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  24563. state.clearAlpha = renderer.getClearAlpha();
  24564. state.autoClear = renderer.autoClear;
  24565. state.scissorTest = renderer.getScissorTest();
  24566. return state;
  24567. }
  24568. /**
  24569. * Saves the state of the given renderer and stores it into the given state object.
  24570. * Besides, the function also resets the state of the renderer to its default values.
  24571. *
  24572. * If not state object is provided, the function creates one.
  24573. *
  24574. * @function
  24575. * @param {Renderer} renderer - The renderer.
  24576. * @param {Object} [state={}] - The state.
  24577. * @return {Object} The state.
  24578. */
  24579. function resetRendererState( renderer, state ) {
  24580. state = saveRendererState( renderer, state );
  24581. renderer.setMRT( null );
  24582. renderer.setRenderObjectFunction( null );
  24583. renderer.setClearColor( 0x000000, 1 );
  24584. renderer.autoClear = true;
  24585. return state;
  24586. }
  24587. /**
  24588. * Restores the state of the given renderer from the given state object.
  24589. *
  24590. * @function
  24591. * @param {Renderer} renderer - The renderer.
  24592. * @param {Object} state - The state to restore.
  24593. */
  24594. function restoreRendererState( renderer, state ) {
  24595. renderer.toneMapping = state.toneMapping;
  24596. renderer.toneMappingExposure = state.toneMappingExposure;
  24597. renderer.outputColorSpace = state.outputColorSpace;
  24598. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  24599. renderer.setRenderObjectFunction( state.renderObjectFunction );
  24600. renderer.setPixelRatio( state.pixelRatio );
  24601. renderer.setMRT( state.mrt );
  24602. renderer.setClearColor( state.clearColor, state.clearAlpha );
  24603. renderer.autoClear = state.autoClear;
  24604. renderer.setScissorTest( state.scissorTest );
  24605. }
  24606. /**
  24607. * Saves the state of the given scene and stores it into the given state object.
  24608. *
  24609. * If not state object is provided, the function creates one.
  24610. *
  24611. * @function
  24612. * @param {Scene} scene - The scene.
  24613. * @param {Object} [state={}] - The state.
  24614. * @return {Object} The state.
  24615. */
  24616. function saveSceneState( scene, state = {} ) {
  24617. state.background = scene.background;
  24618. state.backgroundNode = scene.backgroundNode;
  24619. state.overrideMaterial = scene.overrideMaterial;
  24620. return state;
  24621. }
  24622. /**
  24623. * Saves the state of the given scene and stores it into the given state object.
  24624. * Besides, the function also resets the state of the scene to its default values.
  24625. *
  24626. * If not state object is provided, the function creates one.
  24627. *
  24628. * @function
  24629. * @param {Scene} scene - The scene.
  24630. * @param {Object} [state={}] - The state.
  24631. * @return {Object} The state.
  24632. */
  24633. function resetSceneState( scene, state ) {
  24634. state = saveSceneState( scene, state );
  24635. scene.background = null;
  24636. scene.backgroundNode = null;
  24637. scene.overrideMaterial = null;
  24638. return state;
  24639. }
  24640. /**
  24641. * Restores the state of the given scene from the given state object.
  24642. *
  24643. * @function
  24644. * @param {Scene} scene - The scene.
  24645. * @param {Object} state - The state to restore.
  24646. */
  24647. function restoreSceneState( scene, state ) {
  24648. scene.background = state.background;
  24649. scene.backgroundNode = state.backgroundNode;
  24650. scene.overrideMaterial = state.overrideMaterial;
  24651. }
  24652. /**
  24653. * Saves the state of the given renderer and scene and stores it into the given state object.
  24654. *
  24655. * If not state object is provided, the function creates one.
  24656. *
  24657. * @function
  24658. * @param {Renderer} renderer - The renderer.
  24659. * @param {Scene} scene - The scene.
  24660. * @param {Object} [state={}] - The state.
  24661. * @return {Object} The state.
  24662. */
  24663. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  24664. state = saveRendererState( renderer, state );
  24665. state = saveSceneState( scene, state );
  24666. return state;
  24667. }
  24668. /**
  24669. * Saves the state of the given renderer and scene and stores it into the given state object.
  24670. * Besides, the function also resets the state of the renderer and scene to its default values.
  24671. *
  24672. * If not state object is provided, the function creates one.
  24673. *
  24674. * @function
  24675. * @param {Renderer} renderer - The renderer.
  24676. * @param {Scene} scene - The scene.
  24677. * @param {Object} [state={}] - The state.
  24678. * @return {Object} The state.
  24679. */
  24680. function resetRendererAndSceneState( renderer, scene, state ) {
  24681. state = resetRendererState( renderer, state );
  24682. state = resetSceneState( scene, state );
  24683. return state;
  24684. }
  24685. /**
  24686. * Restores the state of the given renderer and scene from the given state object.
  24687. *
  24688. * @function
  24689. * @param {Renderer} renderer - The renderer.
  24690. * @param {Scene} scene - The scene.
  24691. * @param {Object} state - The state to restore.
  24692. */
  24693. function restoreRendererAndSceneState( renderer, scene, state ) {
  24694. restoreRendererState( renderer, state );
  24695. restoreSceneState( scene, state );
  24696. }
  24697. var RendererUtils = /*#__PURE__*/Object.freeze({
  24698. __proto__: null,
  24699. resetRendererAndSceneState: resetRendererAndSceneState,
  24700. resetRendererState: resetRendererState,
  24701. resetSceneState: resetSceneState,
  24702. restoreRendererAndSceneState: restoreRendererAndSceneState,
  24703. restoreRendererState: restoreRendererState,
  24704. restoreSceneState: restoreSceneState,
  24705. saveRendererAndSceneState: saveRendererAndSceneState,
  24706. saveRendererState: saveRendererState,
  24707. saveSceneState: saveSceneState
  24708. });
  24709. /** @module ShadowNode **/
  24710. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  24711. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  24712. let dist = positionWorld.sub( position ).length();
  24713. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  24714. dist = dist.saturate(); // clamp to [ 0, 1 ]
  24715. return dist;
  24716. } );
  24717. const linearShadowDistance = ( light ) => {
  24718. const camera = light.shadow.camera;
  24719. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  24720. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  24721. const referencePosition = objectPosition( light );
  24722. return linearDistance( referencePosition, nearDistance, farDistance );
  24723. };
  24724. const getShadowMaterial = ( light ) => {
  24725. let material = shadowMaterialLib.get( light );
  24726. if ( material === undefined ) {
  24727. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  24728. material = new NodeMaterial();
  24729. material.colorNode = vec4( 0, 0, 0, 1 );
  24730. material.depthNode = depthNode;
  24731. material.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  24732. material.name = 'ShadowMaterial';
  24733. material.fog = false;
  24734. shadowMaterialLib.set( light, material );
  24735. }
  24736. return material;
  24737. };
  24738. /**
  24739. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  24740. * with a binary `[0,1]` result.
  24741. *
  24742. * @method
  24743. * @param {Object} inputs - The input parameter object.
  24744. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  24745. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  24746. * @return {Node<float>} The filtering result.
  24747. */
  24748. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  24749. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  24750. } );
  24751. /**
  24752. * A shadow filtering function performing PCF filtering.
  24753. *
  24754. * @method
  24755. * @param {Object} inputs - The input parameter object.
  24756. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  24757. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  24758. * @param {LightShadow} inputs.shadow - The light shadow.
  24759. * @return {Node<float>} The filtering result.
  24760. */
  24761. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  24762. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  24763. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  24764. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  24765. const texelSize = vec2( 1 ).div( mapSize );
  24766. const dx0 = texelSize.x.negate().mul( radius );
  24767. const dy0 = texelSize.y.negate().mul( radius );
  24768. const dx1 = texelSize.x.mul( radius );
  24769. const dy1 = texelSize.y.mul( radius );
  24770. const dx2 = dx0.div( 2 );
  24771. const dy2 = dy0.div( 2 );
  24772. const dx3 = dx1.div( 2 );
  24773. const dy3 = dy1.div( 2 );
  24774. return add(
  24775. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  24776. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  24777. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  24778. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  24779. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  24780. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  24781. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  24782. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  24783. depthCompare( shadowCoord.xy, shadowCoord.z ),
  24784. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  24785. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  24786. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  24787. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  24788. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  24789. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  24790. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  24791. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  24792. ).mul( 1 / 17 );
  24793. } );
  24794. /**
  24795. * A shadow filtering function performing PCF soft filtering.
  24796. *
  24797. * @method
  24798. * @param {Object} inputs - The input parameter object.
  24799. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  24800. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  24801. * @param {LightShadow} inputs.shadow - The light shadow.
  24802. * @return {Node<float>} The filtering result.
  24803. */
  24804. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  24805. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  24806. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  24807. const texelSize = vec2( 1 ).div( mapSize );
  24808. const dx = texelSize.x;
  24809. const dy = texelSize.y;
  24810. const uv = shadowCoord.xy;
  24811. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  24812. uv.subAssign( f.mul( texelSize ) );
  24813. return add(
  24814. depthCompare( uv, shadowCoord.z ),
  24815. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  24816. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  24817. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  24818. mix(
  24819. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  24820. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  24821. f.x
  24822. ),
  24823. mix(
  24824. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  24825. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  24826. f.x
  24827. ),
  24828. mix(
  24829. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  24830. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  24831. f.y
  24832. ),
  24833. mix(
  24834. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  24835. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  24836. f.y
  24837. ),
  24838. mix(
  24839. mix(
  24840. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  24841. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  24842. f.x
  24843. ),
  24844. mix(
  24845. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  24846. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  24847. f.x
  24848. ),
  24849. f.y
  24850. )
  24851. ).mul( 1 / 9 );
  24852. } );
  24853. /**
  24854. * A shadow filtering function performing VSM filtering.
  24855. *
  24856. * @method
  24857. * @param {Object} inputs - The input parameter object.
  24858. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  24859. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  24860. * @return {Node<float>} The filtering result.
  24861. */
  24862. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  24863. const occlusion = float( 1 ).toVar();
  24864. const distribution = texture( depthTexture ).sample( shadowCoord.xy ).rg;
  24865. const hardShadow = step( shadowCoord.z, distribution.x );
  24866. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  24867. const distance = shadowCoord.z.sub( distribution.x );
  24868. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  24869. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  24870. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  24871. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  24872. } );
  24873. return occlusion;
  24874. } );
  24875. /**
  24876. * Represents the shader code for the first VSM render pass.
  24877. *
  24878. * @method
  24879. * @param {Object} inputs - The input parameter object.
  24880. * @param {Node<float>} inputs.samples - The number of samples
  24881. * @param {Node<float>} inputs.radius - The radius.
  24882. * @param {Node<float>} inputs.size - The size.
  24883. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  24884. * @return {Node<vec2>} The VSM output.
  24885. */
  24886. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  24887. const mean = float( 0 ).toVar();
  24888. const squaredMean = float( 0 ).toVar();
  24889. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  24890. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  24891. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  24892. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  24893. const depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  24894. mean.addAssign( depth );
  24895. squaredMean.addAssign( depth.mul( depth ) );
  24896. } );
  24897. mean.divAssign( samples );
  24898. squaredMean.divAssign( samples );
  24899. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  24900. return vec2( mean, std_dev );
  24901. } );
  24902. /**
  24903. * Represents the shader code for the second VSM render pass.
  24904. *
  24905. * @method
  24906. * @param {Object} inputs - The input parameter object.
  24907. * @param {Node<float>} inputs.samples - The number of samples
  24908. * @param {Node<float>} inputs.radius - The radius.
  24909. * @param {Node<float>} inputs.size - The size.
  24910. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  24911. * @return {Node<vec2>} The VSM output.
  24912. */
  24913. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  24914. const mean = float( 0 ).toVar();
  24915. const squaredMean = float( 0 ).toVar();
  24916. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  24917. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  24918. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  24919. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  24920. const distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  24921. mean.addAssign( distribution.x );
  24922. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  24923. } );
  24924. mean.divAssign( samples );
  24925. squaredMean.divAssign( samples );
  24926. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  24927. return vec2( mean, std_dev );
  24928. } );
  24929. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  24930. //
  24931. let _rendererState;
  24932. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  24933. /**
  24934. * Represents the default shadow implementation for lighting nodes.
  24935. *
  24936. * @augments module:ShadowBaseNode~ShadowBaseNode
  24937. */
  24938. class ShadowNode extends ShadowBaseNode {
  24939. static get type() {
  24940. return 'ShadowNode';
  24941. }
  24942. /**
  24943. * Constructs a new shadow node.
  24944. *
  24945. * @param {Light} light - The shadow casting light.
  24946. * @param {LightShadow?} [shadow=null] - An optional light shadow.
  24947. */
  24948. constructor( light, shadow = null ) {
  24949. super( light );
  24950. /**
  24951. * The light shadow which defines the properties light's
  24952. * shadow.
  24953. *
  24954. * @type {LightShadow?}
  24955. * @default null
  24956. */
  24957. this.shadow = shadow || light.shadow;
  24958. /**
  24959. * A reference to the shadow map which is a render target.
  24960. *
  24961. * @type {RenderTarget?}
  24962. * @default null
  24963. */
  24964. this.shadowMap = null;
  24965. /**
  24966. * Only relevant for VSM shadows. Render target for the
  24967. * first VSM render pass.
  24968. *
  24969. * @type {RenderTarget?}
  24970. * @default null
  24971. */
  24972. this.vsmShadowMapVertical = null;
  24973. /**
  24974. * Only relevant for VSM shadows. Render target for the
  24975. * second VSM render pass.
  24976. *
  24977. * @type {RenderTarget?}
  24978. * @default null
  24979. */
  24980. this.vsmShadowMapHorizontal = null;
  24981. /**
  24982. * Only relevant for VSM shadows. Node material which
  24983. * is used to render the first VSM pass.
  24984. *
  24985. * @type {NodeMaterial?}
  24986. * @default null
  24987. */
  24988. this.vsmMaterialVertical = null;
  24989. /**
  24990. * Only relevant for VSM shadows. Node material which
  24991. * is used to render the second VSM pass.
  24992. *
  24993. * @type {NodeMaterial?}
  24994. * @default null
  24995. */
  24996. this.vsmMaterialHorizontal = null;
  24997. /**
  24998. * A reference to the output node which defines the
  24999. * final result of this shadow node.
  25000. *
  25001. * @type {Node?}
  25002. * @private
  25003. * @default null
  25004. */
  25005. this._node = null;
  25006. /**
  25007. * This flag can be used for type testing.
  25008. *
  25009. * @type {Boolean}
  25010. * @readonly
  25011. * @default true
  25012. */
  25013. this.isShadowNode = true;
  25014. }
  25015. /**
  25016. * Setups the shadow filtering.
  25017. *
  25018. * @param {NodeBuilder} builder - A reference to the current node builder.
  25019. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  25020. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  25021. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25022. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  25023. * @param {LightShadow} inputs.shadow - The light shadow.
  25024. * @return {Node<float>} The result node of the shadow filtering.
  25025. */
  25026. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  25027. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  25028. .and( shadowCoord.x.lessThanEqual( 1 ) )
  25029. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  25030. .and( shadowCoord.y.lessThanEqual( 1 ) )
  25031. .and( shadowCoord.z.lessThanEqual( 1 ) );
  25032. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow } );
  25033. return frustumTest.select( shadowNode, float( 1 ) );
  25034. }
  25035. /**
  25036. * Setups the shadow coordinates.
  25037. *
  25038. * @param {NodeBuilder} builder - A reference to the current node builder.
  25039. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  25040. * @return {Node<vec3>} The shadow coordinates.
  25041. */
  25042. setupShadowCoord( builder, shadowPosition ) {
  25043. const { shadow } = this;
  25044. const { renderer } = builder;
  25045. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  25046. let shadowCoord = shadowPosition;
  25047. let coordZ;
  25048. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  25049. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  25050. coordZ = shadowCoord.z;
  25051. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  25052. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  25053. }
  25054. } else {
  25055. const w = shadowCoord.w;
  25056. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  25057. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  25058. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  25059. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  25060. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  25061. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  25062. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  25063. }
  25064. shadowCoord = vec3(
  25065. shadowCoord.x,
  25066. shadowCoord.y.oneMinus(), // follow webgpu standards
  25067. coordZ.add( bias )
  25068. );
  25069. return shadowCoord;
  25070. }
  25071. /**
  25072. * Returns the shadow filtering function for the given shadow type.
  25073. *
  25074. * @param {Number} type - The shadow type.
  25075. * @return {Function} The filtering function.
  25076. */
  25077. getShadowFilterFn( type ) {
  25078. return _shadowFilterLib[ type ];
  25079. }
  25080. /**
  25081. * Setups the shadow output node.
  25082. *
  25083. * @param {NodeBuilder} builder - A reference to the current node builder.
  25084. * @return {Node<vec3>} The shadow output node.
  25085. */
  25086. setupShadow( builder ) {
  25087. const { renderer } = builder;
  25088. const { light, shadow } = this;
  25089. const shadowMapType = renderer.shadowMap.type;
  25090. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  25091. depthTexture.compareFunction = LessCompare;
  25092. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  25093. shadowMap.depthTexture = depthTexture;
  25094. shadow.camera.updateProjectionMatrix();
  25095. // VSM
  25096. if ( shadowMapType === VSMShadowMap ) {
  25097. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  25098. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  25099. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  25100. const shadowPassVertical = texture( depthTexture );
  25101. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  25102. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  25103. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  25104. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  25105. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  25106. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  25107. material.name = 'VSMVertical';
  25108. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  25109. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  25110. material.name = 'VSMHorizontal';
  25111. }
  25112. //
  25113. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  25114. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  25115. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( transformedNormalWorld.mul( normalBias ) ) );
  25116. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  25117. //
  25118. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  25119. if ( filterFn === null ) {
  25120. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  25121. }
  25122. const shadowDepthTexture = ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  25123. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow } );
  25124. const shadowColor = texture( shadowMap.texture, shadowCoord );
  25125. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  25126. this.shadowMap = shadowMap;
  25127. this.shadow.map = shadowMap;
  25128. return shadowOutput;
  25129. }
  25130. /**
  25131. * The implementation performs the setup of the output node. An output is only
  25132. * produces if shadow mapping is globally enabled in the renderer.
  25133. *
  25134. * @param {NodeBuilder} builder - A reference to the current node builder.
  25135. * @return {ShaderCallNodeInternal} The output node.
  25136. */
  25137. setup( builder ) {
  25138. if ( builder.renderer.shadowMap.enabled === false ) return;
  25139. return Fn( () => {
  25140. let node = this._node;
  25141. this.setupShadowPosition( builder );
  25142. if ( node === null ) {
  25143. this._node = node = this.setupShadow( builder );
  25144. }
  25145. if ( builder.material.shadowNode ) { // @deprecated, r171
  25146. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  25147. }
  25148. if ( builder.material.receivedShadowNode ) {
  25149. node = builder.material.receivedShadowNode( node );
  25150. }
  25151. return node;
  25152. } )();
  25153. }
  25154. /**
  25155. * Renders the shadow. The logic of this function could be included
  25156. * into {@link ShadowNode#updateShadow} however more specialized shadow
  25157. * nodes might require a custom shadow map rendering. By having a
  25158. * dedicated method, it's easier to overwrite the default behavior.
  25159. *
  25160. * @param {NodeFrame} frame - A reference to the current node frame.
  25161. */
  25162. renderShadow( frame ) {
  25163. const { shadow, shadowMap, light } = this;
  25164. const { renderer, scene } = frame;
  25165. shadow.updateMatrices( light );
  25166. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  25167. renderer.render( scene, shadow.camera );
  25168. }
  25169. /**
  25170. * Updates the shadow.
  25171. *
  25172. * @param {NodeFrame} frame - A reference to the current node frame.
  25173. */
  25174. updateShadow( frame ) {
  25175. const { shadowMap, light, shadow } = this;
  25176. const { renderer, scene, camera } = frame;
  25177. const shadowType = renderer.shadowMap.type;
  25178. const depthVersion = shadowMap.depthTexture.version;
  25179. this._depthVersionCached = depthVersion;
  25180. shadow.camera.layers.mask = camera.layers.mask;
  25181. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  25182. const currentMRT = renderer.getMRT();
  25183. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  25184. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  25185. scene.overrideMaterial = getShadowMaterial( light );
  25186. renderer.setRenderObjectFunction( ( object, scene, _camera, geometry, material, group, ...params ) => {
  25187. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  25188. if ( useVelocity ) {
  25189. getDataFromObject( object ).useVelocity = true;
  25190. }
  25191. object.onBeforeShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  25192. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  25193. object.onAfterShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  25194. }
  25195. } );
  25196. renderer.setRenderTarget( shadowMap );
  25197. this.renderShadow( frame );
  25198. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  25199. // vsm blur pass
  25200. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  25201. this.vsmPass( renderer );
  25202. }
  25203. restoreRendererAndSceneState( renderer, scene, _rendererState );
  25204. }
  25205. /**
  25206. * For VSM additional render passes are required.
  25207. *
  25208. * @param {Renderer} renderer - A reference to the current renderer.
  25209. */
  25210. vsmPass( renderer ) {
  25211. const { shadow } = this;
  25212. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  25213. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  25214. renderer.setRenderTarget( this.vsmShadowMapVertical );
  25215. _quadMesh.material = this.vsmMaterialVertical;
  25216. _quadMesh.render( renderer );
  25217. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  25218. _quadMesh.material = this.vsmMaterialHorizontal;
  25219. _quadMesh.render( renderer );
  25220. }
  25221. /**
  25222. * Frees the internal resources of this shadow node.
  25223. */
  25224. dispose() {
  25225. this.shadowMap.dispose();
  25226. this.shadowMap = null;
  25227. if ( this.vsmShadowMapVertical !== null ) {
  25228. this.vsmShadowMapVertical.dispose();
  25229. this.vsmShadowMapVertical = null;
  25230. this.vsmMaterialVertical.dispose();
  25231. this.vsmMaterialVertical = null;
  25232. }
  25233. if ( this.vsmShadowMapHorizontal !== null ) {
  25234. this.vsmShadowMapHorizontal.dispose();
  25235. this.vsmShadowMapHorizontal = null;
  25236. this.vsmMaterialHorizontal.dispose();
  25237. this.vsmMaterialHorizontal = null;
  25238. }
  25239. super.dispose();
  25240. }
  25241. /**
  25242. * The implementation performs the update of the shadow map if necessary.
  25243. *
  25244. * @param {NodeFrame} frame - A reference to the current node frame.
  25245. */
  25246. updateBefore( frame ) {
  25247. const { shadow } = this;
  25248. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  25249. if ( needsUpdate ) {
  25250. this.updateShadow( frame );
  25251. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  25252. shadow.needsUpdate = false;
  25253. }
  25254. }
  25255. }
  25256. }
  25257. /**
  25258. * TSL function for creating an instance of `ShadowNode`.
  25259. *
  25260. * @function
  25261. * @param {Light} light - The shadow casting light.
  25262. * @param {LightShadow} shadow - The light shadow.
  25263. * @return {ShadowNode} The created shadow node.
  25264. */
  25265. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  25266. /**
  25267. * Base class for analytic light nodes.
  25268. *
  25269. * @augments LightingNode
  25270. */
  25271. class AnalyticLightNode extends LightingNode {
  25272. static get type() {
  25273. return 'AnalyticLightNode';
  25274. }
  25275. /**
  25276. * Constructs a new analytic light node.
  25277. *
  25278. * @param {Light?} [light=null] - The light source.
  25279. */
  25280. constructor( light = null ) {
  25281. super();
  25282. /**
  25283. * The light source.
  25284. *
  25285. * @type {Light?}
  25286. * @default null
  25287. */
  25288. this.light = light;
  25289. /**
  25290. * The light's color value.
  25291. *
  25292. * @type {Color}
  25293. */
  25294. this.color = new Color();
  25295. /**
  25296. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  25297. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  25298. *
  25299. * @type {Node}
  25300. */
  25301. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  25302. /**
  25303. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  25304. * The final color node is represented by a different node when using shadows.
  25305. *
  25306. * @type {Node?}
  25307. * @default null
  25308. */
  25309. this.baseColorNode = null;
  25310. /**
  25311. * Represents the light's shadow.
  25312. *
  25313. * @type {ShadowNode?}
  25314. * @default null
  25315. */
  25316. this.shadowNode = null;
  25317. /**
  25318. * Represents the light's shadow color.
  25319. *
  25320. * @type {Node?}
  25321. * @default null
  25322. */
  25323. this.shadowColorNode = null;
  25324. /**
  25325. * This flag can be used for type testing.
  25326. *
  25327. * @type {Boolean}
  25328. * @readonly
  25329. * @default true
  25330. */
  25331. this.isAnalyticLightNode = true;
  25332. /**
  25333. * Overwritten since analytic light nodes are updated
  25334. * once per frame.
  25335. *
  25336. * @type {String}
  25337. * @default 'frame'
  25338. */
  25339. this.updateType = NodeUpdateType.FRAME;
  25340. }
  25341. /**
  25342. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  25343. * `light.id` and `light.castShadow` into the cache key.
  25344. *
  25345. * @return {Number} The custom cache key.
  25346. */
  25347. customCacheKey() {
  25348. return hash$1( this.light.id, this.light.castShadow ? 1 : 0 );
  25349. }
  25350. getHash() {
  25351. return this.light.uuid;
  25352. }
  25353. /**
  25354. * Setups the shadow node for this light. The method exists so concrete light classes
  25355. * can setup different types of shadow nodes.
  25356. *
  25357. * @return {ShadowNode} The created shadow node.
  25358. */
  25359. setupShadowNode() {
  25360. return shadow( this.light );
  25361. }
  25362. /**
  25363. * Setups the shadow for this light. This method is only executed if the light
  25364. * cast shadows and the current build object receives shadows. It incorporates
  25365. * shadows into the lighting computation.
  25366. *
  25367. * @param {NodeBuilder} builder - The current node builder.
  25368. */
  25369. setupShadow( builder ) {
  25370. const { renderer } = builder;
  25371. if ( renderer.shadowMap.enabled === false ) return;
  25372. let shadowColorNode = this.shadowColorNode;
  25373. if ( shadowColorNode === null ) {
  25374. const customShadowNode = this.light.shadow.shadowNode;
  25375. let shadowNode;
  25376. if ( customShadowNode !== undefined ) {
  25377. shadowNode = nodeObject( customShadowNode );
  25378. } else {
  25379. shadowNode = this.setupShadowNode( builder );
  25380. }
  25381. this.shadowNode = shadowNode;
  25382. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  25383. this.baseColorNode = this.colorNode;
  25384. }
  25385. //
  25386. this.colorNode = shadowColorNode;
  25387. }
  25388. /**
  25389. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  25390. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  25391. * invocate the respective interface methods.
  25392. *
  25393. * @param {NodeBuilder} builder - The current node builder.
  25394. */
  25395. setup( builder ) {
  25396. this.colorNode = this.baseColorNode || this.colorNode;
  25397. if ( this.light.castShadow ) {
  25398. if ( builder.object.receiveShadow ) {
  25399. this.setupShadow( builder );
  25400. }
  25401. } else if ( this.shadowNode !== null ) {
  25402. this.shadowNode.dispose();
  25403. this.shadowNode = null;
  25404. this.shadowColorNode = null;
  25405. }
  25406. }
  25407. /**
  25408. * The update method is used to update light uniforms per frame.
  25409. * Potentially overwritten in concrete light nodes to update light
  25410. * specific uniforms.
  25411. *
  25412. * @param {NodeFrame} frame - A reference to the current node frame.
  25413. */
  25414. update( /*frame*/ ) {
  25415. const { light } = this;
  25416. this.color.copy( light.color ).multiplyScalar( light.intensity );
  25417. }
  25418. }
  25419. /** @module LightUtils **/
  25420. /**
  25421. * Represents a `discard` shader operation in TSL.
  25422. *
  25423. * @method
  25424. * @param {Object} inputs - The input parameter object.
  25425. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  25426. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  25427. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  25428. * @return {Node<float>} The distance falloff.
  25429. */
  25430. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  25431. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  25432. // based upon Frostbite 3 Moving to Physically-based Rendering
  25433. // page 32, equation 26: E[window1]
  25434. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  25435. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  25436. return cutoffDistance.greaterThan( 0 ).select(
  25437. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  25438. distanceFalloff
  25439. );
  25440. } ); // validated
  25441. /** @module PointShadowNode **/
  25442. const _clearColor$2 = /*@__PURE__*/ new Color();
  25443. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  25444. // vector suitable for 2D texture mapping. This code uses the following layout for the
  25445. // 2D texture:
  25446. //
  25447. // xzXZ
  25448. // y Y
  25449. //
  25450. // Y - Positive y direction
  25451. // y - Negative y direction
  25452. // X - Positive x direction
  25453. // x - Negative x direction
  25454. // Z - Positive z direction
  25455. // z - Negative z direction
  25456. //
  25457. // Source and test bed:
  25458. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  25459. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  25460. const v = pos.toVar();
  25461. // Number of texels to avoid at the edge of each square
  25462. const absV = abs( v );
  25463. // Intersect unit cube
  25464. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  25465. absV.mulAssign( scaleToCube );
  25466. // Apply scale to avoid seams
  25467. // two texels less per square (one texel will do for NEAREST)
  25468. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  25469. // Unwrap
  25470. // space: -1 ... 1 range for each square
  25471. //
  25472. // #X## dim := ( 4 , 2 )
  25473. // # # center := ( 1 , 1 )
  25474. const planar = vec2( v.xy ).toVar();
  25475. const almostATexel = texelSizeY.mul( 1.5 );
  25476. const almostOne = almostATexel.oneMinus();
  25477. If( absV.z.greaterThanEqual( almostOne ), () => {
  25478. If( v.z.greaterThan( 0.0 ), () => {
  25479. planar.x.assign( sub( 4.0, v.x ) );
  25480. } );
  25481. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  25482. const signX = sign( v.x );
  25483. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  25484. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  25485. const signY = sign( v.y );
  25486. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  25487. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  25488. } );
  25489. // Transform to UV space
  25490. // scale := 0.5 / dim
  25491. // translate := ( center + 0.5 ) / dim
  25492. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  25493. } ).setLayout( {
  25494. name: 'cubeToUV',
  25495. type: 'vec2',
  25496. inputs: [
  25497. { name: 'pos', type: 'vec3' },
  25498. { name: 'texelSizeY', type: 'float' }
  25499. ]
  25500. } );
  25501. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  25502. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  25503. } );
  25504. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  25505. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  25506. const offset = vec2( - 1.0, 1.0 ).mul( radius ).mul( texelSize.y );
  25507. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  25508. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  25509. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  25510. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  25511. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  25512. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  25513. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  25514. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  25515. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  25516. .mul( 1.0 / 9.0 );
  25517. } );
  25518. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  25519. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  25520. // the vector from the light to the world-space position of the fragment.
  25521. const lightToPosition = shadowCoord.xyz.toVar();
  25522. const lightToPositionLength = lightToPosition.length();
  25523. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  25524. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  25525. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  25526. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  25527. const result = float( 1.0 ).toVar();
  25528. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  25529. // dp = normalized distance from light to fragment position
  25530. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  25531. dp.addAssign( bias );
  25532. // bd3D = base direction 3D
  25533. const bd3D = lightToPosition.normalize();
  25534. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  25535. // percentage-closer filtering
  25536. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  25537. } );
  25538. return result;
  25539. } );
  25540. const _viewport = /*@__PURE__*/ new Vector4();
  25541. const _viewportSize = /*@__PURE__*/ new Vector2();
  25542. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  25543. /**
  25544. * Represents the shadow implementation for point light nodes.
  25545. *
  25546. * @augments module:ShadowNode~ShadowNode
  25547. */
  25548. class PointShadowNode extends ShadowNode {
  25549. static get type() {
  25550. return 'PointShadowNode';
  25551. }
  25552. /**
  25553. * Constructs a new point shadow node.
  25554. *
  25555. * @param {PointLight} light - The shadow casting point light.
  25556. * @param {PointLightShadow?} [shadow=null] - An optional point light shadow.
  25557. */
  25558. constructor( light, shadow = null ) {
  25559. super( light, shadow );
  25560. }
  25561. /**
  25562. * Overwrites the default implementation to return point light shadow specific
  25563. * filtering functions.
  25564. *
  25565. * @param {Number} type - The shadow type.
  25566. * @return {Function} The filtering function.
  25567. */
  25568. getShadowFilterFn( type ) {
  25569. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  25570. }
  25571. /**
  25572. * Overwrites the default implementation so the unaltered shadow position is used.
  25573. *
  25574. * @param {NodeBuilder} builder - A reference to the current node builder.
  25575. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  25576. * @return {Node<vec3>} The shadow coordinates.
  25577. */
  25578. setupShadowCoord( builder, shadowPosition ) {
  25579. return shadowPosition;
  25580. }
  25581. /**
  25582. * Overwrites the default implementation to only use point light specific
  25583. * shadow filter functions.
  25584. *
  25585. * @param {NodeBuilder} builder - A reference to the current node builder.
  25586. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  25587. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  25588. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  25589. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25590. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  25591. * @param {LightShadow} inputs.shadow - The light shadow.
  25592. * @return {Node<float>} The result node of the shadow filtering.
  25593. */
  25594. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  25595. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  25596. }
  25597. /**
  25598. * Overwrites the default implementation with point light specific
  25599. * rendering code.
  25600. *
  25601. * @param {NodeFrame} frame - A reference to the current node frame.
  25602. */
  25603. renderShadow( frame ) {
  25604. const { shadow, shadowMap, light } = this;
  25605. const { renderer, scene } = frame;
  25606. const shadowFrameExtents = shadow.getFrameExtents();
  25607. _shadowMapSize.copy( shadow.mapSize );
  25608. _shadowMapSize.multiply( shadowFrameExtents );
  25609. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  25610. _viewportSize.copy( shadow.mapSize );
  25611. //
  25612. const previousAutoClear = renderer.autoClear;
  25613. const previousClearColor = renderer.getClearColor( _clearColor$2 );
  25614. const previousClearAlpha = renderer.getClearAlpha();
  25615. renderer.autoClear = false;
  25616. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  25617. renderer.clear();
  25618. const viewportCount = shadow.getViewportCount();
  25619. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  25620. const viewport = shadow.getViewport( vp );
  25621. const x = _viewportSize.x * viewport.x;
  25622. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  25623. _viewport.set(
  25624. x,
  25625. y,
  25626. _viewportSize.x * viewport.z,
  25627. _viewportSize.y * viewport.w
  25628. );
  25629. shadowMap.viewport.copy( _viewport );
  25630. shadow.updateMatrices( light, vp );
  25631. renderer.render( scene, shadow.camera );
  25632. }
  25633. //
  25634. renderer.autoClear = previousAutoClear;
  25635. renderer.setClearColor( previousClearColor, previousClearAlpha );
  25636. }
  25637. }
  25638. /**
  25639. * TSL function for creating an instance of `PointShadowNode`.
  25640. *
  25641. * @function
  25642. * @param {PointLight} light - The shadow casting point light.
  25643. * @param {PointLightShadow?} [shadow=null] - An optional point light shadow.
  25644. * @return {PointShadowNode} The created point shadow node.
  25645. */
  25646. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  25647. const directPointLight = Fn( ( { color, lightViewPosition, cutoffDistance, decayExponent }, builder ) => {
  25648. const lightingModel = builder.context.lightingModel;
  25649. const lVector = lightViewPosition.sub( positionView ); // @TODO: Add it into LightNode
  25650. const lightDirection = lVector.normalize();
  25651. const lightDistance = lVector.length();
  25652. const lightAttenuation = getDistanceAttenuation( {
  25653. lightDistance,
  25654. cutoffDistance,
  25655. decayExponent
  25656. } );
  25657. const lightColor = color.mul( lightAttenuation );
  25658. const reflectedLight = builder.context.reflectedLight;
  25659. lightingModel.direct( {
  25660. lightDirection,
  25661. lightColor,
  25662. reflectedLight
  25663. }, builder.stack, builder );
  25664. } );
  25665. /**
  25666. * Module for representing point lights as nodes.
  25667. *
  25668. * @augments AnalyticLightNode
  25669. */
  25670. class PointLightNode extends AnalyticLightNode {
  25671. static get type() {
  25672. return 'PointLightNode';
  25673. }
  25674. /**
  25675. * Constructs a new point light node.
  25676. *
  25677. * @param {PointLight?} [light=null] - The point light source.
  25678. */
  25679. constructor( light = null ) {
  25680. super( light );
  25681. /**
  25682. * Uniform node representing the cutoff distance.
  25683. *
  25684. * @type {UniformNode<float>}
  25685. */
  25686. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  25687. /**
  25688. * Uniform node representing the decay exponent.
  25689. *
  25690. * @type {UniformNode<float>}
  25691. */
  25692. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  25693. }
  25694. /**
  25695. * Overwritten to updated point light specific uniforms.
  25696. *
  25697. * @param {NodeFrame} frame - A reference to the current node frame.
  25698. */
  25699. update( frame ) {
  25700. const { light } = this;
  25701. super.update( frame );
  25702. this.cutoffDistanceNode.value = light.distance;
  25703. this.decayExponentNode.value = light.decay;
  25704. }
  25705. /**
  25706. * Overwritten to setup point light specific shadow.
  25707. *
  25708. * @return {PointShadowNode}
  25709. */
  25710. setupShadowNode() {
  25711. return pointShadow( this.light );
  25712. }
  25713. setup( builder ) {
  25714. super.setup( builder );
  25715. directPointLight( {
  25716. color: this.colorNode,
  25717. lightViewPosition: lightViewPosition( this.light ),
  25718. cutoffDistance: this.cutoffDistanceNode,
  25719. decayExponent: this.decayExponentNode
  25720. } ).append();
  25721. }
  25722. }
  25723. /** @module Procedural **/
  25724. /**
  25725. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  25726. *
  25727. * @method
  25728. * @param {Node<vec2>} coord - The uv coordinates.
  25729. * @return {Node<float>} The result data.
  25730. */
  25731. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  25732. const uv = coord.mul( 2.0 );
  25733. const cx = uv.x.floor();
  25734. const cy = uv.y.floor();
  25735. const result = cx.add( cy ).mod( 2.0 );
  25736. return result.sign();
  25737. } );
  25738. // Three.js Transpiler
  25739. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  25740. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  25741. const f = float( f_immutable ).toVar();
  25742. const t = float( t_immutable ).toVar();
  25743. const b = bool( b_immutable ).toVar();
  25744. return select( b, t, f );
  25745. } ).setLayout( {
  25746. name: 'mx_select',
  25747. type: 'float',
  25748. inputs: [
  25749. { name: 'b', type: 'bool' },
  25750. { name: 't', type: 'float' },
  25751. { name: 'f', type: 'float' }
  25752. ]
  25753. } );
  25754. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  25755. const b = bool( b_immutable ).toVar();
  25756. const val = float( val_immutable ).toVar();
  25757. return select( b, val.negate(), val );
  25758. } ).setLayout( {
  25759. name: 'mx_negate_if',
  25760. type: 'float',
  25761. inputs: [
  25762. { name: 'val', type: 'float' },
  25763. { name: 'b', type: 'bool' }
  25764. ]
  25765. } );
  25766. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  25767. const x = float( x_immutable ).toVar();
  25768. return int( floor( x ) );
  25769. } ).setLayout( {
  25770. name: 'mx_floor',
  25771. type: 'int',
  25772. inputs: [
  25773. { name: 'x', type: 'float' }
  25774. ]
  25775. } );
  25776. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  25777. const x = float( x_immutable ).toVar();
  25778. i.assign( mx_floor( x ) );
  25779. return x.sub( float( i ) );
  25780. } );
  25781. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  25782. const t = float( t_immutable ).toVar();
  25783. const s = float( s_immutable ).toVar();
  25784. const v3 = float( v3_immutable ).toVar();
  25785. const v2 = float( v2_immutable ).toVar();
  25786. const v1 = float( v1_immutable ).toVar();
  25787. const v0 = float( v0_immutable ).toVar();
  25788. const s1 = float( sub( 1.0, s ) ).toVar();
  25789. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  25790. } ).setLayout( {
  25791. name: 'mx_bilerp_0',
  25792. type: 'float',
  25793. inputs: [
  25794. { name: 'v0', type: 'float' },
  25795. { name: 'v1', type: 'float' },
  25796. { name: 'v2', type: 'float' },
  25797. { name: 'v3', type: 'float' },
  25798. { name: 's', type: 'float' },
  25799. { name: 't', type: 'float' }
  25800. ]
  25801. } );
  25802. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  25803. const t = float( t_immutable ).toVar();
  25804. const s = float( s_immutable ).toVar();
  25805. const v3 = vec3( v3_immutable ).toVar();
  25806. const v2 = vec3( v2_immutable ).toVar();
  25807. const v1 = vec3( v1_immutable ).toVar();
  25808. const v0 = vec3( v0_immutable ).toVar();
  25809. const s1 = float( sub( 1.0, s ) ).toVar();
  25810. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  25811. } ).setLayout( {
  25812. name: 'mx_bilerp_1',
  25813. type: 'vec3',
  25814. inputs: [
  25815. { name: 'v0', type: 'vec3' },
  25816. { name: 'v1', type: 'vec3' },
  25817. { name: 'v2', type: 'vec3' },
  25818. { name: 'v3', type: 'vec3' },
  25819. { name: 's', type: 'float' },
  25820. { name: 't', type: 'float' }
  25821. ]
  25822. } );
  25823. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  25824. 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 ] ) => {
  25825. const r = float( r_immutable ).toVar();
  25826. const t = float( t_immutable ).toVar();
  25827. const s = float( s_immutable ).toVar();
  25828. const v7 = float( v7_immutable ).toVar();
  25829. const v6 = float( v6_immutable ).toVar();
  25830. const v5 = float( v5_immutable ).toVar();
  25831. const v4 = float( v4_immutable ).toVar();
  25832. const v3 = float( v3_immutable ).toVar();
  25833. const v2 = float( v2_immutable ).toVar();
  25834. const v1 = float( v1_immutable ).toVar();
  25835. const v0 = float( v0_immutable ).toVar();
  25836. const s1 = float( sub( 1.0, s ) ).toVar();
  25837. const t1 = float( sub( 1.0, t ) ).toVar();
  25838. const r1 = float( sub( 1.0, r ) ).toVar();
  25839. 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 ) ) ) ) ) );
  25840. } ).setLayout( {
  25841. name: 'mx_trilerp_0',
  25842. type: 'float',
  25843. inputs: [
  25844. { name: 'v0', type: 'float' },
  25845. { name: 'v1', type: 'float' },
  25846. { name: 'v2', type: 'float' },
  25847. { name: 'v3', type: 'float' },
  25848. { name: 'v4', type: 'float' },
  25849. { name: 'v5', type: 'float' },
  25850. { name: 'v6', type: 'float' },
  25851. { name: 'v7', type: 'float' },
  25852. { name: 's', type: 'float' },
  25853. { name: 't', type: 'float' },
  25854. { name: 'r', type: 'float' }
  25855. ]
  25856. } );
  25857. 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 ] ) => {
  25858. const r = float( r_immutable ).toVar();
  25859. const t = float( t_immutable ).toVar();
  25860. const s = float( s_immutable ).toVar();
  25861. const v7 = vec3( v7_immutable ).toVar();
  25862. const v6 = vec3( v6_immutable ).toVar();
  25863. const v5 = vec3( v5_immutable ).toVar();
  25864. const v4 = vec3( v4_immutable ).toVar();
  25865. const v3 = vec3( v3_immutable ).toVar();
  25866. const v2 = vec3( v2_immutable ).toVar();
  25867. const v1 = vec3( v1_immutable ).toVar();
  25868. const v0 = vec3( v0_immutable ).toVar();
  25869. const s1 = float( sub( 1.0, s ) ).toVar();
  25870. const t1 = float( sub( 1.0, t ) ).toVar();
  25871. const r1 = float( sub( 1.0, r ) ).toVar();
  25872. 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 ) ) ) ) ) );
  25873. } ).setLayout( {
  25874. name: 'mx_trilerp_1',
  25875. type: 'vec3',
  25876. inputs: [
  25877. { name: 'v0', type: 'vec3' },
  25878. { name: 'v1', type: 'vec3' },
  25879. { name: 'v2', type: 'vec3' },
  25880. { name: 'v3', type: 'vec3' },
  25881. { name: 'v4', type: 'vec3' },
  25882. { name: 'v5', type: 'vec3' },
  25883. { name: 'v6', type: 'vec3' },
  25884. { name: 'v7', type: 'vec3' },
  25885. { name: 's', type: 'float' },
  25886. { name: 't', type: 'float' },
  25887. { name: 'r', type: 'float' }
  25888. ]
  25889. } );
  25890. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  25891. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  25892. const y = float( y_immutable ).toVar();
  25893. const x = float( x_immutable ).toVar();
  25894. const hash = uint( hash_immutable ).toVar();
  25895. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  25896. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  25897. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  25898. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  25899. } ).setLayout( {
  25900. name: 'mx_gradient_float_0',
  25901. type: 'float',
  25902. inputs: [
  25903. { name: 'hash', type: 'uint' },
  25904. { name: 'x', type: 'float' },
  25905. { name: 'y', type: 'float' }
  25906. ]
  25907. } );
  25908. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  25909. const z = float( z_immutable ).toVar();
  25910. const y = float( y_immutable ).toVar();
  25911. const x = float( x_immutable ).toVar();
  25912. const hash = uint( hash_immutable ).toVar();
  25913. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  25914. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  25915. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  25916. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  25917. } ).setLayout( {
  25918. name: 'mx_gradient_float_1',
  25919. type: 'float',
  25920. inputs: [
  25921. { name: 'hash', type: 'uint' },
  25922. { name: 'x', type: 'float' },
  25923. { name: 'y', type: 'float' },
  25924. { name: 'z', type: 'float' }
  25925. ]
  25926. } );
  25927. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  25928. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  25929. const y = float( y_immutable ).toVar();
  25930. const x = float( x_immutable ).toVar();
  25931. const hash = uvec3( hash_immutable ).toVar();
  25932. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  25933. } ).setLayout( {
  25934. name: 'mx_gradient_vec3_0',
  25935. type: 'vec3',
  25936. inputs: [
  25937. { name: 'hash', type: 'uvec3' },
  25938. { name: 'x', type: 'float' },
  25939. { name: 'y', type: 'float' }
  25940. ]
  25941. } );
  25942. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  25943. const z = float( z_immutable ).toVar();
  25944. const y = float( y_immutable ).toVar();
  25945. const x = float( x_immutable ).toVar();
  25946. const hash = uvec3( hash_immutable ).toVar();
  25947. 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 ) );
  25948. } ).setLayout( {
  25949. name: 'mx_gradient_vec3_1',
  25950. type: 'vec3',
  25951. inputs: [
  25952. { name: 'hash', type: 'uvec3' },
  25953. { name: 'x', type: 'float' },
  25954. { name: 'y', type: 'float' },
  25955. { name: 'z', type: 'float' }
  25956. ]
  25957. } );
  25958. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  25959. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  25960. const v = float( v_immutable ).toVar();
  25961. return mul( 0.6616, v );
  25962. } ).setLayout( {
  25963. name: 'mx_gradient_scale2d_0',
  25964. type: 'float',
  25965. inputs: [
  25966. { name: 'v', type: 'float' }
  25967. ]
  25968. } );
  25969. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  25970. const v = float( v_immutable ).toVar();
  25971. return mul( 0.9820, v );
  25972. } ).setLayout( {
  25973. name: 'mx_gradient_scale3d_0',
  25974. type: 'float',
  25975. inputs: [
  25976. { name: 'v', type: 'float' }
  25977. ]
  25978. } );
  25979. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  25980. const v = vec3( v_immutable ).toVar();
  25981. return mul( 0.6616, v );
  25982. } ).setLayout( {
  25983. name: 'mx_gradient_scale2d_1',
  25984. type: 'vec3',
  25985. inputs: [
  25986. { name: 'v', type: 'vec3' }
  25987. ]
  25988. } );
  25989. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  25990. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  25991. const v = vec3( v_immutable ).toVar();
  25992. return mul( 0.9820, v );
  25993. } ).setLayout( {
  25994. name: 'mx_gradient_scale3d_1',
  25995. type: 'vec3',
  25996. inputs: [
  25997. { name: 'v', type: 'vec3' }
  25998. ]
  25999. } );
  26000. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  26001. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  26002. const k = int( k_immutable ).toVar();
  26003. const x = uint( x_immutable ).toVar();
  26004. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  26005. } ).setLayout( {
  26006. name: 'mx_rotl32',
  26007. type: 'uint',
  26008. inputs: [
  26009. { name: 'x', type: 'uint' },
  26010. { name: 'k', type: 'int' }
  26011. ]
  26012. } );
  26013. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  26014. a.subAssign( c );
  26015. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  26016. c.addAssign( b );
  26017. b.subAssign( a );
  26018. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  26019. a.addAssign( c );
  26020. c.subAssign( b );
  26021. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  26022. b.addAssign( a );
  26023. a.subAssign( c );
  26024. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  26025. c.addAssign( b );
  26026. b.subAssign( a );
  26027. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  26028. a.addAssign( c );
  26029. c.subAssign( b );
  26030. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  26031. b.addAssign( a );
  26032. } );
  26033. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  26034. const c = uint( c_immutable ).toVar();
  26035. const b = uint( b_immutable ).toVar();
  26036. const a = uint( a_immutable ).toVar();
  26037. c.bitXorAssign( b );
  26038. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  26039. a.bitXorAssign( c );
  26040. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  26041. b.bitXorAssign( a );
  26042. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  26043. c.bitXorAssign( b );
  26044. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  26045. a.bitXorAssign( c );
  26046. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  26047. b.bitXorAssign( a );
  26048. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  26049. c.bitXorAssign( b );
  26050. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  26051. return c;
  26052. } ).setLayout( {
  26053. name: 'mx_bjfinal',
  26054. type: 'uint',
  26055. inputs: [
  26056. { name: 'a', type: 'uint' },
  26057. { name: 'b', type: 'uint' },
  26058. { name: 'c', type: 'uint' }
  26059. ]
  26060. } );
  26061. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  26062. const bits = uint( bits_immutable ).toVar();
  26063. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  26064. } ).setLayout( {
  26065. name: 'mx_bits_to_01',
  26066. type: 'float',
  26067. inputs: [
  26068. { name: 'bits', type: 'uint' }
  26069. ]
  26070. } );
  26071. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  26072. const t = float( t_immutable ).toVar();
  26073. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  26074. } ).setLayout( {
  26075. name: 'mx_fade',
  26076. type: 'float',
  26077. inputs: [
  26078. { name: 't', type: 'float' }
  26079. ]
  26080. } );
  26081. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  26082. const x = int( x_immutable ).toVar();
  26083. const len = uint( uint( 1 ) ).toVar();
  26084. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  26085. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  26086. } ).setLayout( {
  26087. name: 'mx_hash_int_0',
  26088. type: 'uint',
  26089. inputs: [
  26090. { name: 'x', type: 'int' }
  26091. ]
  26092. } );
  26093. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  26094. const y = int( y_immutable ).toVar();
  26095. const x = int( x_immutable ).toVar();
  26096. const len = uint( uint( 2 ) ).toVar();
  26097. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26098. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26099. a.addAssign( uint( x ) );
  26100. b.addAssign( uint( y ) );
  26101. return mx_bjfinal( a, b, c );
  26102. } ).setLayout( {
  26103. name: 'mx_hash_int_1',
  26104. type: 'uint',
  26105. inputs: [
  26106. { name: 'x', type: 'int' },
  26107. { name: 'y', type: 'int' }
  26108. ]
  26109. } );
  26110. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  26111. const z = int( z_immutable ).toVar();
  26112. const y = int( y_immutable ).toVar();
  26113. const x = int( x_immutable ).toVar();
  26114. const len = uint( uint( 3 ) ).toVar();
  26115. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26116. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26117. a.addAssign( uint( x ) );
  26118. b.addAssign( uint( y ) );
  26119. c.addAssign( uint( z ) );
  26120. return mx_bjfinal( a, b, c );
  26121. } ).setLayout( {
  26122. name: 'mx_hash_int_2',
  26123. type: 'uint',
  26124. inputs: [
  26125. { name: 'x', type: 'int' },
  26126. { name: 'y', type: 'int' },
  26127. { name: 'z', type: 'int' }
  26128. ]
  26129. } );
  26130. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  26131. const xx = int( xx_immutable ).toVar();
  26132. const z = int( z_immutable ).toVar();
  26133. const y = int( y_immutable ).toVar();
  26134. const x = int( x_immutable ).toVar();
  26135. const len = uint( uint( 4 ) ).toVar();
  26136. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26137. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26138. a.addAssign( uint( x ) );
  26139. b.addAssign( uint( y ) );
  26140. c.addAssign( uint( z ) );
  26141. mx_bjmix( a, b, c );
  26142. a.addAssign( uint( xx ) );
  26143. return mx_bjfinal( a, b, c );
  26144. } ).setLayout( {
  26145. name: 'mx_hash_int_3',
  26146. type: 'uint',
  26147. inputs: [
  26148. { name: 'x', type: 'int' },
  26149. { name: 'y', type: 'int' },
  26150. { name: 'z', type: 'int' },
  26151. { name: 'xx', type: 'int' }
  26152. ]
  26153. } );
  26154. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  26155. const yy = int( yy_immutable ).toVar();
  26156. const xx = int( xx_immutable ).toVar();
  26157. const z = int( z_immutable ).toVar();
  26158. const y = int( y_immutable ).toVar();
  26159. const x = int( x_immutable ).toVar();
  26160. const len = uint( uint( 5 ) ).toVar();
  26161. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26162. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26163. a.addAssign( uint( x ) );
  26164. b.addAssign( uint( y ) );
  26165. c.addAssign( uint( z ) );
  26166. mx_bjmix( a, b, c );
  26167. a.addAssign( uint( xx ) );
  26168. b.addAssign( uint( yy ) );
  26169. return mx_bjfinal( a, b, c );
  26170. } ).setLayout( {
  26171. name: 'mx_hash_int_4',
  26172. type: 'uint',
  26173. inputs: [
  26174. { name: 'x', type: 'int' },
  26175. { name: 'y', type: 'int' },
  26176. { name: 'z', type: 'int' },
  26177. { name: 'xx', type: 'int' },
  26178. { name: 'yy', type: 'int' }
  26179. ]
  26180. } );
  26181. 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 ] );
  26182. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  26183. const y = int( y_immutable ).toVar();
  26184. const x = int( x_immutable ).toVar();
  26185. const h = uint( mx_hash_int( x, y ) ).toVar();
  26186. const result = uvec3().toVar();
  26187. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  26188. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  26189. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  26190. return result;
  26191. } ).setLayout( {
  26192. name: 'mx_hash_vec3_0',
  26193. type: 'uvec3',
  26194. inputs: [
  26195. { name: 'x', type: 'int' },
  26196. { name: 'y', type: 'int' }
  26197. ]
  26198. } );
  26199. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  26200. const z = int( z_immutable ).toVar();
  26201. const y = int( y_immutable ).toVar();
  26202. const x = int( x_immutable ).toVar();
  26203. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  26204. const result = uvec3().toVar();
  26205. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  26206. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  26207. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  26208. return result;
  26209. } ).setLayout( {
  26210. name: 'mx_hash_vec3_1',
  26211. type: 'uvec3',
  26212. inputs: [
  26213. { name: 'x', type: 'int' },
  26214. { name: 'y', type: 'int' },
  26215. { name: 'z', type: 'int' }
  26216. ]
  26217. } );
  26218. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  26219. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26220. const p = vec2( p_immutable ).toVar();
  26221. const X = int().toVar(), Y = int().toVar();
  26222. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26223. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26224. const u = float( mx_fade( fx ) ).toVar();
  26225. const v = float( mx_fade( fy ) ).toVar();
  26226. 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();
  26227. return mx_gradient_scale2d( result );
  26228. } ).setLayout( {
  26229. name: 'mx_perlin_noise_float_0',
  26230. type: 'float',
  26231. inputs: [
  26232. { name: 'p', type: 'vec2' }
  26233. ]
  26234. } );
  26235. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26236. const p = vec3( p_immutable ).toVar();
  26237. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26238. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26239. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26240. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  26241. const u = float( mx_fade( fx ) ).toVar();
  26242. const v = float( mx_fade( fy ) ).toVar();
  26243. const w = float( mx_fade( fz ) ).toVar();
  26244. 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();
  26245. return mx_gradient_scale3d( result );
  26246. } ).setLayout( {
  26247. name: 'mx_perlin_noise_float_1',
  26248. type: 'float',
  26249. inputs: [
  26250. { name: 'p', type: 'vec3' }
  26251. ]
  26252. } );
  26253. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  26254. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26255. const p = vec2( p_immutable ).toVar();
  26256. const X = int().toVar(), Y = int().toVar();
  26257. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26258. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26259. const u = float( mx_fade( fx ) ).toVar();
  26260. const v = float( mx_fade( fy ) ).toVar();
  26261. 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();
  26262. return mx_gradient_scale2d( result );
  26263. } ).setLayout( {
  26264. name: 'mx_perlin_noise_vec3_0',
  26265. type: 'vec3',
  26266. inputs: [
  26267. { name: 'p', type: 'vec2' }
  26268. ]
  26269. } );
  26270. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26271. const p = vec3( p_immutable ).toVar();
  26272. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26273. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26274. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26275. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  26276. const u = float( mx_fade( fx ) ).toVar();
  26277. const v = float( mx_fade( fy ) ).toVar();
  26278. const w = float( mx_fade( fz ) ).toVar();
  26279. 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();
  26280. return mx_gradient_scale3d( result );
  26281. } ).setLayout( {
  26282. name: 'mx_perlin_noise_vec3_1',
  26283. type: 'vec3',
  26284. inputs: [
  26285. { name: 'p', type: 'vec3' }
  26286. ]
  26287. } );
  26288. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  26289. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26290. const p = float( p_immutable ).toVar();
  26291. const ix = int( mx_floor( p ) ).toVar();
  26292. return mx_bits_to_01( mx_hash_int( ix ) );
  26293. } ).setLayout( {
  26294. name: 'mx_cell_noise_float_0',
  26295. type: 'float',
  26296. inputs: [
  26297. { name: 'p', type: 'float' }
  26298. ]
  26299. } );
  26300. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26301. const p = vec2( p_immutable ).toVar();
  26302. const ix = int( mx_floor( p.x ) ).toVar();
  26303. const iy = int( mx_floor( p.y ) ).toVar();
  26304. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  26305. } ).setLayout( {
  26306. name: 'mx_cell_noise_float_1',
  26307. type: 'float',
  26308. inputs: [
  26309. { name: 'p', type: 'vec2' }
  26310. ]
  26311. } );
  26312. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26313. const p = vec3( p_immutable ).toVar();
  26314. const ix = int( mx_floor( p.x ) ).toVar();
  26315. const iy = int( mx_floor( p.y ) ).toVar();
  26316. const iz = int( mx_floor( p.z ) ).toVar();
  26317. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  26318. } ).setLayout( {
  26319. name: 'mx_cell_noise_float_2',
  26320. type: 'float',
  26321. inputs: [
  26322. { name: 'p', type: 'vec3' }
  26323. ]
  26324. } );
  26325. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26326. const p = vec4( p_immutable ).toVar();
  26327. const ix = int( mx_floor( p.x ) ).toVar();
  26328. const iy = int( mx_floor( p.y ) ).toVar();
  26329. const iz = int( mx_floor( p.z ) ).toVar();
  26330. const iw = int( mx_floor( p.w ) ).toVar();
  26331. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  26332. } ).setLayout( {
  26333. name: 'mx_cell_noise_float_3',
  26334. type: 'float',
  26335. inputs: [
  26336. { name: 'p', type: 'vec4' }
  26337. ]
  26338. } );
  26339. 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 ] );
  26340. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26341. const p = float( p_immutable ).toVar();
  26342. const ix = int( mx_floor( p ) ).toVar();
  26343. 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 ) ) ) );
  26344. } ).setLayout( {
  26345. name: 'mx_cell_noise_vec3_0',
  26346. type: 'vec3',
  26347. inputs: [
  26348. { name: 'p', type: 'float' }
  26349. ]
  26350. } );
  26351. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26352. const p = vec2( p_immutable ).toVar();
  26353. const ix = int( mx_floor( p.x ) ).toVar();
  26354. const iy = int( mx_floor( p.y ) ).toVar();
  26355. 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 ) ) ) );
  26356. } ).setLayout( {
  26357. name: 'mx_cell_noise_vec3_1',
  26358. type: 'vec3',
  26359. inputs: [
  26360. { name: 'p', type: 'vec2' }
  26361. ]
  26362. } );
  26363. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26364. const p = vec3( p_immutable ).toVar();
  26365. const ix = int( mx_floor( p.x ) ).toVar();
  26366. const iy = int( mx_floor( p.y ) ).toVar();
  26367. const iz = int( mx_floor( p.z ) ).toVar();
  26368. 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 ) ) ) );
  26369. } ).setLayout( {
  26370. name: 'mx_cell_noise_vec3_2',
  26371. type: 'vec3',
  26372. inputs: [
  26373. { name: 'p', type: 'vec3' }
  26374. ]
  26375. } );
  26376. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26377. const p = vec4( p_immutable ).toVar();
  26378. const ix = int( mx_floor( p.x ) ).toVar();
  26379. const iy = int( mx_floor( p.y ) ).toVar();
  26380. const iz = int( mx_floor( p.z ) ).toVar();
  26381. const iw = int( mx_floor( p.w ) ).toVar();
  26382. 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 ) ) ) );
  26383. } ).setLayout( {
  26384. name: 'mx_cell_noise_vec3_3',
  26385. type: 'vec3',
  26386. inputs: [
  26387. { name: 'p', type: 'vec4' }
  26388. ]
  26389. } );
  26390. 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 ] );
  26391. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26392. const diminish = float( diminish_immutable ).toVar();
  26393. const lacunarity = float( lacunarity_immutable ).toVar();
  26394. const octaves = int( octaves_immutable ).toVar();
  26395. const p = vec3( p_immutable ).toVar();
  26396. const result = float( 0.0 ).toVar();
  26397. const amplitude = float( 1.0 ).toVar();
  26398. Loop( octaves, () => {
  26399. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  26400. amplitude.mulAssign( diminish );
  26401. p.mulAssign( lacunarity );
  26402. } );
  26403. return result;
  26404. } ).setLayout( {
  26405. name: 'mx_fractal_noise_float',
  26406. type: 'float',
  26407. inputs: [
  26408. { name: 'p', type: 'vec3' },
  26409. { name: 'octaves', type: 'int' },
  26410. { name: 'lacunarity', type: 'float' },
  26411. { name: 'diminish', type: 'float' }
  26412. ]
  26413. } );
  26414. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26415. const diminish = float( diminish_immutable ).toVar();
  26416. const lacunarity = float( lacunarity_immutable ).toVar();
  26417. const octaves = int( octaves_immutable ).toVar();
  26418. const p = vec3( p_immutable ).toVar();
  26419. const result = vec3( 0.0 ).toVar();
  26420. const amplitude = float( 1.0 ).toVar();
  26421. Loop( octaves, () => {
  26422. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  26423. amplitude.mulAssign( diminish );
  26424. p.mulAssign( lacunarity );
  26425. } );
  26426. return result;
  26427. } ).setLayout( {
  26428. name: 'mx_fractal_noise_vec3',
  26429. type: 'vec3',
  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_vec2$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. 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 ) );
  26443. } ).setLayout( {
  26444. name: 'mx_fractal_noise_vec2',
  26445. type: 'vec2',
  26446. inputs: [
  26447. { name: 'p', type: 'vec3' },
  26448. { name: 'octaves', type: 'int' },
  26449. { name: 'lacunarity', type: 'float' },
  26450. { name: 'diminish', type: 'float' }
  26451. ]
  26452. } );
  26453. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26454. const diminish = float( diminish_immutable ).toVar();
  26455. const lacunarity = float( lacunarity_immutable ).toVar();
  26456. const octaves = int( octaves_immutable ).toVar();
  26457. const p = vec3( p_immutable ).toVar();
  26458. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  26459. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  26460. return vec4( c, f );
  26461. } ).setLayout( {
  26462. name: 'mx_fractal_noise_vec4',
  26463. type: 'vec4',
  26464. inputs: [
  26465. { name: 'p', type: 'vec3' },
  26466. { name: 'octaves', type: 'int' },
  26467. { name: 'lacunarity', type: 'float' },
  26468. { name: 'diminish', type: 'float' }
  26469. ]
  26470. } );
  26471. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  26472. const metric = int( metric_immutable ).toVar();
  26473. const jitter = float( jitter_immutable ).toVar();
  26474. const yoff = int( yoff_immutable ).toVar();
  26475. const xoff = int( xoff_immutable ).toVar();
  26476. const y = int( y_immutable ).toVar();
  26477. const x = int( x_immutable ).toVar();
  26478. const p = vec2( p_immutable ).toVar();
  26479. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  26480. const off = vec2( tmp.x, tmp.y ).toVar();
  26481. off.subAssign( 0.5 );
  26482. off.mulAssign( jitter );
  26483. off.addAssign( 0.5 );
  26484. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  26485. const diff = vec2( cellpos.sub( p ) ).toVar();
  26486. If( metric.equal( int( 2 ) ), () => {
  26487. return abs( diff.x ).add( abs( diff.y ) );
  26488. } );
  26489. If( metric.equal( int( 3 ) ), () => {
  26490. return max$1( abs( diff.x ), abs( diff.y ) );
  26491. } );
  26492. return dot( diff, diff );
  26493. } ).setLayout( {
  26494. name: 'mx_worley_distance_0',
  26495. type: 'float',
  26496. inputs: [
  26497. { name: 'p', type: 'vec2' },
  26498. { name: 'x', type: 'int' },
  26499. { name: 'y', type: 'int' },
  26500. { name: 'xoff', type: 'int' },
  26501. { name: 'yoff', type: 'int' },
  26502. { name: 'jitter', type: 'float' },
  26503. { name: 'metric', type: 'int' }
  26504. ]
  26505. } );
  26506. 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 ] ) => {
  26507. const metric = int( metric_immutable ).toVar();
  26508. const jitter = float( jitter_immutable ).toVar();
  26509. const zoff = int( zoff_immutable ).toVar();
  26510. const yoff = int( yoff_immutable ).toVar();
  26511. const xoff = int( xoff_immutable ).toVar();
  26512. const z = int( z_immutable ).toVar();
  26513. const y = int( y_immutable ).toVar();
  26514. const x = int( x_immutable ).toVar();
  26515. const p = vec3( p_immutable ).toVar();
  26516. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  26517. off.subAssign( 0.5 );
  26518. off.mulAssign( jitter );
  26519. off.addAssign( 0.5 );
  26520. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  26521. const diff = vec3( cellpos.sub( p ) ).toVar();
  26522. If( metric.equal( int( 2 ) ), () => {
  26523. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  26524. } );
  26525. If( metric.equal( int( 3 ) ), () => {
  26526. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  26527. } );
  26528. return dot( diff, diff );
  26529. } ).setLayout( {
  26530. name: 'mx_worley_distance_1',
  26531. type: 'float',
  26532. inputs: [
  26533. { name: 'p', type: 'vec3' },
  26534. { name: 'x', type: 'int' },
  26535. { name: 'y', type: 'int' },
  26536. { name: 'z', type: 'int' },
  26537. { name: 'xoff', type: 'int' },
  26538. { name: 'yoff', type: 'int' },
  26539. { name: 'zoff', type: 'int' },
  26540. { name: 'jitter', type: 'float' },
  26541. { name: 'metric', type: 'int' }
  26542. ]
  26543. } );
  26544. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  26545. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26546. const metric = int( metric_immutable ).toVar();
  26547. const jitter = float( jitter_immutable ).toVar();
  26548. const p = vec2( p_immutable ).toVar();
  26549. const X = int().toVar(), Y = int().toVar();
  26550. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  26551. const sqdist = float( 1e6 ).toVar();
  26552. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26553. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26554. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  26555. sqdist.assign( min$1( sqdist, dist ) );
  26556. } );
  26557. } );
  26558. If( metric.equal( int( 0 ) ), () => {
  26559. sqdist.assign( sqrt( sqdist ) );
  26560. } );
  26561. return sqdist;
  26562. } ).setLayout( {
  26563. name: 'mx_worley_noise_float_0',
  26564. type: 'float',
  26565. inputs: [
  26566. { name: 'p', type: 'vec2' },
  26567. { name: 'jitter', type: 'float' },
  26568. { name: 'metric', type: 'int' }
  26569. ]
  26570. } );
  26571. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26572. const metric = int( metric_immutable ).toVar();
  26573. const jitter = float( jitter_immutable ).toVar();
  26574. const p = vec2( p_immutable ).toVar();
  26575. const X = int().toVar(), Y = int().toVar();
  26576. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  26577. const sqdist = vec2( 1e6, 1e6 ).toVar();
  26578. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26579. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26580. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  26581. If( dist.lessThan( sqdist.x ), () => {
  26582. sqdist.y.assign( sqdist.x );
  26583. sqdist.x.assign( dist );
  26584. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  26585. sqdist.y.assign( dist );
  26586. } );
  26587. } );
  26588. } );
  26589. If( metric.equal( int( 0 ) ), () => {
  26590. sqdist.assign( sqrt( sqdist ) );
  26591. } );
  26592. return sqdist;
  26593. } ).setLayout( {
  26594. name: 'mx_worley_noise_vec2_0',
  26595. type: 'vec2',
  26596. inputs: [
  26597. { name: 'p', type: 'vec2' },
  26598. { name: 'jitter', type: 'float' },
  26599. { name: 'metric', type: 'int' }
  26600. ]
  26601. } );
  26602. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26603. const metric = int( metric_immutable ).toVar();
  26604. const jitter = float( jitter_immutable ).toVar();
  26605. const p = vec2( p_immutable ).toVar();
  26606. const X = int().toVar(), Y = int().toVar();
  26607. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  26608. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  26609. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26610. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26611. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  26612. If( dist.lessThan( sqdist.x ), () => {
  26613. sqdist.z.assign( sqdist.y );
  26614. sqdist.y.assign( sqdist.x );
  26615. sqdist.x.assign( dist );
  26616. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  26617. sqdist.z.assign( sqdist.y );
  26618. sqdist.y.assign( dist );
  26619. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  26620. sqdist.z.assign( dist );
  26621. } );
  26622. } );
  26623. } );
  26624. If( metric.equal( int( 0 ) ), () => {
  26625. sqdist.assign( sqrt( sqdist ) );
  26626. } );
  26627. return sqdist;
  26628. } ).setLayout( {
  26629. name: 'mx_worley_noise_vec3_0',
  26630. type: 'vec3',
  26631. inputs: [
  26632. { name: 'p', type: 'vec2' },
  26633. { name: 'jitter', type: 'float' },
  26634. { name: 'metric', type: 'int' }
  26635. ]
  26636. } );
  26637. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26638. const metric = int( metric_immutable ).toVar();
  26639. const jitter = float( jitter_immutable ).toVar();
  26640. const p = vec3( p_immutable ).toVar();
  26641. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26642. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  26643. const sqdist = float( 1e6 ).toVar();
  26644. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26645. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26646. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  26647. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  26648. sqdist.assign( min$1( sqdist, dist ) );
  26649. } );
  26650. } );
  26651. } );
  26652. If( metric.equal( int( 0 ) ), () => {
  26653. sqdist.assign( sqrt( sqdist ) );
  26654. } );
  26655. return sqdist;
  26656. } ).setLayout( {
  26657. name: 'mx_worley_noise_float_1',
  26658. type: 'float',
  26659. inputs: [
  26660. { name: 'p', type: 'vec3' },
  26661. { name: 'jitter', type: 'float' },
  26662. { name: 'metric', type: 'int' }
  26663. ]
  26664. } );
  26665. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  26666. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26667. const metric = int( metric_immutable ).toVar();
  26668. const jitter = float( jitter_immutable ).toVar();
  26669. const p = vec3( p_immutable ).toVar();
  26670. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26671. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  26672. const sqdist = vec2( 1e6, 1e6 ).toVar();
  26673. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26674. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26675. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  26676. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  26677. If( dist.lessThan( sqdist.x ), () => {
  26678. sqdist.y.assign( sqdist.x );
  26679. sqdist.x.assign( dist );
  26680. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  26681. sqdist.y.assign( dist );
  26682. } );
  26683. } );
  26684. } );
  26685. } );
  26686. If( metric.equal( int( 0 ) ), () => {
  26687. sqdist.assign( sqrt( sqdist ) );
  26688. } );
  26689. return sqdist;
  26690. } ).setLayout( {
  26691. name: 'mx_worley_noise_vec2_1',
  26692. type: 'vec2',
  26693. inputs: [
  26694. { name: 'p', type: 'vec3' },
  26695. { name: 'jitter', type: 'float' },
  26696. { name: 'metric', type: 'int' }
  26697. ]
  26698. } );
  26699. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  26700. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26701. const metric = int( metric_immutable ).toVar();
  26702. const jitter = float( jitter_immutable ).toVar();
  26703. const p = vec3( p_immutable ).toVar();
  26704. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26705. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  26706. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  26707. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26708. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26709. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  26710. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  26711. If( dist.lessThan( sqdist.x ), () => {
  26712. sqdist.z.assign( sqdist.y );
  26713. sqdist.y.assign( sqdist.x );
  26714. sqdist.x.assign( dist );
  26715. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  26716. sqdist.z.assign( sqdist.y );
  26717. sqdist.y.assign( dist );
  26718. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  26719. sqdist.z.assign( dist );
  26720. } );
  26721. } );
  26722. } );
  26723. } );
  26724. If( metric.equal( int( 0 ) ), () => {
  26725. sqdist.assign( sqrt( sqdist ) );
  26726. } );
  26727. return sqdist;
  26728. } ).setLayout( {
  26729. name: 'mx_worley_noise_vec3_1',
  26730. type: 'vec3',
  26731. inputs: [
  26732. { name: 'p', type: 'vec3' },
  26733. { name: 'jitter', type: 'float' },
  26734. { name: 'metric', type: 'int' }
  26735. ]
  26736. } );
  26737. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  26738. // Three.js Transpiler
  26739. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  26740. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  26741. const s = hsv.y;
  26742. const v = hsv.z;
  26743. const result = vec3().toVar();
  26744. If( s.lessThan( 0.0001 ), () => {
  26745. result.assign( vec3( v, v, v ) );
  26746. } ).Else( () => {
  26747. let h = hsv.x;
  26748. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  26749. const hi = int( trunc( h ) );
  26750. const f = h.sub( float( hi ) );
  26751. const p = v.mul( s.oneMinus() );
  26752. const q = v.mul( s.mul( f ).oneMinus() );
  26753. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  26754. If( hi.equal( int( 0 ) ), () => {
  26755. result.assign( vec3( v, t, p ) );
  26756. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  26757. result.assign( vec3( q, v, p ) );
  26758. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  26759. result.assign( vec3( p, v, t ) );
  26760. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  26761. result.assign( vec3( p, q, v ) );
  26762. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  26763. result.assign( vec3( t, p, v ) );
  26764. } ).Else( () => {
  26765. result.assign( vec3( v, p, q ) );
  26766. } );
  26767. } );
  26768. return result;
  26769. } ).setLayout( {
  26770. name: 'mx_hsvtorgb',
  26771. type: 'vec3',
  26772. inputs: [
  26773. { name: 'hsv', type: 'vec3' }
  26774. ]
  26775. } );
  26776. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  26777. const c = vec3( c_immutable ).toVar();
  26778. const r = float( c.x ).toVar();
  26779. const g = float( c.y ).toVar();
  26780. const b = float( c.z ).toVar();
  26781. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  26782. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  26783. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  26784. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  26785. v.assign( maxcomp );
  26786. If( maxcomp.greaterThan( 0.0 ), () => {
  26787. s.assign( delta.div( maxcomp ) );
  26788. } ).Else( () => {
  26789. s.assign( 0.0 );
  26790. } );
  26791. If( s.lessThanEqual( 0.0 ), () => {
  26792. h.assign( 0.0 );
  26793. } ).Else( () => {
  26794. If( r.greaterThanEqual( maxcomp ), () => {
  26795. h.assign( g.sub( b ).div( delta ) );
  26796. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  26797. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  26798. } ).Else( () => {
  26799. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  26800. } );
  26801. h.mulAssign( 1.0 / 6.0 );
  26802. If( h.lessThan( 0.0 ), () => {
  26803. h.addAssign( 1.0 );
  26804. } );
  26805. } );
  26806. return vec3( h, s, v );
  26807. } ).setLayout( {
  26808. name: 'mx_rgbtohsv',
  26809. type: 'vec3',
  26810. inputs: [
  26811. { name: 'c', type: 'vec3' }
  26812. ]
  26813. } );
  26814. // Three.js Transpiler
  26815. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  26816. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  26817. const color = vec3( color_immutable ).toVar();
  26818. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  26819. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  26820. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  26821. return mix( linSeg, powSeg, isAbove );
  26822. } ).setLayout( {
  26823. name: 'mx_srgb_texture_to_lin_rec709',
  26824. type: 'vec3',
  26825. inputs: [
  26826. { name: 'color', type: 'vec3' }
  26827. ]
  26828. } );
  26829. const mx_aastep = ( threshold, value ) => {
  26830. threshold = float( threshold );
  26831. value = float( value );
  26832. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  26833. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  26834. };
  26835. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  26836. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  26837. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  26838. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  26839. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  26840. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  26841. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  26842. const mx_safepower = ( in1, in2 = 1 ) => {
  26843. in1 = float( in1 );
  26844. return in1.abs().pow( in2 ).mul( in1.sign() );
  26845. };
  26846. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  26847. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  26848. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  26849. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  26850. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  26851. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  26852. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  26853. return noise_vec4.mul( amplitude ).add( pivot );
  26854. };
  26855. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  26856. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  26857. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  26858. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  26859. 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 );
  26860. 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 );
  26861. 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 );
  26862. 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 );
  26863. /** @module getParallaxCorrectNormal **/
  26864. /**
  26865. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  26866. *
  26867. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  26868. *
  26869. * ```js
  26870. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  26871. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  26872. * ```
  26873. * @function
  26874. * @param {Node<vec3>} normal - The normal to correct.
  26875. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  26876. * @param {Node<vec3>} cubePos - The cube position.
  26877. * @return {Node<vec3>} The parallax corrected normal.
  26878. */
  26879. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  26880. const nDir = normalize( normal ).toVar( 'nDir' );
  26881. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmax' );
  26882. const rbmin = sub( float( - 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmin' );
  26883. const rbminmax = vec3().toVar( 'rbminmax' );
  26884. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  26885. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  26886. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  26887. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar( 'correction' );
  26888. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar( 'boxIntersection' );
  26889. return boxIntersection.sub( cubePos );
  26890. } );
  26891. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  26892. // normal is assumed to have unit length
  26893. const x = normal.x, y = normal.y, z = normal.z;
  26894. // band 0
  26895. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  26896. // band 1
  26897. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  26898. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  26899. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  26900. // band 2
  26901. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  26902. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  26903. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  26904. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  26905. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  26906. return result;
  26907. } );
  26908. // constants
  26909. var TSL = /*#__PURE__*/Object.freeze({
  26910. __proto__: null,
  26911. BRDF_GGX: BRDF_GGX,
  26912. BRDF_Lambert: BRDF_Lambert,
  26913. BasicShadowFilter: BasicShadowFilter,
  26914. Break: Break,
  26915. Continue: Continue,
  26916. DFGApprox: DFGApprox,
  26917. D_GGX: D_GGX,
  26918. Discard: Discard,
  26919. EPSILON: EPSILON,
  26920. F_Schlick: F_Schlick,
  26921. Fn: Fn,
  26922. INFINITY: INFINITY,
  26923. If: If,
  26924. Loop: Loop,
  26925. NodeAccess: NodeAccess,
  26926. NodeShaderStage: NodeShaderStage,
  26927. NodeType: NodeType,
  26928. NodeUpdateType: NodeUpdateType,
  26929. PCFShadowFilter: PCFShadowFilter,
  26930. PCFSoftShadowFilter: PCFSoftShadowFilter,
  26931. PI: PI,
  26932. PI2: PI2,
  26933. Return: Return,
  26934. Schlick_to_F0: Schlick_to_F0,
  26935. ScriptableNodeResources: ScriptableNodeResources,
  26936. ShaderNode: ShaderNode,
  26937. TBNViewMatrix: TBNViewMatrix,
  26938. VSMShadowFilter: VSMShadowFilter,
  26939. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  26940. abs: abs,
  26941. acesFilmicToneMapping: acesFilmicToneMapping,
  26942. acos: acos,
  26943. add: add,
  26944. addMethodChaining: addMethodChaining,
  26945. addNodeElement: addNodeElement,
  26946. agxToneMapping: agxToneMapping,
  26947. all: all,
  26948. alphaT: alphaT,
  26949. and: and,
  26950. anisotropy: anisotropy,
  26951. anisotropyB: anisotropyB,
  26952. anisotropyT: anisotropyT,
  26953. any: any,
  26954. append: append,
  26955. arrayBuffer: arrayBuffer,
  26956. asin: asin,
  26957. assign: assign,
  26958. atan: atan,
  26959. atan2: atan2,
  26960. atomicAdd: atomicAdd,
  26961. atomicAnd: atomicAnd,
  26962. atomicFunc: atomicFunc,
  26963. atomicMax: atomicMax,
  26964. atomicMin: atomicMin,
  26965. atomicOr: atomicOr,
  26966. atomicStore: atomicStore,
  26967. atomicSub: atomicSub,
  26968. atomicXor: atomicXor,
  26969. attenuationColor: attenuationColor,
  26970. attenuationDistance: attenuationDistance,
  26971. attribute: attribute,
  26972. attributeArray: attributeArray,
  26973. backgroundBlurriness: backgroundBlurriness,
  26974. backgroundIntensity: backgroundIntensity,
  26975. backgroundRotation: backgroundRotation,
  26976. batch: batch,
  26977. billboarding: billboarding,
  26978. bitAnd: bitAnd,
  26979. bitNot: bitNot,
  26980. bitOr: bitOr,
  26981. bitXor: bitXor,
  26982. bitangentGeometry: bitangentGeometry,
  26983. bitangentLocal: bitangentLocal,
  26984. bitangentView: bitangentView,
  26985. bitangentWorld: bitangentWorld,
  26986. bitcast: bitcast,
  26987. blendBurn: blendBurn,
  26988. blendColor: blendColor,
  26989. blendDodge: blendDodge,
  26990. blendOverlay: blendOverlay,
  26991. blendScreen: blendScreen,
  26992. blur: blur,
  26993. bool: bool,
  26994. buffer: buffer,
  26995. bufferAttribute: bufferAttribute,
  26996. bumpMap: bumpMap,
  26997. burn: burn,
  26998. bvec2: bvec2,
  26999. bvec3: bvec3,
  27000. bvec4: bvec4,
  27001. bypass: bypass,
  27002. cache: cache,
  27003. call: call,
  27004. cameraFar: cameraFar,
  27005. cameraNear: cameraNear,
  27006. cameraNormalMatrix: cameraNormalMatrix,
  27007. cameraPosition: cameraPosition,
  27008. cameraProjectionMatrix: cameraProjectionMatrix,
  27009. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  27010. cameraViewMatrix: cameraViewMatrix,
  27011. cameraWorldMatrix: cameraWorldMatrix,
  27012. cbrt: cbrt,
  27013. cdl: cdl,
  27014. ceil: ceil,
  27015. checker: checker,
  27016. cineonToneMapping: cineonToneMapping,
  27017. clamp: clamp,
  27018. clearcoat: clearcoat,
  27019. clearcoatRoughness: clearcoatRoughness,
  27020. code: code,
  27021. color: color,
  27022. colorSpaceToWorking: colorSpaceToWorking,
  27023. colorToDirection: colorToDirection,
  27024. compute: compute,
  27025. cond: cond,
  27026. context: context,
  27027. convert: convert,
  27028. convertColorSpace: convertColorSpace,
  27029. convertToTexture: convertToTexture,
  27030. cos: cos,
  27031. cross: cross,
  27032. cubeTexture: cubeTexture,
  27033. dFdx: dFdx,
  27034. dFdy: dFdy,
  27035. dashSize: dashSize,
  27036. defaultBuildStages: defaultBuildStages,
  27037. defaultShaderStages: defaultShaderStages,
  27038. defined: defined,
  27039. degrees: degrees,
  27040. deltaTime: deltaTime,
  27041. densityFog: densityFog,
  27042. densityFogFactor: densityFogFactor,
  27043. depth: depth,
  27044. depthPass: depthPass,
  27045. difference: difference,
  27046. diffuseColor: diffuseColor,
  27047. directPointLight: directPointLight,
  27048. directionToColor: directionToColor,
  27049. dispersion: dispersion,
  27050. distance: distance,
  27051. div: div,
  27052. dodge: dodge,
  27053. dot: dot,
  27054. drawIndex: drawIndex,
  27055. dynamicBufferAttribute: dynamicBufferAttribute,
  27056. element: element,
  27057. emissive: emissive,
  27058. equal: equal,
  27059. equals: equals,
  27060. equirectUV: equirectUV,
  27061. exp: exp,
  27062. exp2: exp2,
  27063. expression: expression,
  27064. faceDirection: faceDirection,
  27065. faceForward: faceForward,
  27066. faceforward: faceforward,
  27067. float: float,
  27068. floor: floor,
  27069. fog: fog,
  27070. fract: fract,
  27071. frameGroup: frameGroup,
  27072. frameId: frameId,
  27073. frontFacing: frontFacing,
  27074. fwidth: fwidth,
  27075. gain: gain,
  27076. gapSize: gapSize,
  27077. getConstNodeType: getConstNodeType,
  27078. getCurrentStack: getCurrentStack,
  27079. getDirection: getDirection,
  27080. getDistanceAttenuation: getDistanceAttenuation,
  27081. getGeometryRoughness: getGeometryRoughness,
  27082. getNormalFromDepth: getNormalFromDepth,
  27083. getParallaxCorrectNormal: getParallaxCorrectNormal,
  27084. getRoughness: getRoughness,
  27085. getScreenPosition: getScreenPosition,
  27086. getShIrradianceAt: getShIrradianceAt,
  27087. getTextureIndex: getTextureIndex,
  27088. getViewPosition: getViewPosition,
  27089. glsl: glsl,
  27090. glslFn: glslFn,
  27091. grayscale: grayscale,
  27092. greaterThan: greaterThan,
  27093. greaterThanEqual: greaterThanEqual,
  27094. hash: hash,
  27095. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  27096. highpModelViewMatrix: highpModelViewMatrix,
  27097. hue: hue,
  27098. instance: instance,
  27099. instanceIndex: instanceIndex,
  27100. instancedArray: instancedArray,
  27101. instancedBufferAttribute: instancedBufferAttribute,
  27102. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  27103. instancedMesh: instancedMesh,
  27104. int: int,
  27105. inverseSqrt: inverseSqrt,
  27106. inversesqrt: inversesqrt,
  27107. invocationLocalIndex: invocationLocalIndex,
  27108. invocationSubgroupIndex: invocationSubgroupIndex,
  27109. ior: ior,
  27110. iridescence: iridescence,
  27111. iridescenceIOR: iridescenceIOR,
  27112. iridescenceThickness: iridescenceThickness,
  27113. ivec2: ivec2,
  27114. ivec3: ivec3,
  27115. ivec4: ivec4,
  27116. js: js,
  27117. label: label,
  27118. length: length,
  27119. lengthSq: lengthSq,
  27120. lessThan: lessThan,
  27121. lessThanEqual: lessThanEqual,
  27122. lightPosition: lightPosition,
  27123. lightProjectionUV: lightProjectionUV,
  27124. lightShadowMatrix: lightShadowMatrix,
  27125. lightTargetDirection: lightTargetDirection,
  27126. lightTargetPosition: lightTargetPosition,
  27127. lightViewPosition: lightViewPosition,
  27128. lightingContext: lightingContext,
  27129. lights: lights,
  27130. linearDepth: linearDepth,
  27131. linearToneMapping: linearToneMapping,
  27132. localId: localId,
  27133. log: log,
  27134. log2: log2,
  27135. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  27136. loop: loop,
  27137. luminance: luminance,
  27138. mat2: mat2,
  27139. mat3: mat3,
  27140. mat4: mat4,
  27141. matcapUV: matcapUV,
  27142. materialAO: materialAO,
  27143. materialAlphaTest: materialAlphaTest,
  27144. materialAnisotropy: materialAnisotropy,
  27145. materialAnisotropyVector: materialAnisotropyVector,
  27146. materialAttenuationColor: materialAttenuationColor,
  27147. materialAttenuationDistance: materialAttenuationDistance,
  27148. materialClearcoat: materialClearcoat,
  27149. materialClearcoatNormal: materialClearcoatNormal,
  27150. materialClearcoatRoughness: materialClearcoatRoughness,
  27151. materialColor: materialColor,
  27152. materialDispersion: materialDispersion,
  27153. materialEmissive: materialEmissive,
  27154. materialIOR: materialIOR,
  27155. materialIridescence: materialIridescence,
  27156. materialIridescenceIOR: materialIridescenceIOR,
  27157. materialIridescenceThickness: materialIridescenceThickness,
  27158. materialLightMap: materialLightMap,
  27159. materialLineDashOffset: materialLineDashOffset,
  27160. materialLineDashSize: materialLineDashSize,
  27161. materialLineGapSize: materialLineGapSize,
  27162. materialLineScale: materialLineScale,
  27163. materialLineWidth: materialLineWidth,
  27164. materialMetalness: materialMetalness,
  27165. materialNormal: materialNormal,
  27166. materialOpacity: materialOpacity,
  27167. materialPointWidth: materialPointWidth,
  27168. materialReference: materialReference,
  27169. materialReflectivity: materialReflectivity,
  27170. materialRefractionRatio: materialRefractionRatio,
  27171. materialRotation: materialRotation,
  27172. materialRoughness: materialRoughness,
  27173. materialSheen: materialSheen,
  27174. materialSheenRoughness: materialSheenRoughness,
  27175. materialShininess: materialShininess,
  27176. materialSpecular: materialSpecular,
  27177. materialSpecularColor: materialSpecularColor,
  27178. materialSpecularIntensity: materialSpecularIntensity,
  27179. materialSpecularStrength: materialSpecularStrength,
  27180. materialThickness: materialThickness,
  27181. materialTransmission: materialTransmission,
  27182. max: max$1,
  27183. maxMipLevel: maxMipLevel,
  27184. mediumpModelViewMatrix: mediumpModelViewMatrix,
  27185. metalness: metalness,
  27186. min: min$1,
  27187. mix: mix,
  27188. mixElement: mixElement,
  27189. mod: mod,
  27190. modInt: modInt,
  27191. modelDirection: modelDirection,
  27192. modelNormalMatrix: modelNormalMatrix,
  27193. modelPosition: modelPosition,
  27194. modelScale: modelScale,
  27195. modelViewMatrix: modelViewMatrix,
  27196. modelViewPosition: modelViewPosition,
  27197. modelViewProjection: modelViewProjection,
  27198. modelWorldMatrix: modelWorldMatrix,
  27199. modelWorldMatrixInverse: modelWorldMatrixInverse,
  27200. morphReference: morphReference,
  27201. mrt: mrt,
  27202. mul: mul,
  27203. mx_aastep: mx_aastep,
  27204. mx_cell_noise_float: mx_cell_noise_float,
  27205. mx_contrast: mx_contrast,
  27206. mx_fractal_noise_float: mx_fractal_noise_float,
  27207. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  27208. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  27209. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  27210. mx_hsvtorgb: mx_hsvtorgb,
  27211. mx_noise_float: mx_noise_float,
  27212. mx_noise_vec3: mx_noise_vec3,
  27213. mx_noise_vec4: mx_noise_vec4,
  27214. mx_ramplr: mx_ramplr,
  27215. mx_ramptb: mx_ramptb,
  27216. mx_rgbtohsv: mx_rgbtohsv,
  27217. mx_safepower: mx_safepower,
  27218. mx_splitlr: mx_splitlr,
  27219. mx_splittb: mx_splittb,
  27220. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  27221. mx_transform_uv: mx_transform_uv,
  27222. mx_worley_noise_float: mx_worley_noise_float,
  27223. mx_worley_noise_vec2: mx_worley_noise_vec2,
  27224. mx_worley_noise_vec3: mx_worley_noise_vec3,
  27225. negate: negate,
  27226. neutralToneMapping: neutralToneMapping,
  27227. nodeArray: nodeArray,
  27228. nodeImmutable: nodeImmutable,
  27229. nodeObject: nodeObject,
  27230. nodeObjects: nodeObjects,
  27231. nodeProxy: nodeProxy,
  27232. normalFlat: normalFlat,
  27233. normalGeometry: normalGeometry,
  27234. normalLocal: normalLocal,
  27235. normalMap: normalMap,
  27236. normalView: normalView,
  27237. normalWorld: normalWorld,
  27238. normalize: normalize,
  27239. not: not,
  27240. notEqual: notEqual,
  27241. numWorkgroups: numWorkgroups,
  27242. objectDirection: objectDirection,
  27243. objectGroup: objectGroup,
  27244. objectPosition: objectPosition,
  27245. objectScale: objectScale,
  27246. objectViewPosition: objectViewPosition,
  27247. objectWorldMatrix: objectWorldMatrix,
  27248. oneMinus: oneMinus,
  27249. or: or,
  27250. orthographicDepthToViewZ: orthographicDepthToViewZ,
  27251. oscSawtooth: oscSawtooth,
  27252. oscSine: oscSine,
  27253. oscSquare: oscSquare,
  27254. oscTriangle: oscTriangle,
  27255. output: output,
  27256. outputStruct: outputStruct,
  27257. overlay: overlay,
  27258. overloadingFn: overloadingFn,
  27259. parabola: parabola,
  27260. parallaxDirection: parallaxDirection,
  27261. parallaxUV: parallaxUV,
  27262. parameter: parameter,
  27263. pass: pass,
  27264. passTexture: passTexture,
  27265. pcurve: pcurve,
  27266. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  27267. pmremTexture: pmremTexture,
  27268. pointUV: pointUV,
  27269. pointWidth: pointWidth,
  27270. positionGeometry: positionGeometry,
  27271. positionLocal: positionLocal,
  27272. positionPrevious: positionPrevious,
  27273. positionView: positionView,
  27274. positionViewDirection: positionViewDirection,
  27275. positionWorld: positionWorld,
  27276. positionWorldDirection: positionWorldDirection,
  27277. posterize: posterize,
  27278. pow: pow,
  27279. pow2: pow2,
  27280. pow3: pow3,
  27281. pow4: pow4,
  27282. property: property,
  27283. radians: radians,
  27284. rand: rand,
  27285. range: range,
  27286. rangeFog: rangeFog,
  27287. rangeFogFactor: rangeFogFactor,
  27288. reciprocal: reciprocal,
  27289. reference: reference,
  27290. referenceBuffer: referenceBuffer,
  27291. reflect: reflect,
  27292. reflectVector: reflectVector,
  27293. reflectView: reflectView,
  27294. reflector: reflector,
  27295. refract: refract,
  27296. refractVector: refractVector,
  27297. refractView: refractView,
  27298. reinhardToneMapping: reinhardToneMapping,
  27299. remainder: remainder,
  27300. remap: remap,
  27301. remapClamp: remapClamp,
  27302. renderGroup: renderGroup,
  27303. renderOutput: renderOutput,
  27304. rendererReference: rendererReference,
  27305. rotate: rotate,
  27306. rotateUV: rotateUV,
  27307. roughness: roughness,
  27308. round: round,
  27309. rtt: rtt,
  27310. sRGBTransferEOTF: sRGBTransferEOTF,
  27311. sRGBTransferOETF: sRGBTransferOETF,
  27312. sampler: sampler,
  27313. saturate: saturate,
  27314. saturation: saturation,
  27315. screen: screen,
  27316. screenCoordinate: screenCoordinate,
  27317. screenSize: screenSize,
  27318. screenUV: screenUV,
  27319. scriptable: scriptable,
  27320. scriptableValue: scriptableValue,
  27321. select: select,
  27322. setCurrentStack: setCurrentStack,
  27323. shaderStages: shaderStages,
  27324. shadow: shadow,
  27325. shadowPositionWorld: shadowPositionWorld,
  27326. sharedUniformGroup: sharedUniformGroup,
  27327. sheen: sheen,
  27328. sheenRoughness: sheenRoughness,
  27329. shiftLeft: shiftLeft,
  27330. shiftRight: shiftRight,
  27331. shininess: shininess,
  27332. sign: sign,
  27333. sin: sin,
  27334. sinc: sinc,
  27335. skinning: skinning,
  27336. skinningReference: skinningReference,
  27337. smoothstep: smoothstep,
  27338. smoothstepElement: smoothstepElement,
  27339. specularColor: specularColor,
  27340. specularF90: specularF90,
  27341. spherizeUV: spherizeUV,
  27342. split: split,
  27343. spritesheetUV: spritesheetUV,
  27344. sqrt: sqrt,
  27345. stack: stack,
  27346. step: step,
  27347. storage: storage,
  27348. storageBarrier: storageBarrier,
  27349. storageObject: storageObject,
  27350. storageTexture: storageTexture,
  27351. string: string,
  27352. sub: sub,
  27353. subgroupIndex: subgroupIndex,
  27354. subgroupSize: subgroupSize,
  27355. tan: tan,
  27356. tangentGeometry: tangentGeometry,
  27357. tangentLocal: tangentLocal,
  27358. tangentView: tangentView,
  27359. tangentWorld: tangentWorld,
  27360. temp: temp,
  27361. texture: texture,
  27362. texture3D: texture3D,
  27363. textureBarrier: textureBarrier,
  27364. textureBicubic: textureBicubic,
  27365. textureCubeUV: textureCubeUV,
  27366. textureLoad: textureLoad,
  27367. textureSize: textureSize,
  27368. textureStore: textureStore,
  27369. thickness: thickness,
  27370. time: time,
  27371. timerDelta: timerDelta,
  27372. timerGlobal: timerGlobal,
  27373. timerLocal: timerLocal,
  27374. toOutputColorSpace: toOutputColorSpace,
  27375. toWorkingColorSpace: toWorkingColorSpace,
  27376. toneMapping: toneMapping,
  27377. toneMappingExposure: toneMappingExposure,
  27378. toonOutlinePass: toonOutlinePass,
  27379. transformDirection: transformDirection,
  27380. transformNormal: transformNormal,
  27381. transformNormalToView: transformNormalToView,
  27382. transformedBentNormalView: transformedBentNormalView,
  27383. transformedBitangentView: transformedBitangentView,
  27384. transformedBitangentWorld: transformedBitangentWorld,
  27385. transformedClearcoatNormalView: transformedClearcoatNormalView,
  27386. transformedNormalView: transformedNormalView,
  27387. transformedNormalWorld: transformedNormalWorld,
  27388. transformedTangentView: transformedTangentView,
  27389. transformedTangentWorld: transformedTangentWorld,
  27390. transmission: transmission,
  27391. transpose: transpose,
  27392. triNoise3D: triNoise3D,
  27393. triplanarTexture: triplanarTexture,
  27394. triplanarTextures: triplanarTextures,
  27395. trunc: trunc,
  27396. tslFn: tslFn,
  27397. uint: uint,
  27398. uniform: uniform,
  27399. uniformArray: uniformArray,
  27400. uniformGroup: uniformGroup,
  27401. uniforms: uniforms,
  27402. userData: userData,
  27403. uv: uv,
  27404. uvec2: uvec2,
  27405. uvec3: uvec3,
  27406. uvec4: uvec4,
  27407. varying: varying,
  27408. varyingProperty: varyingProperty,
  27409. vec2: vec2,
  27410. vec3: vec3,
  27411. vec4: vec4,
  27412. vectorComponents: vectorComponents,
  27413. velocity: velocity,
  27414. vertexColor: vertexColor,
  27415. vertexIndex: vertexIndex,
  27416. vertexStage: vertexStage,
  27417. vibrance: vibrance,
  27418. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  27419. viewZToOrthographicDepth: viewZToOrthographicDepth,
  27420. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  27421. viewport: viewport,
  27422. viewportBottomLeft: viewportBottomLeft,
  27423. viewportCoordinate: viewportCoordinate,
  27424. viewportDepthTexture: viewportDepthTexture,
  27425. viewportLinearDepth: viewportLinearDepth,
  27426. viewportMipTexture: viewportMipTexture,
  27427. viewportResolution: viewportResolution,
  27428. viewportSafeUV: viewportSafeUV,
  27429. viewportSharedTexture: viewportSharedTexture,
  27430. viewportSize: viewportSize,
  27431. viewportTexture: viewportTexture,
  27432. viewportTopLeft: viewportTopLeft,
  27433. viewportUV: viewportUV,
  27434. wgsl: wgsl,
  27435. wgslFn: wgslFn,
  27436. workgroupArray: workgroupArray,
  27437. workgroupBarrier: workgroupBarrier,
  27438. workgroupId: workgroupId,
  27439. workingToColorSpace: workingToColorSpace,
  27440. xor: xor
  27441. });
  27442. const _clearColor$1 = /*@__PURE__*/ new Color4();
  27443. /**
  27444. * This renderer module manages the background.
  27445. *
  27446. * @private
  27447. * @augments DataMap
  27448. */
  27449. class Background extends DataMap {
  27450. /**
  27451. * Constructs a new background management component.
  27452. *
  27453. * @param {Renderer} renderer - The renderer.
  27454. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  27455. */
  27456. constructor( renderer, nodes ) {
  27457. super();
  27458. /**
  27459. * The renderer.
  27460. *
  27461. * @type {Renderer}
  27462. */
  27463. this.renderer = renderer;
  27464. /**
  27465. * Renderer component for managing nodes related logic.
  27466. *
  27467. * @type {Nodes}
  27468. */
  27469. this.nodes = nodes;
  27470. }
  27471. /**
  27472. * Updates the background for the given scene. Depending on how `Scene.background`
  27473. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  27474. * or add a mesh to the render list for rendering the background as a textured plane
  27475. * or skybox.
  27476. *
  27477. * @param {Scene} scene - The scene.
  27478. * @param {RenderList} renderList - The current render list.
  27479. * @param {RenderContext} renderContext - The current render context.
  27480. */
  27481. update( scene, renderList, renderContext ) {
  27482. const renderer = this.renderer;
  27483. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  27484. let forceClear = false;
  27485. if ( background === null ) {
  27486. // no background settings, use clear color configuration from the renderer
  27487. renderer._clearColor.getRGB( _clearColor$1, LinearSRGBColorSpace );
  27488. _clearColor$1.a = renderer._clearColor.a;
  27489. } else if ( background.isColor === true ) {
  27490. // background is an opaque color
  27491. background.getRGB( _clearColor$1, LinearSRGBColorSpace );
  27492. _clearColor$1.a = 1;
  27493. forceClear = true;
  27494. } else if ( background.isNode === true ) {
  27495. const sceneData = this.get( scene );
  27496. const backgroundNode = background;
  27497. _clearColor$1.copy( renderer._clearColor );
  27498. let backgroundMesh = sceneData.backgroundMesh;
  27499. if ( backgroundMesh === undefined ) {
  27500. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  27501. // @TODO: Add Texture2D support using node context
  27502. getUV: () => backgroundRotation.mul( normalWorld ),
  27503. getTextureLevel: () => backgroundBlurriness
  27504. } );
  27505. let viewProj = modelViewProjection;
  27506. viewProj = viewProj.setZ( viewProj.w );
  27507. const nodeMaterial = new NodeMaterial();
  27508. nodeMaterial.name = 'Background.material';
  27509. nodeMaterial.side = BackSide;
  27510. nodeMaterial.depthTest = false;
  27511. nodeMaterial.depthWrite = false;
  27512. nodeMaterial.fog = false;
  27513. nodeMaterial.lights = false;
  27514. nodeMaterial.vertexNode = viewProj;
  27515. nodeMaterial.colorNode = backgroundMeshNode;
  27516. sceneData.backgroundMeshNode = backgroundMeshNode;
  27517. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  27518. backgroundMesh.frustumCulled = false;
  27519. backgroundMesh.name = 'Background.mesh';
  27520. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  27521. this.matrixWorld.copyPosition( camera.matrixWorld );
  27522. };
  27523. }
  27524. const backgroundCacheKey = backgroundNode.getCacheKey();
  27525. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  27526. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  27527. sceneData.backgroundMeshNode.needsUpdate = true;
  27528. backgroundMesh.material.needsUpdate = true;
  27529. sceneData.backgroundCacheKey = backgroundCacheKey;
  27530. }
  27531. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  27532. } else {
  27533. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  27534. }
  27535. //
  27536. if ( renderer.autoClear === true || forceClear === true ) {
  27537. const clearColorValue = renderContext.clearColorValue;
  27538. clearColorValue.r = _clearColor$1.r;
  27539. clearColorValue.g = _clearColor$1.g;
  27540. clearColorValue.b = _clearColor$1.b;
  27541. clearColorValue.a = _clearColor$1.a;
  27542. // premultiply alpha
  27543. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  27544. clearColorValue.r *= clearColorValue.a;
  27545. clearColorValue.g *= clearColorValue.a;
  27546. clearColorValue.b *= clearColorValue.a;
  27547. }
  27548. //
  27549. renderContext.depthClearValue = renderer._clearDepth;
  27550. renderContext.stencilClearValue = renderer._clearStencil;
  27551. renderContext.clearColor = renderer.autoClearColor === true;
  27552. renderContext.clearDepth = renderer.autoClearDepth === true;
  27553. renderContext.clearStencil = renderer.autoClearStencil === true;
  27554. } else {
  27555. renderContext.clearColor = false;
  27556. renderContext.clearDepth = false;
  27557. renderContext.clearStencil = false;
  27558. }
  27559. }
  27560. }
  27561. let _id$6 = 0;
  27562. /**
  27563. * A bind group represents a collection of bindings and thus a collection
  27564. * or resources. Bind groups are assigned to pipelines to provide them
  27565. * with the required resources (like uniform buffers or textures).
  27566. *
  27567. * @private
  27568. */
  27569. class BindGroup {
  27570. /**
  27571. * Constructs a new bind group.
  27572. *
  27573. * @param {String} name - The bind group's name.
  27574. * @param {Array<Binding>} bindings - An array of bindings.
  27575. * @param {Number} index - The group index.
  27576. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  27577. */
  27578. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  27579. /**
  27580. * The bind group's name.
  27581. *
  27582. * @type {String}
  27583. */
  27584. this.name = name;
  27585. /**
  27586. * An array of bindings.
  27587. *
  27588. * @type {Array<Binding>}
  27589. */
  27590. this.bindings = bindings;
  27591. /**
  27592. * The group index.
  27593. *
  27594. * @type {Number}
  27595. */
  27596. this.index = index;
  27597. /**
  27598. * An array of reference bindings.
  27599. *
  27600. * @type {Array<Binding>}
  27601. */
  27602. this.bindingsReference = bindingsReference;
  27603. /**
  27604. * The group's ID.
  27605. *
  27606. * @type {Number}
  27607. */
  27608. this.id = _id$6 ++;
  27609. }
  27610. }
  27611. /**
  27612. * This module represents the state of a node builder after it was
  27613. * used to build the nodes for a render object. The state holds the
  27614. * results of the build for further processing in the renderer.
  27615. *
  27616. * Render objects with identical cache keys share the same node builder state.
  27617. *
  27618. * @private
  27619. */
  27620. class NodeBuilderState {
  27621. /**
  27622. * Constructs a new node builder state.
  27623. *
  27624. * @param {String?} vertexShader - The native vertex shader code.
  27625. * @param {String?} fragmentShader - The native fragment shader code.
  27626. * @param {String?} computeShader - The native compute shader code.
  27627. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  27628. * @param {Array<BindGroup>} bindings - An array of bind groups.
  27629. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  27630. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  27631. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  27632. * @param {NodeMaterialObserver} monitor - A node material observer.
  27633. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  27634. */
  27635. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, monitor, transforms = [] ) {
  27636. /**
  27637. * The native vertex shader code.
  27638. *
  27639. * @type {String}
  27640. */
  27641. this.vertexShader = vertexShader;
  27642. /**
  27643. * The native fragment shader code.
  27644. *
  27645. * @type {String}
  27646. */
  27647. this.fragmentShader = fragmentShader;
  27648. /**
  27649. * The native compute shader code.
  27650. *
  27651. * @type {String}
  27652. */
  27653. this.computeShader = computeShader;
  27654. /**
  27655. * An array with transform attribute objects.
  27656. * Only relevant when using compute shaders with WebGL 2.
  27657. *
  27658. * @type {Array<Object>}
  27659. */
  27660. this.transforms = transforms;
  27661. /**
  27662. * An array of node attributes representing
  27663. * the attributes of the shaders.
  27664. *
  27665. * @type {Array<NodeAttribute>}
  27666. */
  27667. this.nodeAttributes = nodeAttributes;
  27668. /**
  27669. * An array of bind groups representing the uniform or storage
  27670. * buffers, texture or samplers of the shader.
  27671. *
  27672. * @type {Array<BindGroup>}
  27673. */
  27674. this.bindings = bindings;
  27675. /**
  27676. * An array of nodes that implement their `update()` method.
  27677. *
  27678. * @type {Array<Node>}
  27679. */
  27680. this.updateNodes = updateNodes;
  27681. /**
  27682. * An array of nodes that implement their `updateBefore()` method.
  27683. *
  27684. * @type {Array<Node>}
  27685. */
  27686. this.updateBeforeNodes = updateBeforeNodes;
  27687. /**
  27688. * An array of nodes that implement their `updateAfter()` method.
  27689. *
  27690. * @type {Array<Node>}
  27691. */
  27692. this.updateAfterNodes = updateAfterNodes;
  27693. /**
  27694. * A node material observer.
  27695. *
  27696. * @type {NodeMaterialObserver}
  27697. */
  27698. this.monitor = monitor;
  27699. /**
  27700. * How often this state is used by render objects.
  27701. *
  27702. * @type {Number}
  27703. */
  27704. this.usedTimes = 0;
  27705. }
  27706. /**
  27707. * This method is used to create a array of bind groups based
  27708. * on the existing bind groups of this state. Shared groups are
  27709. * not cloned.
  27710. *
  27711. * @return {Array<BindGroup>} A array of bind groups.
  27712. */
  27713. createBindings() {
  27714. const bindings = [];
  27715. for ( const instanceGroup of this.bindings ) {
  27716. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // TODO: Is it safe to always check the first binding in the group?
  27717. if ( shared !== true ) {
  27718. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  27719. bindings.push( bindingsGroup );
  27720. for ( const instanceBinding of instanceGroup.bindings ) {
  27721. bindingsGroup.bindings.push( instanceBinding.clone() );
  27722. }
  27723. } else {
  27724. bindings.push( instanceGroup );
  27725. }
  27726. }
  27727. return bindings;
  27728. }
  27729. }
  27730. /**
  27731. * {@link NodeBuilder} is going to create instances of this class during the build process
  27732. * of nodes. They represent the final shader attributes that are going to be generated
  27733. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  27734. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  27735. */
  27736. class NodeAttribute {
  27737. /**
  27738. * Constructs a new node attribute.
  27739. *
  27740. * @param {String} name - The name of the attribute.
  27741. * @param {String} type - The type of the attribute.
  27742. * @param {Node?} node - An optional reference to the node.
  27743. */
  27744. constructor( name, type, node = null ) {
  27745. /**
  27746. * This flag can be used for type testing.
  27747. *
  27748. * @type {Boolean}
  27749. * @readonly
  27750. * @default true
  27751. */
  27752. this.isNodeAttribute = true;
  27753. /**
  27754. * The name of the attribute.
  27755. *
  27756. * @type {String}
  27757. */
  27758. this.name = name;
  27759. /**
  27760. * The type of the attribute.
  27761. *
  27762. * @type {String}
  27763. */
  27764. this.type = type;
  27765. /**
  27766. * An optional reference to the node.
  27767. *
  27768. * @type {Node?}
  27769. * @default null
  27770. */
  27771. this.node = node;
  27772. }
  27773. }
  27774. /**
  27775. * {@link NodeBuilder} is going to create instances of this class during the build process
  27776. * of nodes. They represent the final shader uniforms that are going to be generated
  27777. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  27778. * for this purpose.
  27779. */
  27780. class NodeUniform {
  27781. /**
  27782. * Constructs a new node uniform.
  27783. *
  27784. * @param {String} name - The name of the uniform.
  27785. * @param {String} type - The type of the uniform.
  27786. * @param {UniformNode} node - An reference to the node.
  27787. */
  27788. constructor( name, type, node ) {
  27789. /**
  27790. * This flag can be used for type testing.
  27791. *
  27792. * @type {Boolean}
  27793. * @readonly
  27794. * @default true
  27795. */
  27796. this.isNodeUniform = true;
  27797. /**
  27798. * The name of the uniform.
  27799. *
  27800. * @type {String}
  27801. */
  27802. this.name = name;
  27803. /**
  27804. * The type of the uniform.
  27805. *
  27806. * @type {String}
  27807. */
  27808. this.type = type;
  27809. /**
  27810. * An reference to the node.
  27811. *
  27812. * @type {UniformNode}
  27813. */
  27814. this.node = node.getSelf();
  27815. }
  27816. /**
  27817. * The value of the uniform node.
  27818. *
  27819. * @type {Any}
  27820. */
  27821. get value() {
  27822. return this.node.value;
  27823. }
  27824. set value( val ) {
  27825. this.node.value = val;
  27826. }
  27827. /**
  27828. * The id of the uniform node.
  27829. *
  27830. * @type {Number}
  27831. */
  27832. get id() {
  27833. return this.node.id;
  27834. }
  27835. /**
  27836. * The uniform node's group.
  27837. *
  27838. * @type {UniformGroupNode}
  27839. */
  27840. get groupNode() {
  27841. return this.node.groupNode;
  27842. }
  27843. }
  27844. /**
  27845. * {@link NodeBuilder} is going to create instances of this class during the build process
  27846. * of nodes. They represent the final shader variables that are going to be generated
  27847. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  27848. * this purpose.
  27849. */
  27850. class NodeVar {
  27851. /**
  27852. * Constructs a new node variable.
  27853. *
  27854. * @param {String} name - The name of the variable.
  27855. * @param {String} type - The type of the variable.
  27856. */
  27857. constructor( name, type ) {
  27858. /**
  27859. * This flag can be used for type testing.
  27860. *
  27861. * @type {Boolean}
  27862. * @readonly
  27863. * @default true
  27864. */
  27865. this.isNodeVar = true;
  27866. /**
  27867. * The name of the variable.
  27868. *
  27869. * @type {String}
  27870. */
  27871. this.name = name;
  27872. /**
  27873. * The type of the variable.
  27874. *
  27875. * @type {String}
  27876. */
  27877. this.type = type;
  27878. }
  27879. }
  27880. /**
  27881. * {@link NodeBuilder} is going to create instances of this class during the build process
  27882. * of nodes. They represent the final shader varyings that are going to be generated
  27883. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  27884. * this purpose.
  27885. *
  27886. * @augments NodeVar
  27887. */
  27888. class NodeVarying extends NodeVar {
  27889. /**
  27890. * Constructs a new node varying.
  27891. *
  27892. * @param {String} name - The name of the varying.
  27893. * @param {String} type - The type of the varying.
  27894. */
  27895. constructor( name, type ) {
  27896. super( name, type );
  27897. /**
  27898. * Whether this varying requires interpolation or not. This property can be used
  27899. * to check if the varying can be optimized for a variable.
  27900. *
  27901. * @type {Boolean}
  27902. * @default false
  27903. */
  27904. this.needsInterpolation = false;
  27905. /**
  27906. * This flag can be used for type testing.
  27907. *
  27908. * @type {Boolean}
  27909. * @readonly
  27910. * @default true
  27911. */
  27912. this.isNodeVarying = true;
  27913. }
  27914. }
  27915. /**
  27916. * {@link NodeBuilder} is going to create instances of this class during the build process
  27917. * of nodes. They represent user-defined, native shader code portions that are going to be
  27918. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  27919. * for this purpose.
  27920. */
  27921. class NodeCode {
  27922. /**
  27923. * Constructs a new code node.
  27924. *
  27925. * @param {String} name - The name of the code.
  27926. * @param {String} type - The node type.
  27927. * @param {String} [code=''] - The native shader code.
  27928. */
  27929. constructor( name, type, code = '' ) {
  27930. /**
  27931. * The name of the code.
  27932. *
  27933. * @type {String}
  27934. */
  27935. this.name = name;
  27936. /**
  27937. * The node type.
  27938. *
  27939. * @type {String}
  27940. */
  27941. this.type = type;
  27942. /**
  27943. * The native shader code.
  27944. *
  27945. * @type {String}
  27946. * @default ''
  27947. */
  27948. this.code = code;
  27949. Object.defineProperty( this, 'isNodeCode', { value: true } );
  27950. }
  27951. }
  27952. let _id$5 = 0;
  27953. /**
  27954. * This utility class is used in {@link NodeBuilder} as an internal
  27955. * cache data structure for node data.
  27956. */
  27957. class NodeCache {
  27958. /**
  27959. * Constructs a new node cache.
  27960. *
  27961. * @param {NodeCache?} parent - A reference to a parent cache.
  27962. */
  27963. constructor( parent = null ) {
  27964. /**
  27965. * The id of the cache.
  27966. *
  27967. * @type {Number}
  27968. * @readonly
  27969. */
  27970. this.id = _id$5 ++;
  27971. /**
  27972. * A weak map for managing node data.
  27973. *
  27974. * @type {WeakMap<Node, Object>}
  27975. */
  27976. this.nodesData = new WeakMap();
  27977. /**
  27978. * Reference to a parent node cache.
  27979. *
  27980. * @type {NodeCache?}
  27981. * @default null
  27982. */
  27983. this.parent = parent;
  27984. }
  27985. /**
  27986. * Returns the data for the given node.
  27987. *
  27988. * @param {Node} node - The node.
  27989. * @return {Object?} The data for the node.
  27990. */
  27991. getData( node ) {
  27992. let data = this.nodesData.get( node );
  27993. if ( data === undefined && this.parent !== null ) {
  27994. data = this.parent.getData( node );
  27995. }
  27996. return data;
  27997. }
  27998. /**
  27999. * Sets the data for a given node.
  28000. *
  28001. * @param {Node} node - The node.
  28002. * @param {Object} data - The data that should be cached.
  28003. */
  28004. setData( node, data ) {
  28005. this.nodesData.set( node, data );
  28006. }
  28007. }
  28008. /**
  28009. * {@link NodeBuilder} is going to create instances of this class during the build process
  28010. * of nodes. They represent the final shader struct data that are going to be generated
  28011. * by the builder. A dictionary of struct types is maintained in {@link NodeBuilder#structs}
  28012. * for this purpose.
  28013. */
  28014. class StructTypeNode extends Node {
  28015. static get type() {
  28016. return 'StructTypeNode';
  28017. }
  28018. /**
  28019. * Constructs a new struct type node.
  28020. *
  28021. * @param {String} name - The name of the struct.
  28022. * @param {Array<String>} types - An array of types.
  28023. */
  28024. constructor( name, types ) {
  28025. super();
  28026. /**
  28027. * The name of the struct.
  28028. *
  28029. * @type {String}
  28030. */
  28031. this.name = name;
  28032. /**
  28033. * An array of types.
  28034. *
  28035. * @type {Array<String>}
  28036. */
  28037. this.types = types;
  28038. /**
  28039. * This flag can be used for type testing.
  28040. *
  28041. * @type {Boolean}
  28042. * @readonly
  28043. * @default true
  28044. */
  28045. this.isStructTypeNode = true;
  28046. }
  28047. /**
  28048. * Returns the member types.
  28049. *
  28050. * @return {Array<String>} The types.
  28051. */
  28052. getMemberTypes() {
  28053. return this.types;
  28054. }
  28055. }
  28056. /**
  28057. * Abstract base class for uniforms.
  28058. *
  28059. * @abstract
  28060. * @private
  28061. */
  28062. class Uniform {
  28063. /**
  28064. * Constructs a new uniform.
  28065. *
  28066. * @param {String} name - The uniform's name.
  28067. * @param {Any} value - The uniform's value.
  28068. */
  28069. constructor( name, value ) {
  28070. /**
  28071. * The uniform's name.
  28072. *
  28073. * @type {String}
  28074. */
  28075. this.name = name;
  28076. /**
  28077. * The uniform's value.
  28078. *
  28079. * @type {Any}
  28080. */
  28081. this.value = value;
  28082. /**
  28083. * Used to build the uniform buffer according to the STD140 layout.
  28084. * Derived uniforms will set this property to a data type specific
  28085. * value.
  28086. *
  28087. * @type {Number}
  28088. */
  28089. this.boundary = 0;
  28090. /**
  28091. * The item size. Derived uniforms will set this property to a data
  28092. * type specific value.
  28093. *
  28094. * @type {Number}
  28095. */
  28096. this.itemSize = 0;
  28097. /**
  28098. * This property is set by {@link UniformsGroup} and marks
  28099. * the start position in the uniform buffer.
  28100. *
  28101. * @type {Number}
  28102. */
  28103. this.offset = 0;
  28104. }
  28105. /**
  28106. * Sets the uniform's value.
  28107. *
  28108. * @param {Any} value - The value to set.
  28109. */
  28110. setValue( value ) {
  28111. this.value = value;
  28112. }
  28113. /**
  28114. * Returns the uniform's value.
  28115. *
  28116. * @return {Any} The value.
  28117. */
  28118. getValue() {
  28119. return this.value;
  28120. }
  28121. }
  28122. /**
  28123. * Represents a Number uniform.
  28124. *
  28125. * @private
  28126. * @augments Uniform
  28127. */
  28128. class NumberUniform extends Uniform {
  28129. /**
  28130. * Constructs a new Number uniform.
  28131. *
  28132. * @param {String} name - The uniform's name.
  28133. * @param {Number} value - The uniform's value.
  28134. */
  28135. constructor( name, value = 0 ) {
  28136. super( name, value );
  28137. /**
  28138. * This flag can be used for type testing.
  28139. *
  28140. * @type {Boolean}
  28141. * @readonly
  28142. * @default true
  28143. */
  28144. this.isNumberUniform = true;
  28145. this.boundary = 4;
  28146. this.itemSize = 1;
  28147. }
  28148. }
  28149. /**
  28150. * Represents a Vector2 uniform.
  28151. *
  28152. * @private
  28153. * @augments Uniform
  28154. */
  28155. class Vector2Uniform extends Uniform {
  28156. /**
  28157. * Constructs a new Number uniform.
  28158. *
  28159. * @param {String} name - The uniform's name.
  28160. * @param {Vector2} value - The uniform's value.
  28161. */
  28162. constructor( name, value = new Vector2() ) {
  28163. super( name, value );
  28164. /**
  28165. * This flag can be used for type testing.
  28166. *
  28167. * @type {Boolean}
  28168. * @readonly
  28169. * @default true
  28170. */
  28171. this.isVector2Uniform = true;
  28172. this.boundary = 8;
  28173. this.itemSize = 2;
  28174. }
  28175. }
  28176. /**
  28177. * Represents a Vector3 uniform.
  28178. *
  28179. * @private
  28180. * @augments Uniform
  28181. */
  28182. class Vector3Uniform extends Uniform {
  28183. /**
  28184. * Constructs a new Number uniform.
  28185. *
  28186. * @param {String} name - The uniform's name.
  28187. * @param {Vector3} value - The uniform's value.
  28188. */
  28189. constructor( name, value = new Vector3() ) {
  28190. super( name, value );
  28191. /**
  28192. * This flag can be used for type testing.
  28193. *
  28194. * @type {Boolean}
  28195. * @readonly
  28196. * @default true
  28197. */
  28198. this.isVector3Uniform = true;
  28199. this.boundary = 16;
  28200. this.itemSize = 3;
  28201. }
  28202. }
  28203. /**
  28204. * Represents a Vector4 uniform.
  28205. *
  28206. * @private
  28207. * @augments Uniform
  28208. */
  28209. class Vector4Uniform extends Uniform {
  28210. /**
  28211. * Constructs a new Number uniform.
  28212. *
  28213. * @param {String} name - The uniform's name.
  28214. * @param {Vector4} value - The uniform's value.
  28215. */
  28216. constructor( name, value = new Vector4() ) {
  28217. super( name, value );
  28218. /**
  28219. * This flag can be used for type testing.
  28220. *
  28221. * @type {Boolean}
  28222. * @readonly
  28223. * @default true
  28224. */
  28225. this.isVector4Uniform = true;
  28226. this.boundary = 16;
  28227. this.itemSize = 4;
  28228. }
  28229. }
  28230. /**
  28231. * Represents a Color uniform.
  28232. *
  28233. * @private
  28234. * @augments Uniform
  28235. */
  28236. class ColorUniform extends Uniform {
  28237. /**
  28238. * Constructs a new Number uniform.
  28239. *
  28240. * @param {String} name - The uniform's name.
  28241. * @param {Color} value - The uniform's value.
  28242. */
  28243. constructor( name, value = new Color() ) {
  28244. super( name, value );
  28245. /**
  28246. * This flag can be used for type testing.
  28247. *
  28248. * @type {Boolean}
  28249. * @readonly
  28250. * @default true
  28251. */
  28252. this.isColorUniform = true;
  28253. this.boundary = 16;
  28254. this.itemSize = 3;
  28255. }
  28256. }
  28257. /**
  28258. * Represents a Matrix3 uniform.
  28259. *
  28260. * @private
  28261. * @augments Uniform
  28262. */
  28263. class Matrix3Uniform extends Uniform {
  28264. /**
  28265. * Constructs a new Number uniform.
  28266. *
  28267. * @param {String} name - The uniform's name.
  28268. * @param {Matrix3} value - The uniform's value.
  28269. */
  28270. constructor( name, value = new Matrix3() ) {
  28271. super( name, value );
  28272. /**
  28273. * This flag can be used for type testing.
  28274. *
  28275. * @type {Boolean}
  28276. * @readonly
  28277. * @default true
  28278. */
  28279. this.isMatrix3Uniform = true;
  28280. this.boundary = 48;
  28281. this.itemSize = 12;
  28282. }
  28283. }
  28284. /**
  28285. * Represents a Matrix4 uniform.
  28286. *
  28287. * @private
  28288. * @augments Uniform
  28289. */
  28290. class Matrix4Uniform extends Uniform {
  28291. /**
  28292. * Constructs a new Number uniform.
  28293. *
  28294. * @param {String} name - The uniform's name.
  28295. * @param {Matrix4} value - The uniform's value.
  28296. */
  28297. constructor( name, value = new Matrix4() ) {
  28298. super( name, value );
  28299. /**
  28300. * This flag can be used for type testing.
  28301. *
  28302. * @type {Boolean}
  28303. * @readonly
  28304. * @default true
  28305. */
  28306. this.isMatrix4Uniform = true;
  28307. this.boundary = 64;
  28308. this.itemSize = 16;
  28309. }
  28310. }
  28311. /**
  28312. * A special form of Number uniform binding type.
  28313. * It's value is managed by a node object.
  28314. *
  28315. * @private
  28316. * @augments NumberUniform
  28317. */
  28318. class NumberNodeUniform extends NumberUniform {
  28319. /**
  28320. * Constructs a new node-based Number uniform.
  28321. *
  28322. * @param {NodeUniform} nodeUniform - The node uniform.
  28323. */
  28324. constructor( nodeUniform ) {
  28325. super( nodeUniform.name, nodeUniform.value );
  28326. /**
  28327. * The node uniform.
  28328. *
  28329. * @type {NodeUniform}
  28330. */
  28331. this.nodeUniform = nodeUniform;
  28332. }
  28333. /**
  28334. * Overwritten to return the value of the node uniform.
  28335. *
  28336. * @return {Number} The value.
  28337. */
  28338. getValue() {
  28339. return this.nodeUniform.value;
  28340. }
  28341. /**
  28342. * Returns the node uniform data type.
  28343. *
  28344. * @return {String} The data type.
  28345. */
  28346. getType() {
  28347. return this.nodeUniform.type;
  28348. }
  28349. }
  28350. /**
  28351. * A special form of Vector2 uniform binding type.
  28352. * It's value is managed by a node object.
  28353. *
  28354. * @private
  28355. * @augments Vector2Uniform
  28356. */
  28357. class Vector2NodeUniform extends Vector2Uniform {
  28358. /**
  28359. * Constructs a new node-based Vector2 uniform.
  28360. *
  28361. * @param {NodeUniform} nodeUniform - The node uniform.
  28362. */
  28363. constructor( nodeUniform ) {
  28364. super( nodeUniform.name, nodeUniform.value );
  28365. /**
  28366. * The node uniform.
  28367. *
  28368. * @type {NodeUniform}
  28369. */
  28370. this.nodeUniform = nodeUniform;
  28371. }
  28372. /**
  28373. * Overwritten to return the value of the node uniform.
  28374. *
  28375. * @return {Vector2} The value.
  28376. */
  28377. getValue() {
  28378. return this.nodeUniform.value;
  28379. }
  28380. /**
  28381. * Returns the node uniform data type.
  28382. *
  28383. * @return {String} The data type.
  28384. */
  28385. getType() {
  28386. return this.nodeUniform.type;
  28387. }
  28388. }
  28389. /**
  28390. * A special form of Vector3 uniform binding type.
  28391. * It's value is managed by a node object.
  28392. *
  28393. * @private
  28394. * @augments Vector3Uniform
  28395. */
  28396. class Vector3NodeUniform extends Vector3Uniform {
  28397. /**
  28398. * Constructs a new node-based Vector3 uniform.
  28399. *
  28400. * @param {NodeUniform} nodeUniform - The node uniform.
  28401. */
  28402. constructor( nodeUniform ) {
  28403. super( nodeUniform.name, nodeUniform.value );
  28404. /**
  28405. * The node uniform.
  28406. *
  28407. * @type {NodeUniform}
  28408. */
  28409. this.nodeUniform = nodeUniform;
  28410. }
  28411. /**
  28412. * Overwritten to return the value of the node uniform.
  28413. *
  28414. * @return {Vector3} The value.
  28415. */
  28416. getValue() {
  28417. return this.nodeUniform.value;
  28418. }
  28419. /**
  28420. * Returns the node uniform data type.
  28421. *
  28422. * @return {String} The data type.
  28423. */
  28424. getType() {
  28425. return this.nodeUniform.type;
  28426. }
  28427. }
  28428. /**
  28429. * A special form of Vector4 uniform binding type.
  28430. * It's value is managed by a node object.
  28431. *
  28432. * @private
  28433. * @augments Vector4Uniform
  28434. */
  28435. class Vector4NodeUniform extends Vector4Uniform {
  28436. /**
  28437. * Constructs a new node-based Vector4 uniform.
  28438. *
  28439. * @param {NodeUniform} nodeUniform - The node uniform.
  28440. */
  28441. constructor( nodeUniform ) {
  28442. super( nodeUniform.name, nodeUniform.value );
  28443. /**
  28444. * The node uniform.
  28445. *
  28446. * @type {NodeUniform}
  28447. */
  28448. this.nodeUniform = nodeUniform;
  28449. }
  28450. /**
  28451. * Overwritten to return the value of the node uniform.
  28452. *
  28453. * @return {Vector4} The value.
  28454. */
  28455. getValue() {
  28456. return this.nodeUniform.value;
  28457. }
  28458. /**
  28459. * Returns the node uniform data type.
  28460. *
  28461. * @return {String} The data type.
  28462. */
  28463. getType() {
  28464. return this.nodeUniform.type;
  28465. }
  28466. }
  28467. /**
  28468. * A special form of Color uniform binding type.
  28469. * It's value is managed by a node object.
  28470. *
  28471. * @private
  28472. * @augments ColorUniform
  28473. */
  28474. class ColorNodeUniform extends ColorUniform {
  28475. /**
  28476. * Constructs a new node-based Color uniform.
  28477. *
  28478. * @param {NodeUniform} nodeUniform - The node uniform.
  28479. */
  28480. constructor( nodeUniform ) {
  28481. super( nodeUniform.name, nodeUniform.value );
  28482. /**
  28483. * The node uniform.
  28484. *
  28485. * @type {NodeUniform}
  28486. */
  28487. this.nodeUniform = nodeUniform;
  28488. }
  28489. /**
  28490. * Overwritten to return the value of the node uniform.
  28491. *
  28492. * @return {Color} The value.
  28493. */
  28494. getValue() {
  28495. return this.nodeUniform.value;
  28496. }
  28497. /**
  28498. * Returns the node uniform data type.
  28499. *
  28500. * @return {String} The data type.
  28501. */
  28502. getType() {
  28503. return this.nodeUniform.type;
  28504. }
  28505. }
  28506. /**
  28507. * A special form of Matrix3 uniform binding type.
  28508. * It's value is managed by a node object.
  28509. *
  28510. * @private
  28511. * @augments Matrix3Uniform
  28512. */
  28513. class Matrix3NodeUniform extends Matrix3Uniform {
  28514. /**
  28515. * Constructs a new node-based Matrix3 uniform.
  28516. *
  28517. * @param {NodeUniform} nodeUniform - The node uniform.
  28518. */
  28519. constructor( nodeUniform ) {
  28520. super( nodeUniform.name, nodeUniform.value );
  28521. /**
  28522. * The node uniform.
  28523. *
  28524. * @type {NodeUniform}
  28525. */
  28526. this.nodeUniform = nodeUniform;
  28527. }
  28528. /**
  28529. * Overwritten to return the value of the node uniform.
  28530. *
  28531. * @return {Matrix3} The value.
  28532. */
  28533. getValue() {
  28534. return this.nodeUniform.value;
  28535. }
  28536. /**
  28537. * Returns the node uniform data type.
  28538. *
  28539. * @return {String} The data type.
  28540. */
  28541. getType() {
  28542. return this.nodeUniform.type;
  28543. }
  28544. }
  28545. /**
  28546. * A special form of Matrix4 uniform binding type.
  28547. * It's value is managed by a node object.
  28548. *
  28549. * @private
  28550. * @augments Matrix4Uniform
  28551. */
  28552. class Matrix4NodeUniform extends Matrix4Uniform {
  28553. /**
  28554. * Constructs a new node-based Matrix4 uniform.
  28555. *
  28556. * @param {NodeUniform} nodeUniform - The node uniform.
  28557. */
  28558. constructor( nodeUniform ) {
  28559. super( nodeUniform.name, nodeUniform.value );
  28560. /**
  28561. * The node uniform.
  28562. *
  28563. * @type {NodeUniform}
  28564. */
  28565. this.nodeUniform = nodeUniform;
  28566. }
  28567. /**
  28568. * Overwritten to return the value of the node uniform.
  28569. *
  28570. * @return {Matrix4} The value.
  28571. */
  28572. getValue() {
  28573. return this.nodeUniform.value;
  28574. }
  28575. /**
  28576. * Returns the node uniform data type.
  28577. *
  28578. * @return {String} The data type.
  28579. */
  28580. getType() {
  28581. return this.nodeUniform.type;
  28582. }
  28583. }
  28584. const LOD_MIN = 4;
  28585. // The standard deviations (radians) associated with the extra mips. These are
  28586. // chosen to approximate a Trowbridge-Reitz distribution function times the
  28587. // geometric shadowing function. These sigma values squared must match the
  28588. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  28589. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  28590. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  28591. // samples and exit early, but not recompile the shader.
  28592. const MAX_SAMPLES = 20;
  28593. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  28594. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  28595. const _clearColor = /*@__PURE__*/ new Color();
  28596. let _oldTarget = null;
  28597. let _oldActiveCubeFace = 0;
  28598. let _oldActiveMipmapLevel = 0;
  28599. // Golden Ratio
  28600. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  28601. const INV_PHI = 1 / PHI;
  28602. // Vertices of a dodecahedron (except the opposites, which represent the
  28603. // same axis), used as axis directions evenly spread on a sphere.
  28604. const _axisDirections = [
  28605. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  28606. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  28607. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  28608. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  28609. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  28610. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  28611. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  28612. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  28613. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  28614. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  28615. ];
  28616. //
  28617. // WebGPU Face indices
  28618. const _faceLib = [
  28619. 3, 1, 5,
  28620. 0, 4, 2
  28621. ];
  28622. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  28623. const outputDirection = vec3( direction.x, direction.y, direction.z );
  28624. /**
  28625. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  28626. * (PMREM) from a cubeMap environment texture. This allows different levels of
  28627. * blur to be quickly accessed based on material roughness. It is packed into a
  28628. * special CubeUV format that allows us to perform custom interpolation so that
  28629. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  28630. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  28631. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  28632. * higher roughness levels. In this way we maintain resolution to smoothly
  28633. * interpolate diffuse lighting while limiting sampling computation.
  28634. *
  28635. * Paper: Fast, Accurate Image-Based Lighting
  28636. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  28637. */
  28638. class PMREMGenerator {
  28639. constructor( renderer ) {
  28640. this._renderer = renderer;
  28641. this._pingPongRenderTarget = null;
  28642. this._lodMax = 0;
  28643. this._cubeSize = 0;
  28644. this._lodPlanes = [];
  28645. this._sizeLods = [];
  28646. this._sigmas = [];
  28647. this._lodMeshes = [];
  28648. this._blurMaterial = null;
  28649. this._cubemapMaterial = null;
  28650. this._equirectMaterial = null;
  28651. this._backgroundBox = null;
  28652. }
  28653. get _hasInitialized() {
  28654. return this._renderer.hasInitialized();
  28655. }
  28656. /**
  28657. * Generates a PMREM from a supplied Scene, which can be faster than using an
  28658. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  28659. * in radians to be applied to the scene before PMREM generation. Optional near
  28660. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  28661. * is placed at the origin).
  28662. *
  28663. * @param {Scene} scene - The scene to be captured.
  28664. * @param {Number} [sigma=0] - The blur radius in radians.
  28665. * @param {Number} [near=0.1] - The near plane distance.
  28666. * @param {Number} [far=100] - The far plane distance.
  28667. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  28668. * @return {RenderTarget} The resulting PMREM.
  28669. */
  28670. fromScene( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  28671. this._setSize( 256 );
  28672. if ( this._hasInitialized === false ) {
  28673. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  28674. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  28675. this.fromSceneAsync( scene, sigma, near, far, cubeUVRenderTarget );
  28676. return cubeUVRenderTarget;
  28677. }
  28678. _oldTarget = this._renderer.getRenderTarget();
  28679. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  28680. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  28681. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  28682. cubeUVRenderTarget.depthBuffer = true;
  28683. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  28684. if ( sigma > 0 ) {
  28685. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  28686. }
  28687. this._applyPMREM( cubeUVRenderTarget );
  28688. this._cleanup( cubeUVRenderTarget );
  28689. return cubeUVRenderTarget;
  28690. }
  28691. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  28692. if ( this._hasInitialized === false ) await this._renderer.init();
  28693. return this.fromScene( scene, sigma, near, far, renderTarget );
  28694. }
  28695. /**
  28696. * Generates a PMREM from an equirectangular texture, which can be either LDR
  28697. * or HDR. The ideal input image size is 1k (1024 x 512),
  28698. * as this matches best with the 256 x 256 cubemap output.
  28699. *
  28700. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  28701. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  28702. * @return {RenderTarget} The resulting PMREM.
  28703. */
  28704. fromEquirectangular( equirectangular, renderTarget = null ) {
  28705. if ( this._hasInitialized === false ) {
  28706. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  28707. this._setSizeFromTexture( equirectangular );
  28708. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  28709. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  28710. return cubeUVRenderTarget;
  28711. }
  28712. return this._fromTexture( equirectangular, renderTarget );
  28713. }
  28714. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  28715. if ( this._hasInitialized === false ) await this._renderer.init();
  28716. return this._fromTexture( equirectangular, renderTarget );
  28717. }
  28718. /**
  28719. * Generates a PMREM from an cubemap texture, which can be either LDR
  28720. * or HDR. The ideal input cube size is 256 x 256,
  28721. * as this matches best with the 256 x 256 cubemap output.
  28722. *
  28723. * @param {Texture} cubemap - The cubemap texture to be converted.
  28724. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  28725. * @return {RenderTarget} The resulting PMREM.
  28726. */
  28727. fromCubemap( cubemap, renderTarget = null ) {
  28728. if ( this._hasInitialized === false ) {
  28729. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  28730. this._setSizeFromTexture( cubemap );
  28731. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  28732. this.fromCubemapAsync( cubemap, renderTarget );
  28733. return cubeUVRenderTarget;
  28734. }
  28735. return this._fromTexture( cubemap, renderTarget );
  28736. }
  28737. async fromCubemapAsync( cubemap, renderTarget = null ) {
  28738. if ( this._hasInitialized === false ) await this._renderer.init();
  28739. return this._fromTexture( cubemap, renderTarget );
  28740. }
  28741. /**
  28742. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  28743. * your texture's network fetch for increased concurrency.
  28744. */
  28745. async compileCubemapShader() {
  28746. if ( this._cubemapMaterial === null ) {
  28747. this._cubemapMaterial = _getCubemapMaterial();
  28748. await this._compileMaterial( this._cubemapMaterial );
  28749. }
  28750. }
  28751. /**
  28752. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  28753. * your texture's network fetch for increased concurrency.
  28754. */
  28755. async compileEquirectangularShader() {
  28756. if ( this._equirectMaterial === null ) {
  28757. this._equirectMaterial = _getEquirectMaterial();
  28758. await this._compileMaterial( this._equirectMaterial );
  28759. }
  28760. }
  28761. /**
  28762. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  28763. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  28764. * one of them will cause any others to also become unusable.
  28765. */
  28766. dispose() {
  28767. this._dispose();
  28768. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  28769. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  28770. if ( this._backgroundBox !== null ) {
  28771. this._backgroundBox.geometry.dispose();
  28772. this._backgroundBox.material.dispose();
  28773. }
  28774. }
  28775. // private interface
  28776. _setSizeFromTexture( texture ) {
  28777. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  28778. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  28779. } else { // Equirectangular
  28780. this._setSize( texture.image.width / 4 );
  28781. }
  28782. }
  28783. _setSize( cubeSize ) {
  28784. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  28785. this._cubeSize = Math.pow( 2, this._lodMax );
  28786. }
  28787. _dispose() {
  28788. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  28789. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  28790. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  28791. this._lodPlanes[ i ].dispose();
  28792. }
  28793. }
  28794. _cleanup( outputTarget ) {
  28795. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  28796. outputTarget.scissorTest = false;
  28797. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  28798. }
  28799. _fromTexture( texture, renderTarget ) {
  28800. this._setSizeFromTexture( texture );
  28801. _oldTarget = this._renderer.getRenderTarget();
  28802. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  28803. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  28804. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  28805. this._textureToCubeUV( texture, cubeUVRenderTarget );
  28806. this._applyPMREM( cubeUVRenderTarget );
  28807. this._cleanup( cubeUVRenderTarget );
  28808. return cubeUVRenderTarget;
  28809. }
  28810. _allocateTargets() {
  28811. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  28812. const height = 4 * this._cubeSize;
  28813. const params = {
  28814. magFilter: LinearFilter,
  28815. minFilter: LinearFilter,
  28816. generateMipmaps: false,
  28817. type: HalfFloatType,
  28818. format: RGBAFormat,
  28819. colorSpace: LinearSRGBColorSpace,
  28820. //depthBuffer: false
  28821. };
  28822. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  28823. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  28824. if ( this._pingPongRenderTarget !== null ) {
  28825. this._dispose();
  28826. }
  28827. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  28828. const { _lodMax } = this;
  28829. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  28830. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  28831. }
  28832. return cubeUVRenderTarget;
  28833. }
  28834. async _compileMaterial( material ) {
  28835. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  28836. await this._renderer.compile( tmpMesh, _flatCamera );
  28837. }
  28838. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  28839. const cubeCamera = _cubeCamera;
  28840. cubeCamera.near = near;
  28841. cubeCamera.far = far;
  28842. // px, py, pz, nx, ny, nz
  28843. const upSign = [ 1, 1, 1, 1, - 1, 1 ];
  28844. const forwardSign = [ 1, - 1, 1, - 1, 1, - 1 ];
  28845. const renderer = this._renderer;
  28846. const originalAutoClear = renderer.autoClear;
  28847. renderer.getClearColor( _clearColor );
  28848. renderer.autoClear = false;
  28849. let backgroundBox = this._backgroundBox;
  28850. if ( backgroundBox === null ) {
  28851. const backgroundMaterial = new MeshBasicMaterial( {
  28852. name: 'PMREM.Background',
  28853. side: BackSide,
  28854. depthWrite: false,
  28855. depthTest: false
  28856. } );
  28857. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  28858. }
  28859. let useSolidColor = false;
  28860. const background = scene.background;
  28861. if ( background ) {
  28862. if ( background.isColor ) {
  28863. backgroundBox.material.color.copy( background );
  28864. scene.background = null;
  28865. useSolidColor = true;
  28866. }
  28867. } else {
  28868. backgroundBox.material.color.copy( _clearColor );
  28869. useSolidColor = true;
  28870. }
  28871. renderer.setRenderTarget( cubeUVRenderTarget );
  28872. renderer.clear();
  28873. if ( useSolidColor ) {
  28874. renderer.render( backgroundBox, cubeCamera );
  28875. }
  28876. for ( let i = 0; i < 6; i ++ ) {
  28877. const col = i % 3;
  28878. if ( col === 0 ) {
  28879. cubeCamera.up.set( 0, upSign[ i ], 0 );
  28880. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  28881. } else if ( col === 1 ) {
  28882. cubeCamera.up.set( 0, 0, upSign[ i ] );
  28883. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  28884. } else {
  28885. cubeCamera.up.set( 0, upSign[ i ], 0 );
  28886. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  28887. }
  28888. const size = this._cubeSize;
  28889. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  28890. renderer.render( scene, cubeCamera );
  28891. }
  28892. renderer.autoClear = originalAutoClear;
  28893. scene.background = background;
  28894. }
  28895. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  28896. const renderer = this._renderer;
  28897. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  28898. if ( isCubeTexture ) {
  28899. if ( this._cubemapMaterial === null ) {
  28900. this._cubemapMaterial = _getCubemapMaterial( texture );
  28901. }
  28902. } else {
  28903. if ( this._equirectMaterial === null ) {
  28904. this._equirectMaterial = _getEquirectMaterial( texture );
  28905. }
  28906. }
  28907. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  28908. material.fragmentNode.value = texture;
  28909. const mesh = this._lodMeshes[ 0 ];
  28910. mesh.material = material;
  28911. const size = this._cubeSize;
  28912. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  28913. renderer.setRenderTarget( cubeUVRenderTarget );
  28914. renderer.render( mesh, _flatCamera );
  28915. }
  28916. _applyPMREM( cubeUVRenderTarget ) {
  28917. const renderer = this._renderer;
  28918. const autoClear = renderer.autoClear;
  28919. renderer.autoClear = false;
  28920. const n = this._lodPlanes.length;
  28921. for ( let i = 1; i < n; i ++ ) {
  28922. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  28923. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  28924. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  28925. }
  28926. renderer.autoClear = autoClear;
  28927. }
  28928. /**
  28929. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  28930. * vertically and horizontally, but this breaks down on a cube. Here we apply
  28931. * the blur latitudinally (around the poles), and then longitudinally (towards
  28932. * the poles) to approximate the orthogonally-separable blur. It is least
  28933. * accurate at the poles, but still does a decent job.
  28934. *
  28935. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  28936. * @param {Number} lodIn - The input level-of-detail.
  28937. * @param {Number} lodOut - The output level-of-detail.
  28938. * @param {Number} sigma - The blur radius in radians.
  28939. * @param {Vector3} [poleAxis] - The pole axis.
  28940. */
  28941. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  28942. const pingPongRenderTarget = this._pingPongRenderTarget;
  28943. this._halfBlur(
  28944. cubeUVRenderTarget,
  28945. pingPongRenderTarget,
  28946. lodIn,
  28947. lodOut,
  28948. sigma,
  28949. 'latitudinal',
  28950. poleAxis );
  28951. this._halfBlur(
  28952. pingPongRenderTarget,
  28953. cubeUVRenderTarget,
  28954. lodOut,
  28955. lodOut,
  28956. sigma,
  28957. 'longitudinal',
  28958. poleAxis );
  28959. }
  28960. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  28961. const renderer = this._renderer;
  28962. const blurMaterial = this._blurMaterial;
  28963. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  28964. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  28965. }
  28966. // Number of standard deviations at which to cut off the discrete approximation.
  28967. const STANDARD_DEVIATIONS = 3;
  28968. const blurMesh = this._lodMeshes[ lodOut ];
  28969. blurMesh.material = blurMaterial;
  28970. const blurUniforms = blurMaterial.uniforms;
  28971. const pixels = this._sizeLods[ lodIn ] - 1;
  28972. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  28973. const sigmaPixels = sigmaRadians / radiansPerPixel;
  28974. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  28975. if ( samples > MAX_SAMPLES ) {
  28976. console.warn( `sigmaRadians, ${
  28977. sigmaRadians}, is too large and will clip, as it requested ${
  28978. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  28979. }
  28980. const weights = [];
  28981. let sum = 0;
  28982. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  28983. const x = i / sigmaPixels;
  28984. const weight = Math.exp( - x * x / 2 );
  28985. weights.push( weight );
  28986. if ( i === 0 ) {
  28987. sum += weight;
  28988. } else if ( i < samples ) {
  28989. sum += 2 * weight;
  28990. }
  28991. }
  28992. for ( let i = 0; i < weights.length; i ++ ) {
  28993. weights[ i ] = weights[ i ] / sum;
  28994. }
  28995. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  28996. blurUniforms.envMap.value = targetIn.texture;
  28997. blurUniforms.samples.value = samples;
  28998. blurUniforms.weights.array = weights;
  28999. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  29000. if ( poleAxis ) {
  29001. blurUniforms.poleAxis.value = poleAxis;
  29002. }
  29003. const { _lodMax } = this;
  29004. blurUniforms.dTheta.value = radiansPerPixel;
  29005. blurUniforms.mipInt.value = _lodMax - lodIn;
  29006. const outputSize = this._sizeLods[ lodOut ];
  29007. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  29008. const y = 4 * ( this._cubeSize - outputSize );
  29009. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  29010. renderer.setRenderTarget( targetOut );
  29011. renderer.render( blurMesh, _flatCamera );
  29012. }
  29013. }
  29014. function _createPlanes( lodMax ) {
  29015. const lodPlanes = [];
  29016. const sizeLods = [];
  29017. const sigmas = [];
  29018. const lodMeshes = [];
  29019. let lod = lodMax;
  29020. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  29021. for ( let i = 0; i < totalLods; i ++ ) {
  29022. const sizeLod = Math.pow( 2, lod );
  29023. sizeLods.push( sizeLod );
  29024. let sigma = 1.0 / sizeLod;
  29025. if ( i > lodMax - LOD_MIN ) {
  29026. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  29027. } else if ( i === 0 ) {
  29028. sigma = 0;
  29029. }
  29030. sigmas.push( sigma );
  29031. const texelSize = 1.0 / ( sizeLod - 2 );
  29032. const min = - texelSize;
  29033. const max = 1 + texelSize;
  29034. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  29035. const cubeFaces = 6;
  29036. const vertices = 6;
  29037. const positionSize = 3;
  29038. const uvSize = 2;
  29039. const faceIndexSize = 1;
  29040. const position = new Float32Array( positionSize * vertices * cubeFaces );
  29041. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  29042. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  29043. for ( let face = 0; face < cubeFaces; face ++ ) {
  29044. const x = ( face % 3 ) * 2 / 3 - 1;
  29045. const y = face > 2 ? 0 : - 1;
  29046. const coordinates = [
  29047. x, y, 0,
  29048. x + 2 / 3, y, 0,
  29049. x + 2 / 3, y + 1, 0,
  29050. x, y, 0,
  29051. x + 2 / 3, y + 1, 0,
  29052. x, y + 1, 0
  29053. ];
  29054. const faceIdx = _faceLib[ face ];
  29055. position.set( coordinates, positionSize * vertices * faceIdx );
  29056. uv.set( uv1, uvSize * vertices * faceIdx );
  29057. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  29058. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  29059. }
  29060. const planes = new BufferGeometry();
  29061. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  29062. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  29063. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  29064. lodPlanes.push( planes );
  29065. lodMeshes.push( new Mesh( planes, null ) );
  29066. if ( lod > LOD_MIN ) {
  29067. lod --;
  29068. }
  29069. }
  29070. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  29071. }
  29072. function _createRenderTarget( width, height, params ) {
  29073. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  29074. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  29075. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  29076. cubeUVRenderTarget.texture.isPMREMTexture = true;
  29077. cubeUVRenderTarget.scissorTest = true;
  29078. return cubeUVRenderTarget;
  29079. }
  29080. function _setViewport( target, x, y, width, height ) {
  29081. target.viewport.set( x, y, width, height );
  29082. target.scissor.set( x, y, width, height );
  29083. }
  29084. function _getMaterial( type ) {
  29085. const material = new NodeMaterial();
  29086. material.depthTest = false;
  29087. material.depthWrite = false;
  29088. material.blending = NoBlending;
  29089. material.name = `PMREM_${ type }`;
  29090. return material;
  29091. }
  29092. function _getBlurShader( lodMax, width, height ) {
  29093. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  29094. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  29095. const dTheta = uniform( 0 );
  29096. const n = float( MAX_SAMPLES );
  29097. const latitudinal = uniform( 0 ); // false, bool
  29098. const samples = uniform( 1 ); // int
  29099. const envMap = texture( null );
  29100. const mipInt = uniform( 0 ); // int
  29101. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  29102. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  29103. const CUBEUV_MAX_MIP = float( lodMax );
  29104. const materialUniforms = {
  29105. n,
  29106. latitudinal,
  29107. weights,
  29108. poleAxis,
  29109. outputDirection,
  29110. dTheta,
  29111. samples,
  29112. envMap,
  29113. mipInt,
  29114. CUBEUV_TEXEL_WIDTH,
  29115. CUBEUV_TEXEL_HEIGHT,
  29116. CUBEUV_MAX_MIP
  29117. };
  29118. const material = _getMaterial( 'blur' );
  29119. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  29120. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  29121. return material;
  29122. }
  29123. function _getCubemapMaterial( envTexture ) {
  29124. const material = _getMaterial( 'cubemap' );
  29125. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  29126. return material;
  29127. }
  29128. function _getEquirectMaterial( envTexture ) {
  29129. const material = _getMaterial( 'equirect' );
  29130. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  29131. return material;
  29132. }
  29133. const rendererCache = new WeakMap();
  29134. const typeFromArray = new Map( [
  29135. [ Int8Array, 'int' ],
  29136. [ Int16Array, 'int' ],
  29137. [ Int32Array, 'int' ],
  29138. [ Uint8Array, 'uint' ],
  29139. [ Uint16Array, 'uint' ],
  29140. [ Uint32Array, 'uint' ],
  29141. [ Float32Array, 'float' ]
  29142. ] );
  29143. const toFloat = ( value ) => {
  29144. if ( /e/g.test( value ) ) {
  29145. return String( value ).replace( /\+/g, '' );
  29146. } else {
  29147. value = Number( value );
  29148. return value + ( value % 1 ? '' : '.0' );
  29149. }
  29150. };
  29151. /**
  29152. * Base class for builders which generate a shader program based
  29153. * on a 3D object and its node material definition.
  29154. */
  29155. class NodeBuilder {
  29156. /**
  29157. * Constructs a new node builder.
  29158. *
  29159. * @param {Object3D} object - The 3D object.
  29160. * @param {Renderer} renderer - The current renderer.
  29161. * @param {NodeParser} parser - A reference to a node parser.
  29162. */
  29163. constructor( object, renderer, parser ) {
  29164. /**
  29165. * The 3D object.
  29166. *
  29167. * @type {Object3D}
  29168. */
  29169. this.object = object;
  29170. /**
  29171. * The material of the 3D object.
  29172. *
  29173. * @type {Material?}
  29174. */
  29175. this.material = ( object && object.material ) || null;
  29176. /**
  29177. * The geometry of the 3D object.
  29178. *
  29179. * @type {BufferGeometry?}
  29180. */
  29181. this.geometry = ( object && object.geometry ) || null;
  29182. /**
  29183. * The current renderer.
  29184. *
  29185. * @type {Renderer}
  29186. */
  29187. this.renderer = renderer;
  29188. /**
  29189. * A reference to a node parser.
  29190. *
  29191. * @type {NodeParser}
  29192. */
  29193. this.parser = parser;
  29194. /**
  29195. * The scene the 3D object belongs to.
  29196. *
  29197. * @type {Scene?}
  29198. * @default null
  29199. */
  29200. this.scene = null;
  29201. /**
  29202. * The camera the 3D object is rendered with.
  29203. *
  29204. * @type {Camera?}
  29205. * @default null
  29206. */
  29207. this.camera = null;
  29208. /**
  29209. * A list of all nodes the builder is processing
  29210. * for this 3D object.
  29211. *
  29212. * @type {Array<Node>}
  29213. */
  29214. this.nodes = [];
  29215. /**
  29216. * A list of all sequential nodes.
  29217. *
  29218. * @type {Array<Node>}
  29219. */
  29220. this.sequentialNodes = [];
  29221. /**
  29222. * A list of all nodes which {@link Node#update} method should be executed.
  29223. *
  29224. * @type {Array<Node>}
  29225. */
  29226. this.updateNodes = [];
  29227. /**
  29228. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  29229. *
  29230. * @type {Array<Node>}
  29231. */
  29232. this.updateBeforeNodes = [];
  29233. /**
  29234. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  29235. *
  29236. * @type {Array<Node>}
  29237. */
  29238. this.updateAfterNodes = [];
  29239. /**
  29240. * A dictionary that assigns each node to a unique hash.
  29241. *
  29242. * @type {Object<Number,Node>}
  29243. */
  29244. this.hashNodes = {};
  29245. /**
  29246. * A reference to a node material observer.
  29247. *
  29248. * @type {NodeMaterialObserver?}
  29249. * @default null
  29250. */
  29251. this.monitor = null;
  29252. /**
  29253. * A reference to the current lights node.
  29254. *
  29255. * @type {LightsNode?}
  29256. * @default null
  29257. */
  29258. this.lightsNode = null;
  29259. /**
  29260. * A reference to the current environment node.
  29261. *
  29262. * @type {Node?}
  29263. * @default null
  29264. */
  29265. this.environmentNode = null;
  29266. /**
  29267. * A reference to the current fog node.
  29268. *
  29269. * @type {FogNode?}
  29270. * @default null
  29271. */
  29272. this.fogNode = null;
  29273. /**
  29274. * The current clipping context.
  29275. *
  29276. * @type {ClippingContext?}
  29277. */
  29278. this.clippingContext = null;
  29279. /**
  29280. * The generated vertex shader.
  29281. *
  29282. * @type {String?}
  29283. */
  29284. this.vertexShader = null;
  29285. /**
  29286. * The generated fragment shader.
  29287. *
  29288. * @type {String?}
  29289. */
  29290. this.fragmentShader = null;
  29291. /**
  29292. * The generated compute shader.
  29293. *
  29294. * @type {String?}
  29295. */
  29296. this.computeShader = null;
  29297. /**
  29298. * Nodes used in the primary flow of code generation.
  29299. *
  29300. * @type {Object<String,Array<Node>>}
  29301. */
  29302. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  29303. /**
  29304. * Nodes code from `.flowNodes`.
  29305. *
  29306. * @type {Object<String,String>}
  29307. */
  29308. this.flowCode = { vertex: '', fragment: '', compute: '' };
  29309. /**
  29310. * This dictionary holds the node uniforms of the builder.
  29311. * The uniforms are maintained in an array for each shader stage.
  29312. *
  29313. * @type {Object}
  29314. */
  29315. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  29316. /**
  29317. * This dictionary holds the output structs of the builder.
  29318. * The structs are maintained in an array for each shader stage.
  29319. *
  29320. * @type {Object}
  29321. */
  29322. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  29323. /**
  29324. * This dictionary holds the bindings for each shader stage.
  29325. *
  29326. * @type {Object}
  29327. */
  29328. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  29329. /**
  29330. * This dictionary maintains the binding indices per bind group.
  29331. *
  29332. * @type {Object}
  29333. */
  29334. this.bindingsIndexes = {};
  29335. /**
  29336. * Reference to the array of bind groups.
  29337. *
  29338. * @type {Array<BindGroup>?}
  29339. */
  29340. this.bindGroups = null;
  29341. /**
  29342. * This array holds the node attributes of this builder
  29343. * created via {@link AttributeNode}.
  29344. *
  29345. * @type {Array<NodeAttribute>}
  29346. */
  29347. this.attributes = [];
  29348. /**
  29349. * This array holds the node attributes of this builder
  29350. * created via {@link BufferAttributeNode}.
  29351. *
  29352. * @type {Array<NodeAttribute>}
  29353. */
  29354. this.bufferAttributes = [];
  29355. /**
  29356. * This array holds the node varyings of this builder.
  29357. *
  29358. * @type {Array<NodeVarying>}
  29359. */
  29360. this.varyings = [];
  29361. /**
  29362. * This dictionary holds the (native) node codes of this builder.
  29363. * The codes are maintained in an array for each shader stage.
  29364. *
  29365. * @type {Object<String,Array<NodeCode>>}
  29366. */
  29367. this.codes = {};
  29368. /**
  29369. * This dictionary holds the node variables of this builder.
  29370. * The variables are maintained in an array for each shader stage.
  29371. *
  29372. * @type {Object<String,Array<NodeVar>>}
  29373. */
  29374. this.vars = {};
  29375. /**
  29376. * Current code flow.
  29377. * All code generated in this stack will be stored in `.flow`.
  29378. *
  29379. * @type {{code: String}}
  29380. */
  29381. this.flow = { code: '' };
  29382. /**
  29383. * A chain of nodes.
  29384. * Used to check recursive calls in node-graph.
  29385. *
  29386. * @type {Array<Node>}
  29387. */
  29388. this.chaining = [];
  29389. /**
  29390. * The current stack.
  29391. * This reflects the current process in the code block hierarchy,
  29392. * it is useful to know if the current process is inside a conditional for example.
  29393. *
  29394. * @type {StackNode}
  29395. */
  29396. this.stack = stack();
  29397. /**
  29398. * List of stack nodes.
  29399. * The current stack hierarchy is stored in an array.
  29400. *
  29401. * @type {Array<StackNode>}
  29402. */
  29403. this.stacks = [];
  29404. /**
  29405. * A tab value. Used for shader string generation.
  29406. *
  29407. * @type {String}
  29408. * @default '\t'
  29409. */
  29410. this.tab = '\t';
  29411. /**
  29412. * Reference to the current function node.
  29413. *
  29414. * @type {FunctionNode?}
  29415. * @default null
  29416. */
  29417. this.currentFunctionNode = null;
  29418. /**
  29419. * The builder's context.
  29420. *
  29421. * @type {Object}
  29422. */
  29423. this.context = {
  29424. material: this.material
  29425. };
  29426. /**
  29427. * The builder's cache.
  29428. *
  29429. * @type {NodeCache}
  29430. */
  29431. this.cache = new NodeCache();
  29432. /**
  29433. * Since the {@link NodeBuilder#cache} might be temporarily
  29434. * overwritten by other caches, this member retains the reference
  29435. * to the builder's own cache.
  29436. *
  29437. * @type {NodeCache}
  29438. * @default this.cache
  29439. */
  29440. this.globalCache = this.cache;
  29441. this.flowsData = new WeakMap();
  29442. /**
  29443. * The current shader stage.
  29444. *
  29445. * @type {('vertex'|'fragment'|'compute'|'any')?}
  29446. */
  29447. this.shaderStage = null;
  29448. /**
  29449. * The current build stage.
  29450. *
  29451. * @type {('setup'|'analyze'|'generate')?}
  29452. */
  29453. this.buildStage = null;
  29454. /**
  29455. * Whether comparison in shader code are generated with methods or not.
  29456. *
  29457. * @type {Boolean}
  29458. * @default false
  29459. */
  29460. this.useComparisonMethod = false;
  29461. }
  29462. /**
  29463. * Returns the bind groups of the current renderer.
  29464. *
  29465. * @return {ChainMap} The cache.
  29466. */
  29467. getBindGroupsCache() {
  29468. let bindGroupsCache = rendererCache.get( this.renderer );
  29469. if ( bindGroupsCache === undefined ) {
  29470. bindGroupsCache = new ChainMap();
  29471. rendererCache.set( this.renderer, bindGroupsCache );
  29472. }
  29473. return bindGroupsCache;
  29474. }
  29475. /**
  29476. * Factory method for creating an instance of {@link RenderTarget} with the given
  29477. * dimensions and options.
  29478. *
  29479. * @param {Number} width - The width of the render target.
  29480. * @param {Number} height - The height of the render target.
  29481. * @param {Object} options - The options of the render target.
  29482. * @return {RenderTarget} The render target.
  29483. */
  29484. createRenderTarget( width, height, options ) {
  29485. return new RenderTarget( width, height, options );
  29486. }
  29487. /**
  29488. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  29489. * dimensions and options.
  29490. *
  29491. * @param {Number} size - The size of the cube render target.
  29492. * @param {Object} options - The options of the cube render target.
  29493. * @return {CubeRenderTarget} The cube render target.
  29494. */
  29495. createCubeRenderTarget( size, options ) {
  29496. return new CubeRenderTarget( size, options );
  29497. }
  29498. /**
  29499. * Factory method for creating an instance of {@link PMREMGenerator}.
  29500. *
  29501. * @return {PMREMGenerator} The PMREM generator.
  29502. */
  29503. createPMREMGenerator() {
  29504. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  29505. return new PMREMGenerator( this.renderer );
  29506. }
  29507. /**
  29508. * Whether the given node is included in the internal array of nodes or not.
  29509. *
  29510. * @param {Node} node - The node to test.
  29511. * @return {Boolean} Whether the given node is included in the internal array of nodes or not.
  29512. */
  29513. includes( node ) {
  29514. return this.nodes.includes( node );
  29515. }
  29516. /**
  29517. * Returns the output struct name which is required by
  29518. * {@link module:OutputStructNode}.
  29519. *
  29520. * @abstract
  29521. * @return {String} The name of the output struct.
  29522. */
  29523. getOutputStructName() {}
  29524. /**
  29525. * Returns a bind group for the given group name and binding.
  29526. *
  29527. * @private
  29528. * @param {String} groupName - The group name.
  29529. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  29530. * @return {BindGroup} The bind group
  29531. */
  29532. _getBindGroup( groupName, bindings ) {
  29533. const bindGroupsCache = this.getBindGroupsCache();
  29534. //
  29535. const bindingsArray = [];
  29536. let sharedGroup = true;
  29537. for ( const binding of bindings ) {
  29538. bindingsArray.push( binding );
  29539. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  29540. }
  29541. //
  29542. let bindGroup;
  29543. if ( sharedGroup ) {
  29544. bindGroup = bindGroupsCache.get( bindingsArray );
  29545. if ( bindGroup === undefined ) {
  29546. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  29547. bindGroupsCache.set( bindingsArray, bindGroup );
  29548. }
  29549. } else {
  29550. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  29551. }
  29552. return bindGroup;
  29553. }
  29554. /**
  29555. * Returns an array of node uniform groups for the given group name and shader stage.
  29556. *
  29557. * @param {String} groupName - The group name.
  29558. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  29559. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  29560. */
  29561. getBindGroupArray( groupName, shaderStage ) {
  29562. const bindings = this.bindings[ shaderStage ];
  29563. let bindGroup = bindings[ groupName ];
  29564. if ( bindGroup === undefined ) {
  29565. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  29566. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  29567. }
  29568. bindings[ groupName ] = bindGroup = [];
  29569. }
  29570. return bindGroup;
  29571. }
  29572. /**
  29573. * Returns a list bindings of all shader stages separated by groups.
  29574. *
  29575. * @return {Array<BindGroup>} The list of bindings.
  29576. */
  29577. getBindings() {
  29578. let bindingsGroups = this.bindGroups;
  29579. if ( bindingsGroups === null ) {
  29580. const groups = {};
  29581. const bindings = this.bindings;
  29582. for ( const shaderStage of shaderStages ) {
  29583. for ( const groupName in bindings[ shaderStage ] ) {
  29584. const uniforms = bindings[ shaderStage ][ groupName ];
  29585. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  29586. groupUniforms.push( ...uniforms );
  29587. }
  29588. }
  29589. bindingsGroups = [];
  29590. for ( const groupName in groups ) {
  29591. const group = groups[ groupName ];
  29592. const bindingsGroup = this._getBindGroup( groupName, group );
  29593. bindingsGroups.push( bindingsGroup );
  29594. }
  29595. this.bindGroups = bindingsGroups;
  29596. }
  29597. return bindingsGroups;
  29598. }
  29599. /**
  29600. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  29601. */
  29602. sortBindingGroups() {
  29603. const bindingsGroups = this.getBindings();
  29604. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  29605. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  29606. const bindingGroup = bindingsGroups[ i ];
  29607. this.bindingsIndexes[ bindingGroup.name ].group = i;
  29608. bindingGroup.index = i;
  29609. }
  29610. }
  29611. /**
  29612. * The builder maintains each node in a hash-based dictionary.
  29613. * This method sets the given node (value) with the given hash (key) into this dictionary.
  29614. *
  29615. * @param {Node} node - The node to add.
  29616. * @param {Number} hash - The hash of the node.
  29617. */
  29618. setHashNode( node, hash ) {
  29619. this.hashNodes[ hash ] = node;
  29620. }
  29621. /**
  29622. * Adds a node to this builder.
  29623. *
  29624. * @param {Node} node - The node to add.
  29625. */
  29626. addNode( node ) {
  29627. if ( this.nodes.includes( node ) === false ) {
  29628. this.nodes.push( node );
  29629. this.setHashNode( node, node.getHash( this ) );
  29630. }
  29631. }
  29632. /**
  29633. * It is used to add Nodes that will be used as FRAME and RENDER events,
  29634. * and need to follow a certain sequence in the calls to work correctly.
  29635. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  29636. *
  29637. * @param {Node} node - The node to add.
  29638. */
  29639. addSequentialNode( node ) {
  29640. if ( this.sequentialNodes.includes( node ) === false ) {
  29641. this.sequentialNodes.push( node );
  29642. }
  29643. }
  29644. /**
  29645. * Checks the update types of nodes
  29646. */
  29647. buildUpdateNodes() {
  29648. for ( const node of this.nodes ) {
  29649. const updateType = node.getUpdateType();
  29650. if ( updateType !== NodeUpdateType.NONE ) {
  29651. this.updateNodes.push( node.getSelf() );
  29652. }
  29653. }
  29654. for ( const node of this.sequentialNodes ) {
  29655. const updateBeforeType = node.getUpdateBeforeType();
  29656. const updateAfterType = node.getUpdateAfterType();
  29657. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  29658. this.updateBeforeNodes.push( node.getSelf() );
  29659. }
  29660. if ( updateAfterType !== NodeUpdateType.NONE ) {
  29661. this.updateAfterNodes.push( node.getSelf() );
  29662. }
  29663. }
  29664. }
  29665. /**
  29666. * A reference the current node which is the
  29667. * last node in the chain of nodes.
  29668. *
  29669. * @type {Node}
  29670. */
  29671. get currentNode() {
  29672. return this.chaining[ this.chaining.length - 1 ];
  29673. }
  29674. /**
  29675. * Whether the given texture is filtered or not.
  29676. *
  29677. * @param {Texture} texture - The texture to check.
  29678. * @return {Boolean} Whether the given texture is filtered or not.
  29679. */
  29680. isFilteredTexture( texture ) {
  29681. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  29682. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  29683. }
  29684. /**
  29685. * Adds the given node to the internal node chain.
  29686. * This is used to check recursive calls in node-graph.
  29687. *
  29688. * @param {Node} node - The node to add.
  29689. */
  29690. addChain( node ) {
  29691. /*
  29692. if ( this.chaining.indexOf( node ) !== - 1 ) {
  29693. console.warn( 'Recursive node: ', node );
  29694. }
  29695. */
  29696. this.chaining.push( node );
  29697. }
  29698. /**
  29699. * Removes the given node from the internal node chain.
  29700. *
  29701. * @param {Node} node - The node to remove.
  29702. */
  29703. removeChain( node ) {
  29704. const lastChain = this.chaining.pop();
  29705. if ( lastChain !== node ) {
  29706. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  29707. }
  29708. }
  29709. /**
  29710. * Returns the native shader method name for a given generic name. E.g.
  29711. * the method name `textureDimensions` matches the WGSL name but must be
  29712. * resolved to `textureSize` in GLSL.
  29713. *
  29714. * @abstract
  29715. * @param {String} method - The method name to resolve.
  29716. * @return {String} The resolved method name.
  29717. */
  29718. getMethod( method ) {
  29719. return method;
  29720. }
  29721. /**
  29722. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  29723. *
  29724. * @param {Number} hash - The hash of the node.
  29725. * @return {Node} The found node.
  29726. */
  29727. getNodeFromHash( hash ) {
  29728. return this.hashNodes[ hash ];
  29729. }
  29730. /**
  29731. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  29732. *
  29733. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  29734. * @param {Node} node - The node to add.
  29735. * @return {Node} The node.
  29736. */
  29737. addFlow( shaderStage, node ) {
  29738. this.flowNodes[ shaderStage ].push( node );
  29739. return node;
  29740. }
  29741. /**
  29742. * Sets builder's context.
  29743. *
  29744. * @param {Object} context - The context to set.
  29745. */
  29746. setContext( context ) {
  29747. this.context = context;
  29748. }
  29749. /**
  29750. * Returns the builder's current context.
  29751. *
  29752. * @return {Object} The builder's current context.
  29753. */
  29754. getContext() {
  29755. return this.context;
  29756. }
  29757. /**
  29758. * Gets a context used in shader construction that can be shared across different materials.
  29759. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  29760. *
  29761. * @return {Object} The builder's current context without material.
  29762. */
  29763. getSharedContext() {
  29764. ({ ...this.context });
  29765. return this.context;
  29766. }
  29767. /**
  29768. * Sets builder's cache.
  29769. *
  29770. * @param {NodeCache} cache - The cache to set.
  29771. */
  29772. setCache( cache ) {
  29773. this.cache = cache;
  29774. }
  29775. /**
  29776. * Returns the builder's current cache.
  29777. *
  29778. * @return {NodeCache} The builder's current cache.
  29779. */
  29780. getCache() {
  29781. return this.cache;
  29782. }
  29783. /**
  29784. * Returns a cache for the given node.
  29785. *
  29786. * @param {Node} node - The node.
  29787. * @param {Boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  29788. * @return {NodeCache} The cache.
  29789. */
  29790. getCacheFromNode( node, parent = true ) {
  29791. const data = this.getDataFromNode( node );
  29792. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  29793. return data.cache;
  29794. }
  29795. /**
  29796. * Whether the requested feature is available or not.
  29797. *
  29798. * @abstract
  29799. * @param {String} name - The requested feature.
  29800. * @return {Boolean} Whether the requested feature is supported or not.
  29801. */
  29802. isAvailable( /*name*/ ) {
  29803. return false;
  29804. }
  29805. /**
  29806. * Returns the vertexIndex input variable as a native shader string.
  29807. *
  29808. * @abstract
  29809. * @return {String} The instanceIndex shader string.
  29810. */
  29811. getVertexIndex() {
  29812. console.warn( 'Abstract function.' );
  29813. }
  29814. /**
  29815. * Returns the instanceIndex input variable as a native shader string.
  29816. *
  29817. * @abstract
  29818. * @return {String} The instanceIndex shader string.
  29819. */
  29820. getInstanceIndex() {
  29821. console.warn( 'Abstract function.' );
  29822. }
  29823. /**
  29824. * Returns the drawIndex input variable as a native shader string.
  29825. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  29826. *
  29827. * @abstract
  29828. * @return {String} The drawIndex shader string.
  29829. */
  29830. getDrawIndex() {
  29831. console.warn( 'Abstract function.' );
  29832. }
  29833. /**
  29834. * Returns the frontFacing input variable as a native shader string.
  29835. *
  29836. * @abstract
  29837. * @return {String} The frontFacing shader string.
  29838. */
  29839. getFrontFacing() {
  29840. console.warn( 'Abstract function.' );
  29841. }
  29842. /**
  29843. * Returns the fragCoord input variable as a native shader string.
  29844. *
  29845. * @abstract
  29846. * @return {String} The fragCoord shader string.
  29847. */
  29848. getFragCoord() {
  29849. console.warn( 'Abstract function.' );
  29850. }
  29851. /**
  29852. * Whether to flip texture data along its vertical axis or not. WebGL needs
  29853. * this method evaluate to `true`, WebGPU to `false`.
  29854. *
  29855. * @abstract
  29856. * @return {Boolean} Whether to flip texture data along its vertical axis or not.
  29857. */
  29858. isFlipY() {
  29859. return false;
  29860. }
  29861. /**
  29862. * Calling this method increases the usage count for the given node by one.
  29863. *
  29864. * @param {Node} node - The node to increase the usage count for.
  29865. * @return {Number} The updated usage count.
  29866. */
  29867. increaseUsage( node ) {
  29868. const nodeData = this.getDataFromNode( node );
  29869. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  29870. return nodeData.usageCount;
  29871. }
  29872. /**
  29873. * Generates a texture sample shader string for the given texture data.
  29874. *
  29875. * @abstract
  29876. * @param {Texture} texture - The texture.
  29877. * @param {String} textureProperty - The texture property name.
  29878. * @param {String} uvSnippet - Snippet defining the texture coordinates.
  29879. * @return {String} The generated shader string.
  29880. */
  29881. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  29882. console.warn( 'Abstract function.' );
  29883. }
  29884. /**
  29885. * Generates a texture LOD shader string for the given texture data.
  29886. *
  29887. * @abstract
  29888. * @param {Texture} texture - The texture.
  29889. * @param {String} textureProperty - The texture property name.
  29890. * @param {String} uvSnippet - Snippet defining the texture coordinates.
  29891. * @param {String?} depthSnippet - Snippet defining the 0-based texture array index to sample.
  29892. * @param {String} levelSnippet - Snippet defining the mip level.
  29893. * @return {String} The generated shader string.
  29894. */
  29895. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  29896. console.warn( 'Abstract function.' );
  29897. }
  29898. /**
  29899. * Generates the shader string for the given type and value.
  29900. *
  29901. * @param {String} type - The type.
  29902. * @param {Any?} [value=null] - The value.
  29903. * @return {String} The generated value as a shader string.
  29904. */
  29905. generateConst( type, value = null ) {
  29906. if ( value === null ) {
  29907. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  29908. else if ( type === 'bool' ) value = false;
  29909. else if ( type === 'color' ) value = new Color();
  29910. else if ( type === 'vec2' ) value = new Vector2();
  29911. else if ( type === 'vec3' ) value = new Vector3();
  29912. else if ( type === 'vec4' ) value = new Vector4();
  29913. }
  29914. if ( type === 'float' ) return toFloat( value );
  29915. if ( type === 'int' ) return `${ Math.round( value ) }`;
  29916. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  29917. if ( type === 'bool' ) return value ? 'true' : 'false';
  29918. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  29919. const typeLength = this.getTypeLength( type );
  29920. const componentType = this.getComponentType( type );
  29921. const generateConst = value => this.generateConst( componentType, value );
  29922. if ( typeLength === 2 ) {
  29923. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  29924. } else if ( typeLength === 3 ) {
  29925. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  29926. } else if ( typeLength === 4 ) {
  29927. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  29928. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  29929. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  29930. } else if ( typeLength > 4 ) {
  29931. return `${ this.getType( type ) }()`;
  29932. }
  29933. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  29934. }
  29935. /**
  29936. * It might be necessary to convert certain data types to different ones
  29937. * so this method can be used to hide the conversion.
  29938. *
  29939. * @param {String} type - The type.
  29940. * @return {String} The updated type.
  29941. */
  29942. getType( type ) {
  29943. if ( type === 'color' ) return 'vec3';
  29944. return type;
  29945. }
  29946. /**
  29947. * Whether the given attribute name is defined in the geometry or not.
  29948. *
  29949. * @param {String} name - The attribute name.
  29950. * @return {Boolean} Whether the given attribute name is defined in the geometry.
  29951. */
  29952. hasGeometryAttribute( name ) {
  29953. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  29954. }
  29955. /**
  29956. * Returns a node attribute for the given name and type.
  29957. *
  29958. * @param {String} name - The attribute's name.
  29959. * @param {String} type - The attribute's type.
  29960. * @return {NodeAttribute} The node attribute.
  29961. */
  29962. getAttribute( name, type ) {
  29963. const attributes = this.attributes;
  29964. // find attribute
  29965. for ( const attribute of attributes ) {
  29966. if ( attribute.name === name ) {
  29967. return attribute;
  29968. }
  29969. }
  29970. // create a new if no exist
  29971. const attribute = new NodeAttribute( name, type );
  29972. attributes.push( attribute );
  29973. return attribute;
  29974. }
  29975. /**
  29976. * Returns for the given node and shader stage the property name for the shader.
  29977. *
  29978. * @param {Node} node - The node.
  29979. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  29980. * @return {String} The property name.
  29981. */
  29982. getPropertyName( node/*, shaderStage*/ ) {
  29983. return node.name;
  29984. }
  29985. /**
  29986. * Whether the given type is a vector type or not.
  29987. *
  29988. * @param {String} type - The type to check.
  29989. * @return {Boolean} Whether the given type is a vector type or not.
  29990. */
  29991. isVector( type ) {
  29992. return /vec\d/.test( type );
  29993. }
  29994. /**
  29995. * Whether the given type is a matrix type or not.
  29996. *
  29997. * @param {String} type - The type to check.
  29998. * @return {Boolean} Whether the given type is a matrix type or not.
  29999. */
  30000. isMatrix( type ) {
  30001. return /mat\d/.test( type );
  30002. }
  30003. /**
  30004. * Whether the given type is a reference type or not.
  30005. *
  30006. * @param {String} type - The type to check.
  30007. * @return {Boolean} Whether the given type is a reference type or not.
  30008. */
  30009. isReference( type ) {
  30010. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  30011. }
  30012. /**
  30013. * Checks if the given texture requires a manual conversion to the working color space.
  30014. *
  30015. * @abstract
  30016. * @param {Texture} texture - The texture to check.
  30017. * @return {Boolean} Whether the given texture requires a conversion to working color space or not.
  30018. */
  30019. needsToWorkingColorSpace( /*texture*/ ) {
  30020. return false;
  30021. }
  30022. /**
  30023. * Returns the component type of a given texture.
  30024. *
  30025. * @param {Texture} texture - The texture.
  30026. * @return {String} The component type.
  30027. */
  30028. getComponentTypeFromTexture( texture ) {
  30029. const type = texture.type;
  30030. if ( texture.isDataTexture ) {
  30031. if ( type === IntType ) return 'int';
  30032. if ( type === UnsignedIntType ) return 'uint';
  30033. }
  30034. return 'float';
  30035. }
  30036. /**
  30037. * Returns the element type for a given type.
  30038. *
  30039. * @param {String} type - The type.
  30040. * @return {String} The element type.
  30041. */
  30042. getElementType( type ) {
  30043. if ( type === 'mat2' ) return 'vec2';
  30044. if ( type === 'mat3' ) return 'vec3';
  30045. if ( type === 'mat4' ) return 'vec4';
  30046. return this.getComponentType( type );
  30047. }
  30048. /**
  30049. * Returns the component type for a given type.
  30050. *
  30051. * @param {String} type - The type.
  30052. * @return {String} The component type.
  30053. */
  30054. getComponentType( type ) {
  30055. type = this.getVectorType( type );
  30056. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  30057. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  30058. if ( componentType === null ) return null;
  30059. if ( componentType[ 1 ] === 'b' ) return 'bool';
  30060. if ( componentType[ 1 ] === 'i' ) return 'int';
  30061. if ( componentType[ 1 ] === 'u' ) return 'uint';
  30062. return 'float';
  30063. }
  30064. /**
  30065. * Returns the vector type for a given type.
  30066. *
  30067. * @param {String} type - The type.
  30068. * @return {String} The vector type.
  30069. */
  30070. getVectorType( type ) {
  30071. if ( type === 'color' ) return 'vec3';
  30072. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  30073. return type;
  30074. }
  30075. /**
  30076. * Returns the data type for the given the length and component type.
  30077. *
  30078. * @param {Number} length - The length.
  30079. * @param {String} [componentType='float'] - The component type.
  30080. * @return {String} The type.
  30081. */
  30082. getTypeFromLength( length, componentType = 'float' ) {
  30083. if ( length === 1 ) return componentType;
  30084. const baseType = getTypeFromLength( length );
  30085. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  30086. return prefix + baseType;
  30087. }
  30088. /**
  30089. * Returns the type for a given typed array.
  30090. *
  30091. * @param {TypedArray} array - The typed array.
  30092. * @return {String} The type.
  30093. */
  30094. getTypeFromArray( array ) {
  30095. return typeFromArray.get( array.constructor );
  30096. }
  30097. /**
  30098. * Returns the type for a given buffer attribute.
  30099. *
  30100. * @param {BufferAttribute} attribute - The buffer attribute.
  30101. * @return {String} The type.
  30102. */
  30103. getTypeFromAttribute( attribute ) {
  30104. let dataAttribute = attribute;
  30105. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  30106. const array = dataAttribute.array;
  30107. const itemSize = attribute.itemSize;
  30108. const normalized = attribute.normalized;
  30109. let arrayType;
  30110. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  30111. arrayType = this.getTypeFromArray( array );
  30112. }
  30113. return this.getTypeFromLength( itemSize, arrayType );
  30114. }
  30115. /**
  30116. * Returns the length for the given data type.
  30117. *
  30118. * @param {String} type - The data type.
  30119. * @return {Number} The length.
  30120. */
  30121. getTypeLength( type ) {
  30122. const vecType = this.getVectorType( type );
  30123. const vecNum = /vec([2-4])/.exec( vecType );
  30124. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  30125. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  30126. if ( /mat2/.test( type ) === true ) return 4;
  30127. if ( /mat3/.test( type ) === true ) return 9;
  30128. if ( /mat4/.test( type ) === true ) return 16;
  30129. return 0;
  30130. }
  30131. /**
  30132. * Returns the vector type for a given matrix type.
  30133. *
  30134. * @param {String} type - The matrix type.
  30135. * @return {String} The vector type.
  30136. */
  30137. getVectorFromMatrix( type ) {
  30138. return type.replace( 'mat', 'vec' );
  30139. }
  30140. /**
  30141. * For a given type this method changes the component type to the
  30142. * given value. E.g. `vec4` should be changed to the new component type
  30143. * `uint` which results in `uvec4`.
  30144. *
  30145. * @param {String} type - The type.
  30146. * @param {String} newComponentType - The new component type.
  30147. * @return {String} The new type.
  30148. */
  30149. changeComponentType( type, newComponentType ) {
  30150. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  30151. }
  30152. /**
  30153. * Returns the integer type pendant for the given type.
  30154. *
  30155. * @param {String} type - The type.
  30156. * @return {String} The integer type.
  30157. */
  30158. getIntegerType( type ) {
  30159. const componentType = this.getComponentType( type );
  30160. if ( componentType === 'int' || componentType === 'uint' ) return type;
  30161. return this.changeComponentType( type, 'int' );
  30162. }
  30163. /**
  30164. * Adds a stack node to the internal stack.
  30165. *
  30166. * @return {StackNode} The added stack node.
  30167. */
  30168. addStack() {
  30169. this.stack = stack( this.stack );
  30170. this.stacks.push( getCurrentStack() || this.stack );
  30171. setCurrentStack( this.stack );
  30172. return this.stack;
  30173. }
  30174. /**
  30175. * Removes the last stack node from the internal stack.
  30176. *
  30177. * @return {StackNode} The removed stack node.
  30178. */
  30179. removeStack() {
  30180. const lastStack = this.stack;
  30181. this.stack = lastStack.parent;
  30182. setCurrentStack( this.stacks.pop() );
  30183. return lastStack;
  30184. }
  30185. /**
  30186. * The builder maintains (cached) data for each node during the building process. This method
  30187. * can be used to get these data for a specific shader stage and cache.
  30188. *
  30189. * @param {Node} node - The node to get the data for.
  30190. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30191. * @param {NodeCache?} cache - An optional cache.
  30192. * @return {Object} The node data.
  30193. */
  30194. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  30195. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  30196. let nodeData = cache.getData( node );
  30197. if ( nodeData === undefined ) {
  30198. nodeData = {};
  30199. cache.setData( node, nodeData );
  30200. }
  30201. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  30202. return nodeData[ shaderStage ];
  30203. }
  30204. /**
  30205. * Returns the properties for the given node and shader stage.
  30206. *
  30207. * @param {Node} node - The node to get the properties for.
  30208. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  30209. * @return {Object} The node properties.
  30210. */
  30211. getNodeProperties( node, shaderStage = 'any' ) {
  30212. const nodeData = this.getDataFromNode( node, shaderStage );
  30213. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  30214. }
  30215. /**
  30216. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  30217. *
  30218. * @param {BufferAttributeNode} node - The buffer attribute node.
  30219. * @param {String} type - The node type.
  30220. * @return {NodeAttribute} The node attribute.
  30221. */
  30222. getBufferAttributeFromNode( node, type ) {
  30223. const nodeData = this.getDataFromNode( node );
  30224. let bufferAttribute = nodeData.bufferAttribute;
  30225. if ( bufferAttribute === undefined ) {
  30226. const index = this.uniforms.index ++;
  30227. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  30228. this.bufferAttributes.push( bufferAttribute );
  30229. nodeData.bufferAttribute = bufferAttribute;
  30230. }
  30231. return bufferAttribute;
  30232. }
  30233. /**
  30234. * Returns an instance of {@link StructTypeNode} for the given output struct node.
  30235. *
  30236. * @param {OutputStructNode} node - The output struct node.
  30237. * @param {Array<String>} types - The output struct types.
  30238. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30239. * @return {StructTypeNode} The struct type attribute.
  30240. */
  30241. getStructTypeFromNode( node, types, shaderStage = this.shaderStage ) {
  30242. const nodeData = this.getDataFromNode( node, shaderStage );
  30243. let structType = nodeData.structType;
  30244. if ( structType === undefined ) {
  30245. const index = this.structs.index ++;
  30246. structType = new StructTypeNode( 'StructType' + index, types );
  30247. this.structs[ shaderStage ].push( structType );
  30248. nodeData.structType = structType;
  30249. }
  30250. return structType;
  30251. }
  30252. /**
  30253. * Returns an instance of {@link NodeUniform} for the given uniform node.
  30254. *
  30255. * @param {UniformNode} node - The uniform node.
  30256. * @param {String} type - The uniform type.
  30257. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30258. * @param {String?} name - The name of the uniform.
  30259. * @return {NodeUniform} The node uniform.
  30260. */
  30261. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  30262. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  30263. let nodeUniform = nodeData.uniform;
  30264. if ( nodeUniform === undefined ) {
  30265. const index = this.uniforms.index ++;
  30266. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  30267. this.uniforms[ shaderStage ].push( nodeUniform );
  30268. nodeData.uniform = nodeUniform;
  30269. }
  30270. return nodeUniform;
  30271. }
  30272. /**
  30273. * Returns an instance of {@link NodeVar} for the given variable node.
  30274. *
  30275. * @param {VarNode} node - The variable node.
  30276. * @param {String?} name - The variable's name.
  30277. * @param {String} [type=node.getNodeType( this )] - The variable's type.
  30278. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30279. * @return {NodeVar} The node variable.
  30280. */
  30281. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  30282. const nodeData = this.getDataFromNode( node, shaderStage );
  30283. let nodeVar = nodeData.variable;
  30284. if ( nodeVar === undefined ) {
  30285. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  30286. if ( name === null ) name = 'nodeVar' + vars.length;
  30287. nodeVar = new NodeVar( name, type );
  30288. vars.push( nodeVar );
  30289. nodeData.variable = nodeVar;
  30290. }
  30291. return nodeVar;
  30292. }
  30293. /**
  30294. * Returns an instance of {@link NodeVarying} for the given varying node.
  30295. *
  30296. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  30297. * @param {String?} name - The varying's name.
  30298. * @param {String} [type=node.getNodeType( this )] - The varying's type.
  30299. * @return {NodeVar} The node varying.
  30300. */
  30301. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  30302. const nodeData = this.getDataFromNode( node, 'any' );
  30303. let nodeVarying = nodeData.varying;
  30304. if ( nodeVarying === undefined ) {
  30305. const varyings = this.varyings;
  30306. const index = varyings.length;
  30307. if ( name === null ) name = 'nodeVarying' + index;
  30308. nodeVarying = new NodeVarying( name, type );
  30309. varyings.push( nodeVarying );
  30310. nodeData.varying = nodeVarying;
  30311. }
  30312. return nodeVarying;
  30313. }
  30314. /**
  30315. * Returns an instance of {@link NodeCode} for the given code node.
  30316. *
  30317. * @param {CodeNode} node - The code node.
  30318. * @param {String} type - The node type.
  30319. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30320. * @return {NodeCode} The node code.
  30321. */
  30322. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  30323. const nodeData = this.getDataFromNode( node );
  30324. let nodeCode = nodeData.code;
  30325. if ( nodeCode === undefined ) {
  30326. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  30327. const index = codes.length;
  30328. nodeCode = new NodeCode( 'nodeCode' + index, type );
  30329. codes.push( nodeCode );
  30330. nodeData.code = nodeCode;
  30331. }
  30332. return nodeCode;
  30333. }
  30334. /**
  30335. * Adds a code flow based on the code-block hierarchy.
  30336. * This is used so that code-blocks like If,Else create their variables locally if the Node
  30337. * is only used inside one of these conditionals in the current shader stage.
  30338. *
  30339. * @param {Node} node - The node to add.
  30340. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  30341. */
  30342. addFlowCodeHierarchy( node, nodeBlock ) {
  30343. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  30344. let needsFlowCode = true;
  30345. let nodeBlockHierarchy = nodeBlock;
  30346. while ( nodeBlockHierarchy ) {
  30347. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  30348. needsFlowCode = false;
  30349. break;
  30350. }
  30351. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  30352. }
  30353. if ( needsFlowCode ) {
  30354. for ( const flowCode of flowCodes ) {
  30355. this.addLineFlowCode( flowCode );
  30356. }
  30357. }
  30358. }
  30359. /**
  30360. * Add a inline-code to the current flow code-block.
  30361. *
  30362. * @param {Node} node - The node to add.
  30363. * @param {String} code - The code to add.
  30364. * @param {Node} nodeBlock - Current ConditionalNode
  30365. */
  30366. addLineFlowCodeBlock( node, code, nodeBlock ) {
  30367. const nodeData = this.getDataFromNode( node );
  30368. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  30369. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  30370. flowCodes.push( code );
  30371. codeBlock.set( nodeBlock, true );
  30372. }
  30373. /**
  30374. * Add a inline-code to the current flow.
  30375. *
  30376. * @param {String} code - The code to add.
  30377. * @param {Node?} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  30378. * @return {NodeBuilder} A reference to this node builder.
  30379. */
  30380. addLineFlowCode( code, node = null ) {
  30381. if ( code === '' ) return this;
  30382. if ( node !== null && this.context.nodeBlock ) {
  30383. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  30384. }
  30385. code = this.tab + code;
  30386. if ( ! /;\s*$/.test( code ) ) {
  30387. code = code + ';\n';
  30388. }
  30389. this.flow.code += code;
  30390. return this;
  30391. }
  30392. /**
  30393. * Adds a code to the current code flow.
  30394. *
  30395. * @param {String} code - Shader code.
  30396. * @return {NodeBuilder} A reference to this node builder.
  30397. */
  30398. addFlowCode( code ) {
  30399. this.flow.code += code;
  30400. return this;
  30401. }
  30402. /**
  30403. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  30404. * Typically used in codes with If,Else.
  30405. *
  30406. * @return {NodeBuilder} A reference to this node builder.
  30407. */
  30408. addFlowTab() {
  30409. this.tab += '\t';
  30410. return this;
  30411. }
  30412. /**
  30413. * Removes a tab.
  30414. *
  30415. * @return {NodeBuilder} A reference to this node builder.
  30416. */
  30417. removeFlowTab() {
  30418. this.tab = this.tab.slice( 0, - 1 );
  30419. return this;
  30420. }
  30421. /**
  30422. * Gets the current flow data based on a Node.
  30423. *
  30424. * @param {Node} node - Node that the flow was started.
  30425. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30426. * @return {Object} The flow data.
  30427. */
  30428. getFlowData( node/*, shaderStage*/ ) {
  30429. return this.flowsData.get( node );
  30430. }
  30431. /**
  30432. * Executes the node flow based on a root node to generate the final shader code.
  30433. *
  30434. * @param {Node} node - The node to execute.
  30435. * @return {Object} The code flow.
  30436. */
  30437. flowNode( node ) {
  30438. const output = node.getNodeType( this );
  30439. const flowData = this.flowChildNode( node, output );
  30440. this.flowsData.set( node, flowData );
  30441. return flowData;
  30442. }
  30443. /**
  30444. * Returns the native shader operator name for a given generic name.
  30445. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  30446. *
  30447. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  30448. * @return {FunctionNode} The build function node.
  30449. */
  30450. buildFunctionNode( shaderNode ) {
  30451. const fn = new FunctionNode();
  30452. const previous = this.currentFunctionNode;
  30453. this.currentFunctionNode = fn;
  30454. fn.code = this.buildFunctionCode( shaderNode );
  30455. this.currentFunctionNode = previous;
  30456. return fn;
  30457. }
  30458. /**
  30459. * Generates a code flow based on a TSL function: Fn().
  30460. *
  30461. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  30462. * @return {Object}
  30463. */
  30464. flowShaderNode( shaderNode ) {
  30465. const layout = shaderNode.layout;
  30466. const inputs = {
  30467. [ Symbol.iterator ]() {
  30468. let index = 0;
  30469. const values = Object.values( this );
  30470. return {
  30471. next: () => ( {
  30472. value: values[ index ],
  30473. done: index ++ >= values.length
  30474. } )
  30475. };
  30476. }
  30477. };
  30478. for ( const input of layout.inputs ) {
  30479. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  30480. }
  30481. //
  30482. shaderNode.layout = null;
  30483. const callNode = shaderNode.call( inputs );
  30484. const flowData = this.flowStagesNode( callNode, layout.type );
  30485. shaderNode.layout = layout;
  30486. return flowData;
  30487. }
  30488. /**
  30489. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  30490. *
  30491. * @param {Node} node - The node to execute.
  30492. * @param {String?} output - Expected output type. For example 'vec3'.
  30493. * @return {Object}
  30494. */
  30495. flowStagesNode( node, output = null ) {
  30496. const previousFlow = this.flow;
  30497. const previousVars = this.vars;
  30498. const previousCache = this.cache;
  30499. const previousBuildStage = this.buildStage;
  30500. const previousStack = this.stack;
  30501. const flow = {
  30502. code: ''
  30503. };
  30504. this.flow = flow;
  30505. this.vars = {};
  30506. this.cache = new NodeCache();
  30507. this.stack = stack();
  30508. for ( const buildStage of defaultBuildStages ) {
  30509. this.setBuildStage( buildStage );
  30510. flow.result = node.build( this, output );
  30511. }
  30512. flow.vars = this.getVars( this.shaderStage );
  30513. this.flow = previousFlow;
  30514. this.vars = previousVars;
  30515. this.cache = previousCache;
  30516. this.stack = previousStack;
  30517. this.setBuildStage( previousBuildStage );
  30518. return flow;
  30519. }
  30520. /**
  30521. * Returns the native shader operator name for a given generic name.
  30522. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  30523. *
  30524. * @abstract
  30525. * @param {String} op - The operator name to resolve.
  30526. * @return {String} The resolved operator name.
  30527. */
  30528. getFunctionOperator( /* op */ ) {
  30529. return null;
  30530. }
  30531. /**
  30532. * Generates a code flow based on a child Node.
  30533. *
  30534. * @param {Node} node - The node to execute.
  30535. * @param {String?} output - Expected output type. For example 'vec3'.
  30536. * @return {Object} The code flow.
  30537. */
  30538. flowChildNode( node, output = null ) {
  30539. const previousFlow = this.flow;
  30540. const flow = {
  30541. code: ''
  30542. };
  30543. this.flow = flow;
  30544. flow.result = node.build( this, output );
  30545. this.flow = previousFlow;
  30546. return flow;
  30547. }
  30548. /**
  30549. * Executes a flow of code in a different stage.
  30550. *
  30551. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  30552. * return the value in fragment-stage even if it is being executed in an input fragment.
  30553. *
  30554. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30555. * @param {Node} node - The node to execute.
  30556. * @param {String?} output - Expected output type. For example 'vec3'.
  30557. * @param {String?} propertyName - The property name to assign the result.
  30558. * @return {Object}
  30559. */
  30560. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  30561. const previousShaderStage = this.shaderStage;
  30562. this.setShaderStage( shaderStage );
  30563. const flowData = this.flowChildNode( node, output );
  30564. if ( propertyName !== null ) {
  30565. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  30566. }
  30567. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  30568. this.setShaderStage( previousShaderStage );
  30569. return flowData;
  30570. }
  30571. /**
  30572. * Returns an array holding all node attributes of this node builder.
  30573. *
  30574. * @return {Array<NodeAttribute>} The node attributes of this builder.
  30575. */
  30576. getAttributesArray() {
  30577. return this.attributes.concat( this.bufferAttributes );
  30578. }
  30579. /**
  30580. * Returns the attribute definitions as a shader string for the given shader stage.
  30581. *
  30582. * @abstract
  30583. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30584. * @return {String} The attribute code section.
  30585. */
  30586. getAttributes( /*shaderStage*/ ) {
  30587. console.warn( 'Abstract function.' );
  30588. }
  30589. /**
  30590. * Returns the varying definitions as a shader string for the given shader stage.
  30591. *
  30592. * @abstract
  30593. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30594. * @return {String} The varying code section.
  30595. */
  30596. getVaryings( /*shaderStage*/ ) {
  30597. console.warn( 'Abstract function.' );
  30598. }
  30599. /**
  30600. * Returns a single variable definition as a shader string for the given variable type and name.
  30601. *
  30602. * @param {String} type - The variable's type.
  30603. * @param {String} name - The variable's name.
  30604. * @return {String} The shader string.
  30605. */
  30606. getVar( type, name ) {
  30607. return `${ this.getType( type ) } ${ name }`;
  30608. }
  30609. /**
  30610. * Returns the variable definitions as a shader string for the given shader stage.
  30611. *
  30612. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30613. * @return {String} The variable code section.
  30614. */
  30615. getVars( shaderStage ) {
  30616. let snippet = '';
  30617. const vars = this.vars[ shaderStage ];
  30618. if ( vars !== undefined ) {
  30619. for ( const variable of vars ) {
  30620. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  30621. }
  30622. }
  30623. return snippet;
  30624. }
  30625. /**
  30626. * Returns the uniform definitions as a shader string for the given shader stage.
  30627. *
  30628. * @abstract
  30629. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30630. * @return {String} The uniform code section.
  30631. */
  30632. getUniforms( /*shaderStage*/ ) {
  30633. console.warn( 'Abstract function.' );
  30634. }
  30635. /**
  30636. * Returns the native code definitions as a shader string for the given shader stage.
  30637. *
  30638. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30639. * @return {String} The native code section.
  30640. */
  30641. getCodes( shaderStage ) {
  30642. const codes = this.codes[ shaderStage ];
  30643. let code = '';
  30644. if ( codes !== undefined ) {
  30645. for ( const nodeCode of codes ) {
  30646. code += nodeCode.code + '\n';
  30647. }
  30648. }
  30649. return code;
  30650. }
  30651. /**
  30652. * Returns the hash of this node builder.
  30653. *
  30654. * @return {String} The hash.
  30655. */
  30656. getHash() {
  30657. return this.vertexShader + this.fragmentShader + this.computeShader;
  30658. }
  30659. /**
  30660. * Sets the current shader stage.
  30661. *
  30662. * @param {('vertex'|'fragment'|'compute'|'any')?} shaderStage - The shader stage to set.
  30663. */
  30664. setShaderStage( shaderStage ) {
  30665. this.shaderStage = shaderStage;
  30666. }
  30667. /**
  30668. * Returns the current shader stage.
  30669. *
  30670. * @return {('vertex'|'fragment'|'compute'|'any')?} The current shader stage.
  30671. */
  30672. getShaderStage() {
  30673. return this.shaderStage;
  30674. }
  30675. /**
  30676. * Sets the current build stage.
  30677. *
  30678. * @param {('setup'|'analyze'|'generate')?} buildStage - The build stage to set.
  30679. */
  30680. setBuildStage( buildStage ) {
  30681. this.buildStage = buildStage;
  30682. }
  30683. /**
  30684. * Returns the current build stage.
  30685. *
  30686. * @return {('setup'|'analyze'|'generate')?} The current build stage.
  30687. */
  30688. getBuildStage() {
  30689. return this.buildStage;
  30690. }
  30691. /**
  30692. * Controls the code build of the shader stages.
  30693. *
  30694. * @abstract
  30695. */
  30696. buildCode() {
  30697. console.warn( 'Abstract function.' );
  30698. }
  30699. /**
  30700. * Central build method which controls the build for the given object.
  30701. *
  30702. * @return {NodeBuilder} A reference to this node builder.
  30703. */
  30704. build() {
  30705. const { object, material, renderer } = this;
  30706. if ( material !== null ) {
  30707. let nodeMaterial = renderer.library.fromMaterial( material );
  30708. if ( nodeMaterial === null ) {
  30709. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  30710. nodeMaterial = new NodeMaterial();
  30711. }
  30712. nodeMaterial.build( this );
  30713. } else {
  30714. this.addFlow( 'compute', object );
  30715. }
  30716. // setup() -> stage 1: create possible new nodes and returns an output reference node
  30717. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  30718. // generate() -> stage 3: generate shader
  30719. for ( const buildStage of defaultBuildStages ) {
  30720. this.setBuildStage( buildStage );
  30721. if ( this.context.vertex && this.context.vertex.isNode ) {
  30722. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  30723. }
  30724. for ( const shaderStage of shaderStages ) {
  30725. this.setShaderStage( shaderStage );
  30726. const flowNodes = this.flowNodes[ shaderStage ];
  30727. for ( const node of flowNodes ) {
  30728. if ( buildStage === 'generate' ) {
  30729. this.flowNode( node );
  30730. } else {
  30731. node.build( this );
  30732. }
  30733. }
  30734. }
  30735. }
  30736. this.setBuildStage( null );
  30737. this.setShaderStage( null );
  30738. // stage 4: build code for a specific output
  30739. this.buildCode();
  30740. this.buildUpdateNodes();
  30741. return this;
  30742. }
  30743. /**
  30744. * Returns a uniform representation which is later used for UBO generation and rendering.
  30745. *
  30746. * @param {NodeUniform} uniformNode - The uniform node.
  30747. * @param {String} type - The requested type.
  30748. * @return {Uniform} The uniform.
  30749. */
  30750. getNodeUniform( uniformNode, type ) {
  30751. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  30752. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  30753. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  30754. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  30755. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  30756. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  30757. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  30758. throw new Error( `Uniform "${type}" not declared.` );
  30759. }
  30760. /**
  30761. * Formats the given shader snippet from a given type into another one. E.g.
  30762. * this method might be used to convert a simple float string `"1.0"` into a
  30763. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  30764. *
  30765. * @param {String} snippet - The shader snippet.
  30766. * @param {String} fromType - The source type.
  30767. * @param {String} toType - The target type.
  30768. * @return {String} The updated shader string.
  30769. */
  30770. format( snippet, fromType, toType ) {
  30771. fromType = this.getVectorType( fromType );
  30772. toType = this.getVectorType( toType );
  30773. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  30774. return snippet;
  30775. }
  30776. const fromTypeLength = this.getTypeLength( fromType );
  30777. const toTypeLength = this.getTypeLength( toType );
  30778. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  30779. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  30780. }
  30781. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  30782. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  30783. }
  30784. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  30785. // @TODO: ignore for now
  30786. return snippet;
  30787. }
  30788. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  30789. // @TODO: ignore for now
  30790. return snippet;
  30791. }
  30792. if ( fromTypeLength === toTypeLength ) {
  30793. return `${ this.getType( toType ) }( ${ snippet } )`;
  30794. }
  30795. if ( fromTypeLength > toTypeLength ) {
  30796. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  30797. }
  30798. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  30799. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  30800. }
  30801. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  30802. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  30803. }
  30804. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  30805. // convert a number value to vector type, e.g:
  30806. // vec3( 1u ) -> vec3( float( 1u ) )
  30807. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  30808. }
  30809. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  30810. }
  30811. /**
  30812. * Returns a signature with the engine's current revision.
  30813. *
  30814. * @return {String} The signature.
  30815. */
  30816. getSignature() {
  30817. return `// Three.js r${ REVISION } - Node System\n`;
  30818. }
  30819. // deprecated
  30820. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  30821. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  30822. }
  30823. }
  30824. /**
  30825. * Management class for updating nodes. The module tracks metrics like
  30826. * the elapsed time, delta time, the render and frame ID to correctly
  30827. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  30828. * and {@link Node#updateAfter} depending on the node's configuration.
  30829. */
  30830. class NodeFrame {
  30831. /**
  30832. * Constructs a new node fame.
  30833. */
  30834. constructor() {
  30835. /**
  30836. * The elapsed time in seconds.
  30837. *
  30838. * @type {Number}
  30839. * @default 0
  30840. */
  30841. this.time = 0;
  30842. /**
  30843. * The delta time in seconds.
  30844. *
  30845. * @type {Number}
  30846. * @default 0
  30847. */
  30848. this.deltaTime = 0;
  30849. /**
  30850. * The frame ID.
  30851. *
  30852. * @type {Number}
  30853. * @default 0
  30854. */
  30855. this.frameId = 0;
  30856. /**
  30857. * The render ID.
  30858. *
  30859. * @type {Number}
  30860. * @default 0
  30861. */
  30862. this.renderId = 0;
  30863. /**
  30864. * Used to control the {@link Node#update} call.
  30865. *
  30866. * @type {WeakMap<Node, Object>}
  30867. */
  30868. this.updateMap = new WeakMap();
  30869. /**
  30870. * Used to control the {@link Node#updateBefore} call.
  30871. *
  30872. * @type {WeakMap<Node, Object>}
  30873. */
  30874. this.updateBeforeMap = new WeakMap();
  30875. /**
  30876. * Used to control the {@link Node#updateAfter} call.
  30877. *
  30878. * @type {WeakMap<Node, Object>}
  30879. */
  30880. this.updateAfterMap = new WeakMap();
  30881. /**
  30882. * A reference to the current renderer.
  30883. *
  30884. * @type {Renderer?}
  30885. * @default null
  30886. */
  30887. this.renderer = null;
  30888. /**
  30889. * A reference to the current material.
  30890. *
  30891. * @type {Material?}
  30892. * @default null
  30893. */
  30894. this.material = null;
  30895. /**
  30896. * A reference to the current camera.
  30897. *
  30898. * @type {Camera?}
  30899. * @default null
  30900. */
  30901. this.camera = null;
  30902. /**
  30903. * A reference to the current 3D object.
  30904. *
  30905. * @type {Object3D?}
  30906. * @default null
  30907. */
  30908. this.object = null;
  30909. /**
  30910. * A reference to the current scene.
  30911. *
  30912. * @type {Scene?}
  30913. * @default null
  30914. */
  30915. this.scene = null;
  30916. }
  30917. /**
  30918. * Returns a dictionary for a given node and update map which
  30919. * is used to correctly call node update methods per frame or render.
  30920. *
  30921. * @private
  30922. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  30923. * @param {Node} nodeRef - The reference to the current node.
  30924. * @return {Object<String,WeakMap>} The dictionary.
  30925. */
  30926. _getMaps( referenceMap, nodeRef ) {
  30927. let maps = referenceMap.get( nodeRef );
  30928. if ( maps === undefined ) {
  30929. maps = {
  30930. renderMap: new WeakMap(),
  30931. frameMap: new WeakMap()
  30932. };
  30933. referenceMap.set( nodeRef, maps );
  30934. }
  30935. return maps;
  30936. }
  30937. /**
  30938. * This method executes the {@link Node#updateBefore} for the given node.
  30939. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  30940. * is only executed once per frame, render or object depending on the update
  30941. * type.
  30942. *
  30943. * @param {Node} node - The node that should be updated.
  30944. */
  30945. updateBeforeNode( node ) {
  30946. const updateType = node.getUpdateBeforeType();
  30947. const reference = node.updateReference( this );
  30948. if ( updateType === NodeUpdateType.FRAME ) {
  30949. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  30950. if ( frameMap.get( reference ) !== this.frameId ) {
  30951. if ( node.updateBefore( this ) !== false ) {
  30952. frameMap.set( reference, this.frameId );
  30953. }
  30954. }
  30955. } else if ( updateType === NodeUpdateType.RENDER ) {
  30956. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  30957. if ( renderMap.get( reference ) !== this.renderId ) {
  30958. if ( node.updateBefore( this ) !== false ) {
  30959. renderMap.set( reference, this.renderId );
  30960. }
  30961. }
  30962. } else if ( updateType === NodeUpdateType.OBJECT ) {
  30963. node.updateBefore( this );
  30964. }
  30965. }
  30966. /**
  30967. * This method executes the {@link Node#updateAfter} for the given node.
  30968. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  30969. * is only executed once per frame, render or object depending on the update
  30970. * type.
  30971. *
  30972. * @param {Node} node - The node that should be updated.
  30973. */
  30974. updateAfterNode( node ) {
  30975. const updateType = node.getUpdateAfterType();
  30976. const reference = node.updateReference( this );
  30977. if ( updateType === NodeUpdateType.FRAME ) {
  30978. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  30979. if ( frameMap.get( reference ) !== this.frameId ) {
  30980. if ( node.updateAfter( this ) !== false ) {
  30981. frameMap.set( reference, this.frameId );
  30982. }
  30983. }
  30984. } else if ( updateType === NodeUpdateType.RENDER ) {
  30985. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  30986. if ( renderMap.get( reference ) !== this.renderId ) {
  30987. if ( node.updateAfter( this ) !== false ) {
  30988. renderMap.set( reference, this.renderId );
  30989. }
  30990. }
  30991. } else if ( updateType === NodeUpdateType.OBJECT ) {
  30992. node.updateAfter( this );
  30993. }
  30994. }
  30995. /**
  30996. * This method executes the {@link Node#update} for the given node.
  30997. * It makes sure {@link Node#updateType} is honored meaning the update
  30998. * is only executed once per frame, render or object depending on the update
  30999. * type.
  31000. *
  31001. * @param {Node} node - The node that should be updated.
  31002. */
  31003. updateNode( node ) {
  31004. const updateType = node.getUpdateType();
  31005. const reference = node.updateReference( this );
  31006. if ( updateType === NodeUpdateType.FRAME ) {
  31007. const { frameMap } = this._getMaps( this.updateMap, reference );
  31008. if ( frameMap.get( reference ) !== this.frameId ) {
  31009. if ( node.update( this ) !== false ) {
  31010. frameMap.set( reference, this.frameId );
  31011. }
  31012. }
  31013. } else if ( updateType === NodeUpdateType.RENDER ) {
  31014. const { renderMap } = this._getMaps( this.updateMap, reference );
  31015. if ( renderMap.get( reference ) !== this.renderId ) {
  31016. if ( node.update( this ) !== false ) {
  31017. renderMap.set( reference, this.renderId );
  31018. }
  31019. }
  31020. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31021. node.update( this );
  31022. }
  31023. }
  31024. /**
  31025. * Updates the internal state of the node frame. This method is
  31026. * called by the renderer in its internal animation loop.
  31027. */
  31028. update() {
  31029. this.frameId ++;
  31030. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  31031. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  31032. this.lastTime = performance.now();
  31033. this.time += this.deltaTime;
  31034. }
  31035. }
  31036. /**
  31037. * Describes the input of a {@link NodeFunction}.
  31038. */
  31039. class NodeFunctionInput {
  31040. /**
  31041. * Constructs a new node function input.
  31042. *
  31043. * @param {String} type - The input type.
  31044. * @param {String} name - The input name.
  31045. * @param {Number?} [count=null] - If the input is an Array, count will be the length.
  31046. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  31047. * @param {Boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  31048. */
  31049. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  31050. /**
  31051. * The input type.
  31052. *
  31053. * @type {String}
  31054. */
  31055. this.type = type;
  31056. /**
  31057. * The input name.
  31058. *
  31059. * @type {String}
  31060. */
  31061. this.name = name;
  31062. /**
  31063. * If the input is an Array, count will be the length.
  31064. *
  31065. * @type {Number?}
  31066. * @default null
  31067. */
  31068. this.count = count;
  31069. /**
  31070. *The parameter qualifier (only relevant for GLSL).
  31071. *
  31072. * @type {('in'|'out'|'inout')}
  31073. * @default ''
  31074. */
  31075. this.qualifier = qualifier;
  31076. /**
  31077. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  31078. *
  31079. * @type {Boolean}
  31080. * @default false
  31081. */
  31082. this.isConst = isConst;
  31083. }
  31084. }
  31085. NodeFunctionInput.isNodeFunctionInput = true;
  31086. /**
  31087. * Module for representing directional lights as nodes.
  31088. *
  31089. * @augments AnalyticLightNode
  31090. */
  31091. class DirectionalLightNode extends AnalyticLightNode {
  31092. static get type() {
  31093. return 'DirectionalLightNode';
  31094. }
  31095. /**
  31096. * Constructs a new directional light node.
  31097. *
  31098. * @param {DirectionalLight?} [light=null] - The directional light source.
  31099. */
  31100. constructor( light = null ) {
  31101. super( light );
  31102. }
  31103. setup( builder ) {
  31104. super.setup( builder );
  31105. const lightingModel = builder.context.lightingModel;
  31106. const lightColor = this.colorNode;
  31107. const lightDirection = lightTargetDirection( this.light );
  31108. const reflectedLight = builder.context.reflectedLight;
  31109. lightingModel.direct( {
  31110. lightDirection,
  31111. lightColor,
  31112. reflectedLight
  31113. }, builder.stack, builder );
  31114. }
  31115. }
  31116. const _matrix41 = /*@__PURE__*/ new Matrix4();
  31117. const _matrix42 = /*@__PURE__*/ new Matrix4();
  31118. let _ltcLib = null;
  31119. /**
  31120. * Module for representing rect area lights as nodes.
  31121. *
  31122. * @augments AnalyticLightNode
  31123. */
  31124. class RectAreaLightNode extends AnalyticLightNode {
  31125. static get type() {
  31126. return 'RectAreaLightNode';
  31127. }
  31128. /**
  31129. * Constructs a new rect area light node.
  31130. *
  31131. * @param {RectAreaLight?} [light=null] - The rect area light source.
  31132. */
  31133. constructor( light = null ) {
  31134. super( light );
  31135. /**
  31136. * Uniform node representing the half height of the are light.
  31137. *
  31138. * @type {UniformNode<vec3>}
  31139. */
  31140. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  31141. /**
  31142. * Uniform node representing the half width of the are light.
  31143. *
  31144. * @type {UniformNode<vec3>}
  31145. */
  31146. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  31147. /**
  31148. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  31149. * relies on `viewMatrix` which might vary per render call.
  31150. *
  31151. * @type {String}
  31152. * @default 'render'
  31153. */
  31154. this.updateType = NodeUpdateType.RENDER;
  31155. }
  31156. /**
  31157. * Overwritten to updated rect area light specific uniforms.
  31158. *
  31159. * @param {NodeFrame} frame - A reference to the current node frame.
  31160. */
  31161. update( frame ) {
  31162. super.update( frame );
  31163. const { light } = this;
  31164. const viewMatrix = frame.camera.matrixWorldInverse;
  31165. _matrix42.identity();
  31166. _matrix41.copy( light.matrixWorld );
  31167. _matrix41.premultiply( viewMatrix );
  31168. _matrix42.extractRotation( _matrix41 );
  31169. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  31170. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  31171. this.halfWidth.value.applyMatrix4( _matrix42 );
  31172. this.halfHeight.value.applyMatrix4( _matrix42 );
  31173. }
  31174. setup( builder ) {
  31175. super.setup( builder );
  31176. let ltc_1, ltc_2;
  31177. if ( builder.isAvailable( 'float32Filterable' ) ) {
  31178. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  31179. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  31180. } else {
  31181. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  31182. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  31183. }
  31184. const { colorNode, light } = this;
  31185. const lightingModel = builder.context.lightingModel;
  31186. const lightPosition = lightViewPosition( light );
  31187. const reflectedLight = builder.context.reflectedLight;
  31188. lightingModel.directRectArea( {
  31189. lightColor: colorNode,
  31190. lightPosition,
  31191. halfWidth: this.halfWidth,
  31192. halfHeight: this.halfHeight,
  31193. reflectedLight,
  31194. ltc_1,
  31195. ltc_2
  31196. }, builder.stack, builder );
  31197. }
  31198. /**
  31199. * Used to configure the internal BRDF approximation texture data.
  31200. *
  31201. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  31202. */
  31203. static setLTC( ltc ) {
  31204. _ltcLib = ltc;
  31205. }
  31206. }
  31207. /**
  31208. * Module for representing spot lights as nodes.
  31209. *
  31210. * @augments AnalyticLightNode
  31211. */
  31212. class SpotLightNode extends AnalyticLightNode {
  31213. static get type() {
  31214. return 'SpotLightNode';
  31215. }
  31216. /**
  31217. * Constructs a new spot light node.
  31218. *
  31219. * @param {SpotLight?} [light=null] - The spot light source.
  31220. */
  31221. constructor( light = null ) {
  31222. super( light );
  31223. /**
  31224. * Uniform node representing the cone cosine.
  31225. *
  31226. * @type {UniformNode<float>}
  31227. */
  31228. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  31229. /**
  31230. * Uniform node representing the penumbra cosine.
  31231. *
  31232. * @type {UniformNode<float>}
  31233. */
  31234. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  31235. /**
  31236. * Uniform node representing the cutoff distance.
  31237. *
  31238. * @type {UniformNode<float>}
  31239. */
  31240. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  31241. /**
  31242. * Uniform node representing the decay exponent.
  31243. *
  31244. * @type {UniformNode<float>}
  31245. */
  31246. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  31247. }
  31248. /**
  31249. * Overwritten to updated spot light specific uniforms.
  31250. *
  31251. * @param {NodeFrame} frame - A reference to the current node frame.
  31252. */
  31253. update( frame ) {
  31254. super.update( frame );
  31255. const { light } = this;
  31256. this.coneCosNode.value = Math.cos( light.angle );
  31257. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  31258. this.cutoffDistanceNode.value = light.distance;
  31259. this.decayExponentNode.value = light.decay;
  31260. }
  31261. /**
  31262. * Computes the spot attenuation for the given angle.
  31263. *
  31264. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  31265. * @return {Node<float>} The spot attenuation.
  31266. */
  31267. getSpotAttenuation( angleCosine ) {
  31268. const { coneCosNode, penumbraCosNode } = this;
  31269. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  31270. }
  31271. setup( builder ) {
  31272. super.setup( builder );
  31273. const lightingModel = builder.context.lightingModel;
  31274. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  31275. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  31276. const lightDirection = lVector.normalize();
  31277. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  31278. const spotAttenuation = this.getSpotAttenuation( angleCos );
  31279. const lightDistance = lVector.length();
  31280. const lightAttenuation = getDistanceAttenuation( {
  31281. lightDistance,
  31282. cutoffDistance: cutoffDistanceNode,
  31283. decayExponent: decayExponentNode
  31284. } );
  31285. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  31286. if ( light.map ) {
  31287. const spotLightCoord = lightProjectionUV( light );
  31288. const projectedTexture = texture( light.map, spotLightCoord.xy ).onRenderUpdate( () => light.map );
  31289. const inSpotLightMap = spotLightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  31290. lightColor = inSpotLightMap.select( lightColor.mul( projectedTexture ), lightColor );
  31291. }
  31292. const reflectedLight = builder.context.reflectedLight;
  31293. lightingModel.direct( {
  31294. lightDirection,
  31295. lightColor,
  31296. reflectedLight
  31297. }, builder.stack, builder );
  31298. }
  31299. }
  31300. /**
  31301. * An IES version of the default spot light node.
  31302. *
  31303. * @augments SpotLightNode
  31304. */
  31305. class IESSpotLightNode extends SpotLightNode {
  31306. static get type() {
  31307. return 'IESSpotLightNode';
  31308. }
  31309. /**
  31310. * Overwrites the default implementation to compute an IES conform spot attenuation.
  31311. *
  31312. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  31313. * @return {Node<float>} The spot attenuation.
  31314. */
  31315. getSpotAttenuation( angleCosine ) {
  31316. const iesMap = this.light.iesMap;
  31317. let spotAttenuation = null;
  31318. if ( iesMap && iesMap.isTexture === true ) {
  31319. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  31320. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  31321. } else {
  31322. spotAttenuation = super.getSpotAttenuation( angleCosine );
  31323. }
  31324. return spotAttenuation;
  31325. }
  31326. }
  31327. /**
  31328. * Module for representing ambient lights as nodes.
  31329. *
  31330. * @augments AnalyticLightNode
  31331. */
  31332. class AmbientLightNode extends AnalyticLightNode {
  31333. static get type() {
  31334. return 'AmbientLightNode';
  31335. }
  31336. /**
  31337. * Constructs a new ambient light node.
  31338. *
  31339. * @param {AmbientLight?} [light=null] - The ambient light source.
  31340. */
  31341. constructor( light = null ) {
  31342. super( light );
  31343. }
  31344. setup( { context } ) {
  31345. context.irradiance.addAssign( this.colorNode );
  31346. }
  31347. }
  31348. /**
  31349. * Module for representing hemisphere lights as nodes.
  31350. *
  31351. * @augments AnalyticLightNode
  31352. */
  31353. class HemisphereLightNode extends AnalyticLightNode {
  31354. static get type() {
  31355. return 'HemisphereLightNode';
  31356. }
  31357. /**
  31358. * Constructs a new hemisphere light node.
  31359. *
  31360. * @param {HemisphereLight?} [light=null] - The hemisphere light source.
  31361. */
  31362. constructor( light = null ) {
  31363. super( light );
  31364. /**
  31365. * Uniform node representing the light's position.
  31366. *
  31367. * @type {UniformNode<vec3>}
  31368. */
  31369. this.lightPositionNode = lightPosition( light );
  31370. /**
  31371. * A node representing the light's direction.
  31372. *
  31373. * @type {Node<vec3>}
  31374. */
  31375. this.lightDirectionNode = this.lightPositionNode.normalize();
  31376. /**
  31377. * Uniform node representing the light's ground color.
  31378. *
  31379. * @type {UniformNode<vec3>}
  31380. */
  31381. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  31382. }
  31383. /**
  31384. * Overwritten to updated hemisphere light specific uniforms.
  31385. *
  31386. * @param {NodeFrame} frame - A reference to the current node frame.
  31387. */
  31388. update( frame ) {
  31389. const { light } = this;
  31390. super.update( frame );
  31391. this.lightPositionNode.object3d = light;
  31392. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  31393. }
  31394. setup( builder ) {
  31395. const { colorNode, groundColorNode, lightDirectionNode } = this;
  31396. const dotNL = normalView.dot( lightDirectionNode );
  31397. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  31398. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  31399. builder.context.irradiance.addAssign( irradiance );
  31400. }
  31401. }
  31402. /**
  31403. * Module for representing light probes as nodes.
  31404. *
  31405. * @augments AnalyticLightNode
  31406. */
  31407. class LightProbeNode extends AnalyticLightNode {
  31408. static get type() {
  31409. return 'LightProbeNode';
  31410. }
  31411. /**
  31412. * Constructs a new light probe node.
  31413. *
  31414. * @param {LightProbe?} [light=null] - The light probe.
  31415. */
  31416. constructor( light = null ) {
  31417. super( light );
  31418. const array = [];
  31419. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  31420. /**
  31421. * Light probe represented as a uniform of spherical harmonics.
  31422. *
  31423. * @type {UniformArrayNode}
  31424. */
  31425. this.lightProbe = uniformArray( array );
  31426. }
  31427. /**
  31428. * Overwritten to updated light probe specific uniforms.
  31429. *
  31430. * @param {NodeFrame} frame - A reference to the current node frame.
  31431. */
  31432. update( frame ) {
  31433. const { light } = this;
  31434. super.update( frame );
  31435. //
  31436. for ( let i = 0; i < 9; i ++ ) {
  31437. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  31438. }
  31439. }
  31440. setup( builder ) {
  31441. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  31442. builder.context.irradiance.addAssign( irradiance );
  31443. }
  31444. }
  31445. /**
  31446. * Base class for node parsers. A derived parser must be implemented
  31447. * for each supported native shader language.
  31448. */
  31449. class NodeParser {
  31450. /**
  31451. * The method parses the given native code an returns a node function.
  31452. *
  31453. * @abstract
  31454. * @param {String} source - The native shader code.
  31455. * @return {NodeFunction} A node function.
  31456. */
  31457. parseFunction( /*source*/ ) {
  31458. console.warn( 'Abstract function.' );
  31459. }
  31460. }
  31461. /**
  31462. * Base class for node functions. A derived module must be implemented
  31463. * for each supported native shader language. Similar to other `Node*` modules,
  31464. * this class is only relevant during the building process and not used
  31465. * in user-level code.
  31466. */
  31467. class NodeFunction {
  31468. /**
  31469. * Constructs a new node function.
  31470. *
  31471. * @param {String} type - The node type. This type is the return type of the node function.
  31472. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  31473. * @param {String} [name=''] - The function's name.
  31474. * @param {String} [precision=''] - The precision qualifier.
  31475. */
  31476. constructor( type, inputs, name = '', precision = '' ) {
  31477. /**
  31478. * The node type. This type is the return type of the node function.
  31479. *
  31480. * @type {String}
  31481. */
  31482. this.type = type;
  31483. /**
  31484. * The function's inputs.
  31485. *
  31486. * @type {Array<NodeFunctionInput>}
  31487. */
  31488. this.inputs = inputs;
  31489. /**
  31490. * The name of the uniform.
  31491. *
  31492. * @type {String}
  31493. * @default ''
  31494. */
  31495. this.name = name;
  31496. /**
  31497. * The precision qualifier.
  31498. *
  31499. * @type {String}
  31500. * @default ''
  31501. */
  31502. this.precision = precision;
  31503. }
  31504. /**
  31505. * This method returns the native code of the node function.
  31506. *
  31507. * @abstract
  31508. * @param {String} name - The function's name.
  31509. * @return {String} A shader code.
  31510. */
  31511. getCode( /*name = this.name*/ ) {
  31512. console.warn( 'Abstract function.' );
  31513. }
  31514. }
  31515. NodeFunction.isNodeFunction = true;
  31516. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  31517. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  31518. const pragmaMain = '#pragma main';
  31519. const parse$1 = ( source ) => {
  31520. source = source.trim();
  31521. const pragmaMainIndex = source.indexOf( pragmaMain );
  31522. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  31523. const declaration = mainCode.match( declarationRegexp$1 );
  31524. if ( declaration !== null && declaration.length === 5 ) {
  31525. // tokenizer
  31526. const inputsCode = declaration[ 4 ];
  31527. const propsMatches = [];
  31528. let nameMatch = null;
  31529. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  31530. propsMatches.push( nameMatch );
  31531. }
  31532. // parser
  31533. const inputs = [];
  31534. let i = 0;
  31535. while ( i < propsMatches.length ) {
  31536. const isConst = propsMatches[ i ][ 0 ] === 'const';
  31537. if ( isConst === true ) {
  31538. i ++;
  31539. }
  31540. let qualifier = propsMatches[ i ][ 0 ];
  31541. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  31542. i ++;
  31543. } else {
  31544. qualifier = '';
  31545. }
  31546. const type = propsMatches[ i ++ ][ 0 ];
  31547. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  31548. if ( Number.isNaN( count ) === false ) i ++;
  31549. else count = null;
  31550. const name = propsMatches[ i ++ ][ 0 ];
  31551. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  31552. }
  31553. //
  31554. const blockCode = mainCode.substring( declaration[ 0 ].length );
  31555. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  31556. const type = declaration[ 2 ];
  31557. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  31558. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  31559. return {
  31560. type,
  31561. inputs,
  31562. name,
  31563. precision,
  31564. inputsCode,
  31565. blockCode,
  31566. headerCode
  31567. };
  31568. } else {
  31569. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  31570. }
  31571. };
  31572. /**
  31573. * This class represents a GLSL node function.
  31574. *
  31575. * @augments NodeFunction
  31576. */
  31577. class GLSLNodeFunction extends NodeFunction {
  31578. /**
  31579. * Constructs a new GLSL node function.
  31580. *
  31581. * @param {String} source - The GLSL source.
  31582. */
  31583. constructor( source ) {
  31584. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  31585. super( type, inputs, name, precision );
  31586. this.inputsCode = inputsCode;
  31587. this.blockCode = blockCode;
  31588. this.headerCode = headerCode;
  31589. }
  31590. /**
  31591. * This method returns the GLSL code of the node function.
  31592. *
  31593. * @param {String} [name=this.name] - The function's name.
  31594. * @return {String} The shader code.
  31595. */
  31596. getCode( name = this.name ) {
  31597. let code;
  31598. const blockCode = this.blockCode;
  31599. if ( blockCode !== '' ) {
  31600. const { type, inputsCode, headerCode, precision } = this;
  31601. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  31602. if ( precision !== '' ) {
  31603. declarationCode = `${ precision } ${ declarationCode }`;
  31604. }
  31605. code = headerCode + declarationCode + blockCode;
  31606. } else {
  31607. // interface function
  31608. code = '';
  31609. }
  31610. return code;
  31611. }
  31612. }
  31613. /**
  31614. * A GLSL node parser.
  31615. *
  31616. * @augments NodeParser
  31617. */
  31618. class GLSLNodeParser extends NodeParser {
  31619. /**
  31620. * The method parses the given GLSL code an returns a node function.
  31621. *
  31622. * @param {String} source - The GLSL code.
  31623. * @return {GLSLNodeFunction} A node function.
  31624. */
  31625. parseFunction( source ) {
  31626. return new GLSLNodeFunction( source );
  31627. }
  31628. }
  31629. const _outputNodeMap = new WeakMap();
  31630. const _chainKeys$2 = [];
  31631. const _cacheKeyValues = [];
  31632. /**
  31633. * This renderer module manages node-related objects and is the
  31634. * primary interface between the renderer and the node system.
  31635. *
  31636. * @private
  31637. * @augments DataMap
  31638. */
  31639. class Nodes extends DataMap {
  31640. /**
  31641. * Constructs a new nodes management component.
  31642. *
  31643. * @param {Renderer} renderer - The renderer.
  31644. * @param {Backend} backend - The renderer's backend.
  31645. */
  31646. constructor( renderer, backend ) {
  31647. super();
  31648. /**
  31649. * The renderer.
  31650. *
  31651. * @type {Renderer}
  31652. */
  31653. this.renderer = renderer;
  31654. /**
  31655. * The renderer's backend.
  31656. *
  31657. * @type {Backend}
  31658. */
  31659. this.backend = backend;
  31660. /**
  31661. * The node frame.
  31662. *
  31663. * @type {Renderer}
  31664. */
  31665. this.nodeFrame = new NodeFrame();
  31666. /**
  31667. * A cache for managing node builder states.
  31668. *
  31669. * @type {Map<Number,NodeBuilderState>}
  31670. */
  31671. this.nodeBuilderCache = new Map();
  31672. /**
  31673. * A cache for managing data cache key data.
  31674. *
  31675. * @type {ChainMap}
  31676. */
  31677. this.callHashCache = new ChainMap();
  31678. /**
  31679. * A cache for managing node uniforms group data.
  31680. *
  31681. * @type {ChainMap}
  31682. */
  31683. this.groupsData = new ChainMap();
  31684. /**
  31685. * A cache for managing node objects of
  31686. * scene properties like fog or environments.
  31687. *
  31688. * @type {Object<String,WeakMap>}
  31689. */
  31690. this.cacheLib = {};
  31691. }
  31692. /**
  31693. * Returns `true` if the given node uniforms group must be updated or not.
  31694. *
  31695. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  31696. * @return {Boolean} Whether the node uniforms group requires an update or not.
  31697. */
  31698. updateGroup( nodeUniformsGroup ) {
  31699. const groupNode = nodeUniformsGroup.groupNode;
  31700. const name = groupNode.name;
  31701. // objectGroup is always updated
  31702. if ( name === objectGroup.name ) return true;
  31703. // renderGroup is updated once per render/compute call
  31704. if ( name === renderGroup.name ) {
  31705. const uniformsGroupData = this.get( nodeUniformsGroup );
  31706. const renderId = this.nodeFrame.renderId;
  31707. if ( uniformsGroupData.renderId !== renderId ) {
  31708. uniformsGroupData.renderId = renderId;
  31709. return true;
  31710. }
  31711. return false;
  31712. }
  31713. // frameGroup is updated once per frame
  31714. if ( name === frameGroup.name ) {
  31715. const uniformsGroupData = this.get( nodeUniformsGroup );
  31716. const frameId = this.nodeFrame.frameId;
  31717. if ( uniformsGroupData.frameId !== frameId ) {
  31718. uniformsGroupData.frameId = frameId;
  31719. return true;
  31720. }
  31721. return false;
  31722. }
  31723. // other groups are updated just when groupNode.needsUpdate is true
  31724. _chainKeys$2[ 0 ] = groupNode;
  31725. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  31726. let groupData = this.groupsData.get( _chainKeys$2 );
  31727. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  31728. _chainKeys$2.length = 0;
  31729. if ( groupData.version !== groupNode.version ) {
  31730. groupData.version = groupNode.version;
  31731. return true;
  31732. }
  31733. return false;
  31734. }
  31735. /**
  31736. * Returns the cache key for the given render object.
  31737. *
  31738. * @param {RenderObject} renderObject - The render object.
  31739. * @return {Number} The cache key.
  31740. */
  31741. getForRenderCacheKey( renderObject ) {
  31742. return renderObject.initialCacheKey;
  31743. }
  31744. /**
  31745. * Returns a node builder state for the given render object.
  31746. *
  31747. * @param {RenderObject} renderObject - The render object.
  31748. * @return {NodeBuilderState} The node builder state.
  31749. */
  31750. getForRender( renderObject ) {
  31751. const renderObjectData = this.get( renderObject );
  31752. let nodeBuilderState = renderObjectData.nodeBuilderState;
  31753. if ( nodeBuilderState === undefined ) {
  31754. const { nodeBuilderCache } = this;
  31755. const cacheKey = this.getForRenderCacheKey( renderObject );
  31756. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  31757. if ( nodeBuilderState === undefined ) {
  31758. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  31759. nodeBuilder.scene = renderObject.scene;
  31760. nodeBuilder.material = renderObject.material;
  31761. nodeBuilder.camera = renderObject.camera;
  31762. nodeBuilder.context.material = renderObject.material;
  31763. nodeBuilder.lightsNode = renderObject.lightsNode;
  31764. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  31765. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  31766. nodeBuilder.clippingContext = renderObject.clippingContext;
  31767. nodeBuilder.build();
  31768. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  31769. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  31770. }
  31771. nodeBuilderState.usedTimes ++;
  31772. renderObjectData.nodeBuilderState = nodeBuilderState;
  31773. }
  31774. return nodeBuilderState;
  31775. }
  31776. /**
  31777. * Deletes the given object from the internal data map
  31778. *
  31779. * @param {Any} object - The object to delete.
  31780. * @return {Object?} The deleted dictionary.
  31781. */
  31782. delete( object ) {
  31783. if ( object.isRenderObject ) {
  31784. const nodeBuilderState = this.get( object ).nodeBuilderState;
  31785. nodeBuilderState.usedTimes --;
  31786. if ( nodeBuilderState.usedTimes === 0 ) {
  31787. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  31788. }
  31789. }
  31790. return super.delete( object );
  31791. }
  31792. /**
  31793. * Returns a node builder state for the given compute node.
  31794. *
  31795. * @param {Node} computeNode - The compute node.
  31796. * @return {NodeBuilderState} The node builder state.
  31797. */
  31798. getForCompute( computeNode ) {
  31799. const computeData = this.get( computeNode );
  31800. let nodeBuilderState = computeData.nodeBuilderState;
  31801. if ( nodeBuilderState === undefined ) {
  31802. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  31803. nodeBuilder.build();
  31804. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  31805. computeData.nodeBuilderState = nodeBuilderState;
  31806. }
  31807. return nodeBuilderState;
  31808. }
  31809. /**
  31810. * Creates a node builder state for the given node builder.
  31811. *
  31812. * @private
  31813. * @param {NodeBuilder} nodeBuilder - The node builder.
  31814. * @return {NodeBuilderState} The node builder state.
  31815. */
  31816. _createNodeBuilderState( nodeBuilder ) {
  31817. return new NodeBuilderState(
  31818. nodeBuilder.vertexShader,
  31819. nodeBuilder.fragmentShader,
  31820. nodeBuilder.computeShader,
  31821. nodeBuilder.getAttributesArray(),
  31822. nodeBuilder.getBindings(),
  31823. nodeBuilder.updateNodes,
  31824. nodeBuilder.updateBeforeNodes,
  31825. nodeBuilder.updateAfterNodes,
  31826. nodeBuilder.monitor,
  31827. nodeBuilder.transforms
  31828. );
  31829. }
  31830. /**
  31831. * Returns an environment node for the current configured
  31832. * scene environment.
  31833. *
  31834. * @param {Scene} scene - The scene.
  31835. * @return {Node} A node representing the current scene environment.
  31836. */
  31837. getEnvironmentNode( scene ) {
  31838. this.updateEnvironment( scene );
  31839. let environmentNode = null;
  31840. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  31841. environmentNode = scene.environmentNode;
  31842. } else {
  31843. const sceneData = this.get( scene );
  31844. if ( sceneData.environmentNode ) {
  31845. environmentNode = sceneData.environmentNode;
  31846. }
  31847. }
  31848. return environmentNode;
  31849. }
  31850. /**
  31851. * Returns a background node for the current configured
  31852. * scene background.
  31853. *
  31854. * @param {Scene} scene - The scene.
  31855. * @return {Node} A node representing the current scene background.
  31856. */
  31857. getBackgroundNode( scene ) {
  31858. this.updateBackground( scene );
  31859. let backgroundNode = null;
  31860. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  31861. backgroundNode = scene.backgroundNode;
  31862. } else {
  31863. const sceneData = this.get( scene );
  31864. if ( sceneData.backgroundNode ) {
  31865. backgroundNode = sceneData.backgroundNode;
  31866. }
  31867. }
  31868. return backgroundNode;
  31869. }
  31870. /**
  31871. * Returns a fog node for the current configured scene fog.
  31872. *
  31873. * @param {Scene} scene - The scene.
  31874. * @return {Node} A node representing the current scene fog.
  31875. */
  31876. getFogNode( scene ) {
  31877. this.updateFog( scene );
  31878. return scene.fogNode || this.get( scene ).fogNode || null;
  31879. }
  31880. /**
  31881. * Returns a cache key for the given scene and lights node.
  31882. * This key is used by `RenderObject` as a part of the dynamic
  31883. * cache key (a key that must be checked every time the render
  31884. * objects is drawn).
  31885. *
  31886. * @param {Scene} scene - The scene.
  31887. * @param {LightsNode} lightsNode - The lights node.
  31888. * @return {Number} The cache key.
  31889. */
  31890. getCacheKey( scene, lightsNode ) {
  31891. _chainKeys$2[ 0 ] = scene;
  31892. _chainKeys$2[ 1 ] = lightsNode;
  31893. const callId = this.renderer.info.calls;
  31894. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  31895. if ( cacheKeyData.callId !== callId ) {
  31896. const environmentNode = this.getEnvironmentNode( scene );
  31897. const fogNode = this.getFogNode( scene );
  31898. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  31899. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  31900. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  31901. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  31902. cacheKeyData.callId = callId;
  31903. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  31904. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  31905. _cacheKeyValues.length = 0;
  31906. }
  31907. _chainKeys$2.length = 0;
  31908. return cacheKeyData.cacheKey;
  31909. }
  31910. /**
  31911. * A boolean that indicates whether tone mapping should be enabled
  31912. * or not.
  31913. *
  31914. * @type {Boolean}
  31915. */
  31916. get isToneMappingState() {
  31917. return this.renderer.getRenderTarget() ? false : true;
  31918. }
  31919. /**
  31920. * If a scene background is configured, this method makes sure to
  31921. * represent the background with a corresponding node-based implementation.
  31922. *
  31923. * @param {Scene} scene - The scene.
  31924. */
  31925. updateBackground( scene ) {
  31926. const sceneData = this.get( scene );
  31927. const background = scene.background;
  31928. if ( background ) {
  31929. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  31930. if ( sceneData.background !== background || forceUpdate ) {
  31931. const backgroundNode = this.getCacheNode( 'background', background, () => {
  31932. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  31933. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  31934. return pmremTexture( background );
  31935. } else {
  31936. let envMap;
  31937. if ( background.isCubeTexture === true ) {
  31938. envMap = cubeTexture( background );
  31939. } else {
  31940. envMap = texture( background );
  31941. }
  31942. return cubeMapNode( envMap );
  31943. }
  31944. } else if ( background.isTexture === true ) {
  31945. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  31946. } else if ( background.isColor !== true ) {
  31947. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  31948. }
  31949. }, forceUpdate );
  31950. sceneData.backgroundNode = backgroundNode;
  31951. sceneData.background = background;
  31952. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  31953. }
  31954. } else if ( sceneData.backgroundNode ) {
  31955. delete sceneData.backgroundNode;
  31956. delete sceneData.background;
  31957. }
  31958. }
  31959. /**
  31960. * This method is part of the caching of nodes which are used to represents the
  31961. * scene's background, fog or environment.
  31962. *
  31963. * @param {String} type - The type of object to cache.
  31964. * @param {Object} object - The object.
  31965. * @param {Function} callback - A callback that produces a node representation for the given object.
  31966. * @param {Boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  31967. * @return {Node} The node representation.
  31968. */
  31969. getCacheNode( type, object, callback, forceUpdate = false ) {
  31970. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  31971. let node = nodeCache.get( object );
  31972. if ( node === undefined || forceUpdate ) {
  31973. node = callback();
  31974. nodeCache.set( object, node );
  31975. }
  31976. return node;
  31977. }
  31978. /**
  31979. * If a scene fog is configured, this method makes sure to
  31980. * represent the fog with a corresponding node-based implementation.
  31981. *
  31982. * @param {Scene} scene - The scene.
  31983. */
  31984. updateFog( scene ) {
  31985. const sceneData = this.get( scene );
  31986. const sceneFog = scene.fog;
  31987. if ( sceneFog ) {
  31988. if ( sceneData.fog !== sceneFog ) {
  31989. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  31990. if ( sceneFog.isFogExp2 ) {
  31991. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  31992. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  31993. return fog( color, densityFogFactor( density ) );
  31994. } else if ( sceneFog.isFog ) {
  31995. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  31996. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  31997. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  31998. return fog( color, rangeFogFactor( near, far ) );
  31999. } else {
  32000. console.error( 'THREE.Renderer: Unsupported fog configuration.', sceneFog );
  32001. }
  32002. } );
  32003. sceneData.fogNode = fogNode;
  32004. sceneData.fog = sceneFog;
  32005. }
  32006. } else {
  32007. delete sceneData.fogNode;
  32008. delete sceneData.fog;
  32009. }
  32010. }
  32011. /**
  32012. * If a scene environment is configured, this method makes sure to
  32013. * represent the environment with a corresponding node-based implementation.
  32014. *
  32015. * @param {Scene} scene - The scene.
  32016. */
  32017. updateEnvironment( scene ) {
  32018. const sceneData = this.get( scene );
  32019. const environment = scene.environment;
  32020. if ( environment ) {
  32021. if ( sceneData.environment !== environment ) {
  32022. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  32023. if ( environment.isCubeTexture === true ) {
  32024. return cubeTexture( environment );
  32025. } else if ( environment.isTexture === true ) {
  32026. return texture( environment );
  32027. } else {
  32028. console.error( 'Nodes: Unsupported environment configuration.', environment );
  32029. }
  32030. } );
  32031. sceneData.environmentNode = environmentNode;
  32032. sceneData.environment = environment;
  32033. }
  32034. } else if ( sceneData.environmentNode ) {
  32035. delete sceneData.environmentNode;
  32036. delete sceneData.environment;
  32037. }
  32038. }
  32039. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  32040. const nodeFrame = this.nodeFrame;
  32041. nodeFrame.renderer = renderer;
  32042. nodeFrame.scene = scene;
  32043. nodeFrame.object = object;
  32044. nodeFrame.camera = camera;
  32045. nodeFrame.material = material;
  32046. return nodeFrame;
  32047. }
  32048. getNodeFrameForRender( renderObject ) {
  32049. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  32050. }
  32051. /**
  32052. * Returns the current output cache key.
  32053. *
  32054. * @return {String} The output cache key.
  32055. */
  32056. getOutputCacheKey() {
  32057. const renderer = this.renderer;
  32058. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  32059. }
  32060. /**
  32061. * Checks if the output configuration (tone mapping and color space) for
  32062. * the given target has changed.
  32063. *
  32064. * @param {Texture} outputTarget - The output target.
  32065. * @return {Boolean} Whether the output configuration has changed or not.
  32066. */
  32067. hasOutputChange( outputTarget ) {
  32068. const cacheKey = _outputNodeMap.get( outputTarget );
  32069. return cacheKey !== this.getOutputCacheKey();
  32070. }
  32071. /**
  32072. * Returns a node that represents the output configuration (tone mapping and
  32073. * color space) for the current target.
  32074. *
  32075. * @param {Texture} outputTarget - The output target.
  32076. * @return {Node} The output node.
  32077. */
  32078. getOutputNode( outputTarget ) {
  32079. const renderer = this.renderer;
  32080. const cacheKey = this.getOutputCacheKey();
  32081. const output = texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  32082. _outputNodeMap.set( outputTarget, cacheKey );
  32083. return output;
  32084. }
  32085. /**
  32086. * Triggers the call of `updateBefore()` methods
  32087. * for all nodes of the given render object.
  32088. *
  32089. * @param {RenderObject} renderObject - The render object.
  32090. */
  32091. updateBefore( renderObject ) {
  32092. const nodeBuilder = renderObject.getNodeBuilderState();
  32093. for ( const node of nodeBuilder.updateBeforeNodes ) {
  32094. // update frame state for each node
  32095. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  32096. }
  32097. }
  32098. /**
  32099. * Triggers the call of `updateAfter()` methods
  32100. * for all nodes of the given render object.
  32101. *
  32102. * @param {RenderObject} renderObject - The render object.
  32103. */
  32104. updateAfter( renderObject ) {
  32105. const nodeBuilder = renderObject.getNodeBuilderState();
  32106. for ( const node of nodeBuilder.updateAfterNodes ) {
  32107. // update frame state for each node
  32108. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  32109. }
  32110. }
  32111. /**
  32112. * Triggers the call of `update()` methods
  32113. * for all nodes of the given compute node.
  32114. *
  32115. * @param {Node} computeNode - The compute node.
  32116. */
  32117. updateForCompute( computeNode ) {
  32118. const nodeFrame = this.getNodeFrame();
  32119. const nodeBuilder = this.getForCompute( computeNode );
  32120. for ( const node of nodeBuilder.updateNodes ) {
  32121. nodeFrame.updateNode( node );
  32122. }
  32123. }
  32124. /**
  32125. * Triggers the call of `update()` methods
  32126. * for all nodes of the given compute node.
  32127. *
  32128. * @param {RenderObject} renderObject - The render object.
  32129. */
  32130. updateForRender( renderObject ) {
  32131. const nodeFrame = this.getNodeFrameForRender( renderObject );
  32132. const nodeBuilder = renderObject.getNodeBuilderState();
  32133. for ( const node of nodeBuilder.updateNodes ) {
  32134. nodeFrame.updateNode( node );
  32135. }
  32136. }
  32137. /**
  32138. * Returns `true` if the given render object requires a refresh.
  32139. *
  32140. * @param {RenderObject} renderObject - The render object.
  32141. * @return {Boolean} Whether the given render object requires a refresh or not.
  32142. */
  32143. needsRefresh( renderObject ) {
  32144. const nodeFrame = this.getNodeFrameForRender( renderObject );
  32145. const monitor = renderObject.getMonitor();
  32146. return monitor.needsRefresh( renderObject, nodeFrame );
  32147. }
  32148. /**
  32149. * Frees the internal resources.
  32150. */
  32151. dispose() {
  32152. super.dispose();
  32153. this.nodeFrame = new NodeFrame();
  32154. this.nodeBuilderCache = new Map();
  32155. this.cacheLib = {};
  32156. }
  32157. }
  32158. const _plane = /*@__PURE__*/ new Plane();
  32159. /**
  32160. * Represents the state that is used to perform clipping via clipping planes.
  32161. * There is a default clipping context for each render context. When the
  32162. * scene holds instances of `ClippingGroup`, there will be a context for each
  32163. * group.
  32164. *
  32165. * @private
  32166. */
  32167. class ClippingContext {
  32168. /**
  32169. * Constructs a new clipping context.
  32170. *
  32171. * @param {ClippingContext?} [parentContext=null] - A reference to the parent clipping context.
  32172. */
  32173. constructor( parentContext = null ) {
  32174. /**
  32175. * The clipping context's version.
  32176. *
  32177. * @type {Number}
  32178. * @readonly
  32179. */
  32180. this.version = 0;
  32181. /**
  32182. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  32183. *
  32184. * @type {Boolean?}
  32185. * @default null
  32186. */
  32187. this.clipIntersection = null;
  32188. /**
  32189. * The clipping context's cache key.
  32190. *
  32191. * @type {String}
  32192. */
  32193. this.cacheKey = '';
  32194. /**
  32195. * Whether the shadow pass is active or not.
  32196. *
  32197. * @type {Boolean}
  32198. * @default false
  32199. */
  32200. this.shadowPass = false;
  32201. /**
  32202. * The view normal matrix.
  32203. *
  32204. * @type {Matrix3}
  32205. */
  32206. this.viewNormalMatrix = new Matrix3();
  32207. /**
  32208. * Internal cache for maintaining clipping contexts.
  32209. *
  32210. * @type {WeakMap<ClippingGroup,ClippingContext>}
  32211. */
  32212. this.clippingGroupContexts = new WeakMap();
  32213. /**
  32214. * The intersection planes.
  32215. *
  32216. * @type {Array<Vector4>}
  32217. */
  32218. this.intersectionPlanes = [];
  32219. /**
  32220. * The intersection planes.
  32221. *
  32222. * @type {Array<Vector4>}
  32223. */
  32224. this.unionPlanes = [];
  32225. /**
  32226. * The version of the clipping context's parent context.
  32227. *
  32228. * @type {Number?}
  32229. * @readonly
  32230. */
  32231. this.parentVersion = null;
  32232. if ( parentContext !== null ) {
  32233. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  32234. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  32235. this.shadowPass = parentContext.shadowPass;
  32236. this.viewMatrix = parentContext.viewMatrix;
  32237. }
  32238. }
  32239. /**
  32240. * Projects the given source clipping planes and writes the result into the
  32241. * destination array.
  32242. *
  32243. * @param {Array<Plane>} source - The source clipping planes.
  32244. * @param {Array<Vector4>} destination - The destination.
  32245. * @param {Number} offset - The offset.
  32246. */
  32247. projectPlanes( source, destination, offset ) {
  32248. const l = source.length;
  32249. for ( let i = 0; i < l; i ++ ) {
  32250. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  32251. const v = destination[ offset + i ];
  32252. const normal = _plane.normal;
  32253. v.x = - normal.x;
  32254. v.y = - normal.y;
  32255. v.z = - normal.z;
  32256. v.w = _plane.constant;
  32257. }
  32258. }
  32259. /**
  32260. * Updates the root clipping context of a scene.
  32261. *
  32262. * @param {Scene} scene - The scene.
  32263. * @param {Camera} camera - The camera that is used to render the scene.
  32264. */
  32265. updateGlobal( scene, camera ) {
  32266. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowNodeMaterial );
  32267. this.viewMatrix = camera.matrixWorldInverse;
  32268. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  32269. }
  32270. /**
  32271. * Updates the clipping context.
  32272. *
  32273. * @param {ClippingContext} parentContext - The parent context.
  32274. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  32275. */
  32276. update( parentContext, clippingGroup ) {
  32277. let update = false;
  32278. if ( parentContext.version !== this.parentVersion ) {
  32279. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  32280. this.unionPlanes = Array.from( parentContext.unionPlanes );
  32281. this.parentVersion = parentContext.version;
  32282. }
  32283. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  32284. this.clipIntersection = clippingGroup.clipIntersection;
  32285. if ( this.clipIntersection ) {
  32286. this.unionPlanes.length = parentContext.unionPlanes.length;
  32287. } else {
  32288. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  32289. }
  32290. }
  32291. const srcClippingPlanes = clippingGroup.clippingPlanes;
  32292. const l = srcClippingPlanes.length;
  32293. let dstClippingPlanes;
  32294. let offset;
  32295. if ( this.clipIntersection ) {
  32296. dstClippingPlanes = this.intersectionPlanes;
  32297. offset = parentContext.intersectionPlanes.length;
  32298. } else {
  32299. dstClippingPlanes = this.unionPlanes;
  32300. offset = parentContext.unionPlanes.length;
  32301. }
  32302. if ( dstClippingPlanes.length !== offset + l ) {
  32303. dstClippingPlanes.length = offset + l;
  32304. for ( let i = 0; i < l; i ++ ) {
  32305. dstClippingPlanes[ offset + i ] = new Vector4();
  32306. }
  32307. update = true;
  32308. }
  32309. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  32310. if ( update ) {
  32311. this.version ++;
  32312. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  32313. }
  32314. }
  32315. /**
  32316. * Returns a clipping context for the given clipping group.
  32317. *
  32318. * @param {ClippingGroup} clippingGroup - The clipping group.
  32319. * @return {ClippingContext} The clipping context.
  32320. */
  32321. getGroupContext( clippingGroup ) {
  32322. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  32323. let context = this.clippingGroupContexts.get( clippingGroup );
  32324. if ( context === undefined ) {
  32325. context = new ClippingContext( this );
  32326. this.clippingGroupContexts.set( clippingGroup, context );
  32327. }
  32328. context.update( this, clippingGroup );
  32329. return context;
  32330. }
  32331. /**
  32332. * The count of union clipping planes.
  32333. *
  32334. * @type {Number}
  32335. * @readonly
  32336. */
  32337. get unionClippingCount() {
  32338. return this.unionPlanes.length;
  32339. }
  32340. }
  32341. /**
  32342. * This module is used to represent render bundles inside the renderer
  32343. * for further processing.
  32344. *
  32345. * @private
  32346. */
  32347. class RenderBundle {
  32348. /**
  32349. * Constructs a new bundle group.
  32350. *
  32351. * @param {BundleGroup} bundleGroup - The bundle group.
  32352. * @param {Camera} camera - The camera the bundle group is rendered with.
  32353. */
  32354. constructor( bundleGroup, camera ) {
  32355. this.bundleGroup = bundleGroup;
  32356. this.camera = camera;
  32357. }
  32358. }
  32359. const _chainKeys$1 = [];
  32360. /**
  32361. * This renderer module manages render bundles.
  32362. *
  32363. * @private
  32364. */
  32365. class RenderBundles {
  32366. /**
  32367. * Constructs a new render bundle management component.
  32368. */
  32369. constructor() {
  32370. /**
  32371. * A chain map for maintaining the render bundles.
  32372. *
  32373. * @type {ChainMap}
  32374. */
  32375. this.bundles = new ChainMap();
  32376. }
  32377. /**
  32378. * Returns a render bundle for the given bundle group and camera.
  32379. *
  32380. * @param {BundleGroup} bundleGroup - The bundle group.
  32381. * @param {Camera} camera - The camera the bundle group is rendered with.
  32382. * @return {RenderBundle} The render bundle.
  32383. */
  32384. get( bundleGroup, camera ) {
  32385. const bundles = this.bundles;
  32386. _chainKeys$1[ 0 ] = bundleGroup;
  32387. _chainKeys$1[ 1 ] = camera;
  32388. let bundle = bundles.get( _chainKeys$1 );
  32389. if ( bundle === undefined ) {
  32390. bundle = new RenderBundle( bundleGroup, camera );
  32391. bundles.set( _chainKeys$1, bundle );
  32392. }
  32393. _chainKeys$1.length = 0;
  32394. return bundle;
  32395. }
  32396. /**
  32397. * Frees all internal resources.
  32398. */
  32399. dispose() {
  32400. this.bundles = new ChainMap();
  32401. }
  32402. }
  32403. /**
  32404. * The purpose of a node library is to assign node implementations
  32405. * to existing library features. In `WebGPURenderer` lights, materials
  32406. * which are not based on `NodeMaterial` as well as tone mapping techniques
  32407. * are implemented with node-based modules.
  32408. *
  32409. * @private
  32410. */
  32411. class NodeLibrary {
  32412. /**
  32413. * Constructs a new node library.
  32414. */
  32415. constructor() {
  32416. /**
  32417. * A weak map that maps lights to light nodes.
  32418. *
  32419. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  32420. */
  32421. this.lightNodes = new WeakMap();
  32422. /**
  32423. * A map that maps materials to node materials.
  32424. *
  32425. * @type {WeakMap<String,NodeMaterial.constructor>}
  32426. */
  32427. this.materialNodes = new Map();
  32428. /**
  32429. * A map that maps tone mapping techniques (constants)
  32430. * to tone mapping node functions.
  32431. *
  32432. * @type {WeakMap<Number,Function>}
  32433. */
  32434. this.toneMappingNodes = new Map();
  32435. }
  32436. /**
  32437. * Returns a matching node material instance for the given material object.
  32438. *
  32439. * This method also assigns/copies the properties of the given material object
  32440. * to the node material. This is done to make sure the current material
  32441. * configuration carries over to the node version.
  32442. *
  32443. * @param {Material} material - A material.
  32444. * @return {NodeMaterial} The corresponding node material.
  32445. */
  32446. fromMaterial( material ) {
  32447. if ( material.isNodeMaterial ) return material;
  32448. let nodeMaterial = null;
  32449. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  32450. if ( nodeMaterialClass !== null ) {
  32451. nodeMaterial = new nodeMaterialClass();
  32452. for ( const key in material ) {
  32453. nodeMaterial[ key ] = material[ key ];
  32454. }
  32455. }
  32456. return nodeMaterial;
  32457. }
  32458. /**
  32459. * Adds a tone mapping node function for a tone mapping technique (constant).
  32460. *
  32461. * @param {Function} toneMappingNode - The tone mapping node function.
  32462. * @param {Number} toneMapping - The tone mapping.
  32463. */
  32464. addToneMapping( toneMappingNode, toneMapping ) {
  32465. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  32466. }
  32467. /**
  32468. * Returns a tone mapping node function for a tone mapping technique (constant).
  32469. *
  32470. * @param {Number} toneMapping - The tone mapping.
  32471. * @return {Function?} The tone mapping node function. Returns `null` if no node function is found.
  32472. */
  32473. getToneMappingFunction( toneMapping ) {
  32474. return this.toneMappingNodes.get( toneMapping ) || null;
  32475. }
  32476. /**
  32477. * Returns a node material class definition for a material type.
  32478. *
  32479. * @param {String} materialType - The material type.
  32480. * @return {NodeMaterial.constructor?} The node material class definition. Returns `null` if no node material is found.
  32481. */
  32482. getMaterialNodeClass( materialType ) {
  32483. return this.materialNodes.get( materialType ) || null;
  32484. }
  32485. /**
  32486. * Adds a node material class definition for a given material type.
  32487. *
  32488. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  32489. * @param {String} materialClassType - The material type.
  32490. */
  32491. addMaterial( materialNodeClass, materialClassType ) {
  32492. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  32493. }
  32494. /**
  32495. * Returns a light node class definition for a light class definition.
  32496. *
  32497. * @param {Light.constructor} light - The light class definition.
  32498. * @return {AnalyticLightNode.constructor?} The light node class definition. Returns `null` if no light node is found.
  32499. */
  32500. getLightNodeClass( light ) {
  32501. return this.lightNodes.get( light ) || null;
  32502. }
  32503. /**
  32504. * Adds a light node class definition for a given light class definition.
  32505. *
  32506. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  32507. * @param {Light.constructor} lightClass - The light class definition.
  32508. */
  32509. addLight( lightNodeClass, lightClass ) {
  32510. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  32511. }
  32512. /**
  32513. * Adds a node class definition for the given type to the provided type library.
  32514. *
  32515. * @param {Any} nodeClass - The node class definition.
  32516. * @param {String} type - The object type.
  32517. * @param {Map} library - The type library.
  32518. */
  32519. addType( nodeClass, type, library ) {
  32520. if ( library.has( type ) ) {
  32521. console.warn( `Redefinition of node ${ type }` );
  32522. return;
  32523. }
  32524. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  32525. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  32526. library.set( type, nodeClass );
  32527. }
  32528. /**
  32529. * Adds a node class definition for the given class definition to the provided type library.
  32530. *
  32531. * @param {Any} nodeClass - The node class definition.
  32532. * @param {Any} baseClass - The class definition.
  32533. * @param {WeakMap} library - The type library.
  32534. */
  32535. addClass( nodeClass, baseClass, library ) {
  32536. if ( library.has( baseClass ) ) {
  32537. console.warn( `Redefinition of node ${ baseClass.name }` );
  32538. return;
  32539. }
  32540. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  32541. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  32542. library.set( baseClass, nodeClass );
  32543. }
  32544. }
  32545. const _defaultLights = /*@__PURE__*/ new LightsNode();
  32546. const _chainKeys = [];
  32547. /**
  32548. * This renderer module manages the lights nodes which are unique
  32549. * per scene and camera combination.
  32550. *
  32551. * The lights node itself is later configured in the render list
  32552. * with the actual lights from the scene.
  32553. *
  32554. * @private
  32555. * @augments ChainMap
  32556. */
  32557. class Lighting extends ChainMap {
  32558. /**
  32559. * Constructs a lighting management component.
  32560. */
  32561. constructor() {
  32562. super();
  32563. }
  32564. /**
  32565. * Creates a new lights node for the given array of lights.
  32566. *
  32567. * @param {Array<Light>} lights - The render object.
  32568. * @return {Boolean} Whether if the given render object has an initialized geometry or not.
  32569. */
  32570. createNode( lights = [] ) {
  32571. return new LightsNode().setLights( lights );
  32572. }
  32573. /**
  32574. * Returns a lights node for the given scene and camera.
  32575. *
  32576. * @param {Scene} scene - The scene.
  32577. * @param {Camera} camera - The camera.
  32578. * @return {LightsNode} The lights node.
  32579. */
  32580. getNode( scene, camera ) {
  32581. // ignore post-processing
  32582. if ( scene.isQuadMesh ) return _defaultLights;
  32583. _chainKeys[ 0 ] = scene;
  32584. _chainKeys[ 1 ] = camera;
  32585. let node = this.get( _chainKeys );
  32586. if ( node === undefined ) {
  32587. node = this.createNode();
  32588. this.set( _chainKeys, node );
  32589. }
  32590. _chainKeys.length = 0;
  32591. return node;
  32592. }
  32593. }
  32594. /** @module Renderer **/
  32595. const _scene = /*@__PURE__*/ new Scene();
  32596. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  32597. const _screen = /*@__PURE__*/ new Vector4();
  32598. const _frustum = /*@__PURE__*/ new Frustum();
  32599. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  32600. const _vector4 = /*@__PURE__*/ new Vector4();
  32601. /**
  32602. * Base class for renderers.
  32603. */
  32604. class Renderer {
  32605. /**
  32606. * Constructs a new renderer.
  32607. *
  32608. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  32609. * @param {Object} parameters - The configuration parameter.
  32610. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  32611. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  32612. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  32613. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  32614. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  32615. * @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
  32616. * to overwrite the default.
  32617. * @param {Function?} [parameters.getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  32618. */
  32619. constructor( backend, parameters = {} ) {
  32620. /**
  32621. * This flag can be used for type testing.
  32622. *
  32623. * @type {Boolean}
  32624. * @readonly
  32625. * @default true
  32626. */
  32627. this.isRenderer = true;
  32628. //
  32629. const {
  32630. logarithmicDepthBuffer = false,
  32631. alpha = true,
  32632. depth = true,
  32633. stencil = false,
  32634. antialias = false,
  32635. samples = 0,
  32636. getFallback = null
  32637. } = parameters;
  32638. /**
  32639. * A reference to the canvas element the renderer is drawing to.
  32640. * This value of this property will automatically be created by
  32641. * the renderer.
  32642. *
  32643. * @type {HTMLCanvasElement|OffscreenCanvas}
  32644. */
  32645. this.domElement = backend.getDomElement();
  32646. /**
  32647. * A reference to the current backend.
  32648. *
  32649. * @type {Backend}
  32650. */
  32651. this.backend = backend;
  32652. /**
  32653. * The number of MSAA samples.
  32654. *
  32655. * @type {Number}
  32656. * @default 0
  32657. */
  32658. this.samples = samples || ( antialias === true ) ? 4 : 0;
  32659. /**
  32660. * Whether the renderer should automatically clear the current rendering target
  32661. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  32662. * or the current bound render target (custom framebuffer).
  32663. *
  32664. * @type {Boolean}
  32665. * @default true
  32666. */
  32667. this.autoClear = true;
  32668. /**
  32669. * When `autoClear` is set to `true`, this property defines whether the renderer
  32670. * should clear the color buffer.
  32671. *
  32672. * @type {Boolean}
  32673. * @default true
  32674. */
  32675. this.autoClearColor = true;
  32676. /**
  32677. * When `autoClear` is set to `true`, this property defines whether the renderer
  32678. * should clear the depth buffer.
  32679. *
  32680. * @type {Boolean}
  32681. * @default true
  32682. */
  32683. this.autoClearDepth = true;
  32684. /**
  32685. * When `autoClear` is set to `true`, this property defines whether the renderer
  32686. * should clear the stencil buffer.
  32687. *
  32688. * @type {Boolean}
  32689. * @default true
  32690. */
  32691. this.autoClearStencil = true;
  32692. /**
  32693. * Whether the default framebuffer should be transparent or opaque.
  32694. *
  32695. * @type {Boolean}
  32696. * @default true
  32697. */
  32698. this.alpha = alpha;
  32699. /**
  32700. * Whether logarithmic depth buffer is enabled or not.
  32701. *
  32702. * @type {Boolean}
  32703. * @default false
  32704. */
  32705. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  32706. /**
  32707. * Defines the output color space of the renderer.
  32708. *
  32709. * @type {String}
  32710. * @default SRGBColorSpace
  32711. */
  32712. this.outputColorSpace = SRGBColorSpace;
  32713. /**
  32714. * Defines the tone mapping of the renderer.
  32715. *
  32716. * @type {Number}
  32717. * @default NoToneMapping
  32718. */
  32719. this.toneMapping = NoToneMapping;
  32720. /**
  32721. * Defines the tone mapping exposure.
  32722. *
  32723. * @type {Number}
  32724. * @default 1
  32725. */
  32726. this.toneMappingExposure = 1.0;
  32727. /**
  32728. * Whether the renderer should sort its render lists or not.
  32729. *
  32730. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  32731. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  32732. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  32733. * e.g. manually determining each object's rendering order.
  32734. *
  32735. * @type {Boolean}
  32736. * @default true
  32737. */
  32738. this.sortObjects = true;
  32739. /**
  32740. * Whether the default framebuffer should have a depth buffer or not.
  32741. *
  32742. * @type {Boolean}
  32743. * @default true
  32744. */
  32745. this.depth = depth;
  32746. /**
  32747. * Whether the default framebuffer should have a stencil buffer or not.
  32748. *
  32749. * @type {Boolean}
  32750. * @default false
  32751. */
  32752. this.stencil = stencil;
  32753. /**
  32754. * Holds a series of statistical information about the GPU memory
  32755. * and the rendering process. Useful for debugging and monitoring.
  32756. *
  32757. * @type {Boolean}
  32758. */
  32759. this.info = new Info();
  32760. this.nodes = {
  32761. modelViewMatrix: null,
  32762. modelNormalViewMatrix: null
  32763. };
  32764. /**
  32765. * The node library defines how certain library objects like materials, lights
  32766. * or tone mapping functions are mapped to node types. This is required since
  32767. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  32768. * be part of the scene graph, they are internally represented as nodes for
  32769. * further processing.
  32770. *
  32771. * @type {NodeLibrary}
  32772. */
  32773. this.library = new NodeLibrary();
  32774. /**
  32775. * A map-like data structure for managing lights.
  32776. *
  32777. * @type {Lighting}
  32778. */
  32779. this.lighting = new Lighting();
  32780. // internals
  32781. /**
  32782. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  32783. *
  32784. * @private
  32785. * @type {Function}
  32786. */
  32787. this._getFallback = getFallback;
  32788. /**
  32789. * The renderer's pixel ration.
  32790. *
  32791. * @private
  32792. * @type {Number}
  32793. * @default 1
  32794. */
  32795. this._pixelRatio = 1;
  32796. /**
  32797. * The width of the renderer's default framebuffer in logical pixel unit.
  32798. *
  32799. * @private
  32800. * @type {Number}
  32801. */
  32802. this._width = this.domElement.width;
  32803. /**
  32804. * The height of the renderer's default framebuffer in logical pixel unit.
  32805. *
  32806. * @private
  32807. * @type {Number}
  32808. */
  32809. this._height = this.domElement.height;
  32810. /**
  32811. * The viewport of the renderer in logical pixel unit.
  32812. *
  32813. * @private
  32814. * @type {Vector4}
  32815. */
  32816. this._viewport = new Vector4( 0, 0, this._width, this._height );
  32817. /**
  32818. * The scissor rectangle of the renderer in logical pixel unit.
  32819. *
  32820. * @private
  32821. * @type {Vector4}
  32822. */
  32823. this._scissor = new Vector4( 0, 0, this._width, this._height );
  32824. /**
  32825. * Whether the scissor test should be enabled or not.
  32826. *
  32827. * @private
  32828. * @type {Vector4}
  32829. */
  32830. this._scissorTest = false;
  32831. /**
  32832. * A reference to a renderer module for managing shader attributes.
  32833. *
  32834. * @private
  32835. * @type {Attributes?}
  32836. * @default null
  32837. */
  32838. this._attributes = null;
  32839. /**
  32840. * A reference to a renderer module for managing geometries.
  32841. *
  32842. * @private
  32843. * @type {Geometries?}
  32844. * @default null
  32845. */
  32846. this._geometries = null;
  32847. /**
  32848. * A reference to a renderer module for managing node related logic.
  32849. *
  32850. * @private
  32851. * @type {Nodes?}
  32852. * @default null
  32853. */
  32854. this._nodes = null;
  32855. /**
  32856. * A reference to a renderer module for managing the internal animation loop.
  32857. *
  32858. * @private
  32859. * @type {Animation?}
  32860. * @default null
  32861. */
  32862. this._animation = null;
  32863. /**
  32864. * A reference to a renderer module for managing shader program bindings.
  32865. *
  32866. * @private
  32867. * @type {Bindings?}
  32868. * @default null
  32869. */
  32870. this._bindings = null;
  32871. /**
  32872. * A reference to a renderer module for managing render objects.
  32873. *
  32874. * @private
  32875. * @type {RenderObjects?}
  32876. * @default null
  32877. */
  32878. this._objects = null;
  32879. /**
  32880. * A reference to a renderer module for managing render and compute pipelines.
  32881. *
  32882. * @private
  32883. * @type {Pipelines?}
  32884. * @default null
  32885. */
  32886. this._pipelines = null;
  32887. /**
  32888. * A reference to a renderer module for managing render bundles.
  32889. *
  32890. * @private
  32891. * @type {RenderBundles?}
  32892. * @default null
  32893. */
  32894. this._bundles = null;
  32895. /**
  32896. * A reference to a renderer module for managing render lists.
  32897. *
  32898. * @private
  32899. * @type {RenderLists?}
  32900. * @default null
  32901. */
  32902. this._renderLists = null;
  32903. /**
  32904. * A reference to a renderer module for managing render contexts.
  32905. *
  32906. * @private
  32907. * @type {RenderContexts?}
  32908. * @default null
  32909. */
  32910. this._renderContexts = null;
  32911. /**
  32912. * A reference to a renderer module for managing textures.
  32913. *
  32914. * @private
  32915. * @type {Textures?}
  32916. * @default null
  32917. */
  32918. this._textures = null;
  32919. /**
  32920. * A reference to a renderer module for backgrounds.
  32921. *
  32922. * @private
  32923. * @type {Background?}
  32924. * @default null
  32925. */
  32926. this._background = null;
  32927. /**
  32928. * This fullscreen quad is used for internal render passes
  32929. * like the tone mapping and color space output pass.
  32930. *
  32931. * @private
  32932. * @type {QuadMesh}
  32933. */
  32934. this._quad = new QuadMesh( new NodeMaterial() );
  32935. this._quad.material.name = 'Renderer_output';
  32936. /**
  32937. * A reference to the current render context.
  32938. *
  32939. * @private
  32940. * @type {RenderContext?}
  32941. * @default null
  32942. */
  32943. this._currentRenderContext = null;
  32944. /**
  32945. * A custom sort function for the opaque render list.
  32946. *
  32947. * @private
  32948. * @type {Function?}
  32949. * @default null
  32950. */
  32951. this._opaqueSort = null;
  32952. /**
  32953. * A custom sort function for the transparent render list.
  32954. *
  32955. * @private
  32956. * @type {Function?}
  32957. * @default null
  32958. */
  32959. this._transparentSort = null;
  32960. /**
  32961. * The framebuffer target.
  32962. *
  32963. * @private
  32964. * @type {RenderTarget?}
  32965. * @default null
  32966. */
  32967. this._frameBufferTarget = null;
  32968. const alphaClear = this.alpha === true ? 0 : 1;
  32969. /**
  32970. * The clear color value.
  32971. *
  32972. * @private
  32973. * @type {Color4}
  32974. */
  32975. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  32976. /**
  32977. * The clear depth value.
  32978. *
  32979. * @private
  32980. * @type {Number}
  32981. * @default 1
  32982. */
  32983. this._clearDepth = 1;
  32984. /**
  32985. * The clear stencil value.
  32986. *
  32987. * @private
  32988. * @type {Number}
  32989. * @default 0
  32990. */
  32991. this._clearStencil = 0;
  32992. /**
  32993. * The current render target.
  32994. *
  32995. * @private
  32996. * @type {RenderTarget?}
  32997. * @default null
  32998. */
  32999. this._renderTarget = null;
  33000. /**
  33001. * The active cube face.
  33002. *
  33003. * @private
  33004. * @type {Number}
  33005. * @default 0
  33006. */
  33007. this._activeCubeFace = 0;
  33008. /**
  33009. * The active mipmap level.
  33010. *
  33011. * @private
  33012. * @type {Number}
  33013. * @default 0
  33014. */
  33015. this._activeMipmapLevel = 0;
  33016. /**
  33017. * The MRT setting.
  33018. *
  33019. * @private
  33020. * @type {MRTNode?}
  33021. * @default null
  33022. */
  33023. this._mrt = null;
  33024. /**
  33025. * This function defines how a render object is going
  33026. * to be rendered.
  33027. *
  33028. * @private
  33029. * @type {Function?}
  33030. * @default null
  33031. */
  33032. this._renderObjectFunction = null;
  33033. /**
  33034. * Used to keep track of the current render object function.
  33035. *
  33036. * @private
  33037. * @type {Function?}
  33038. * @default null
  33039. */
  33040. this._currentRenderObjectFunction = null;
  33041. /**
  33042. * Used to keep track of the current render bundle.
  33043. *
  33044. * @private
  33045. * @type {RenderBundle?}
  33046. * @default null
  33047. */
  33048. this._currentRenderBundle = null;
  33049. /**
  33050. * Next to `_renderObjectFunction()`, this function provides another hook
  33051. * for influencing the render process of a render object. It is meant for internal
  33052. * use and only relevant for `compileAsync()` right now. Instead of using
  33053. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  33054. * a different function might be used which performs no draw but just the node
  33055. * and pipeline updates.
  33056. *
  33057. * @private
  33058. * @type {Function?}
  33059. * @default null
  33060. */
  33061. this._handleObjectFunction = this._renderObjectDirect;
  33062. /**
  33063. * Indicates whether the device has been lost or not. In WebGL terms, the device
  33064. * lost is considered as a context lost. When this is set to `true`, rendering
  33065. * isn't possible anymore.
  33066. *
  33067. * @private
  33068. * @type {Boolean}
  33069. * @default false
  33070. */
  33071. this._isDeviceLost = false;
  33072. /**
  33073. * A callback function that defines what should happen when a device/context lost occurs.
  33074. *
  33075. * @type {Function}
  33076. */
  33077. this.onDeviceLost = this._onDeviceLost;
  33078. /**
  33079. * Whether the renderer has been initialized or not.
  33080. *
  33081. * @private
  33082. * @type {Boolean}
  33083. * @default false
  33084. */
  33085. this._initialized = false;
  33086. /**
  33087. * A reference to the promise which initializes the renderer.
  33088. *
  33089. * @private
  33090. * @type {Promise?}
  33091. * @default null
  33092. */
  33093. this._initPromise = null;
  33094. /**
  33095. * An array of compilation promises which are used in `compileAsync()`.
  33096. *
  33097. * @private
  33098. * @type {Array<Promise>?}
  33099. * @default null
  33100. */
  33101. this._compilationPromises = null;
  33102. /**
  33103. * Whether the renderer should render transparent render objects or not.
  33104. *
  33105. * @type {Boolean}
  33106. * @default true
  33107. */
  33108. this.transparent = true;
  33109. /**
  33110. * Whether the renderer should render opaque render objects or not.
  33111. *
  33112. * @type {Boolean}
  33113. * @default true
  33114. */
  33115. this.opaque = true;
  33116. /**
  33117. * Shadow map configuration
  33118. * @typedef {Object} ShadowMapConfig
  33119. * @property {Boolean} enabled - Whether to globally enable shadows or not.
  33120. * @property {Number} type - The shadow map type.
  33121. */
  33122. /**
  33123. * The renderer's shadow configuration.
  33124. *
  33125. * @type {module:Renderer~ShadowMapConfig}
  33126. */
  33127. this.shadowMap = {
  33128. enabled: false,
  33129. type: PCFShadowMap
  33130. };
  33131. /**
  33132. * XR configuration.
  33133. * @typedef {Object} XRConfig
  33134. * @property {Boolean} enabled - Whether to globally enable XR or not.
  33135. */
  33136. /**
  33137. * The renderer's XR configuration.
  33138. *
  33139. * @type {module:Renderer~XRConfig}
  33140. */
  33141. this.xr = {
  33142. enabled: false
  33143. };
  33144. /**
  33145. * Debug configuration.
  33146. * @typedef {Object} DebugConfig
  33147. * @property {Boolean} checkShaderErrors - Whether shader errors should be checked or not.
  33148. * @property {Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  33149. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  33150. */
  33151. /**
  33152. * The renderer's debug configuration.
  33153. *
  33154. * @type {module:Renderer~DebugConfig}
  33155. */
  33156. this.debug = {
  33157. checkShaderErrors: true,
  33158. onShaderError: null,
  33159. getShaderAsync: async ( scene, camera, object ) => {
  33160. await this.compileAsync( scene, camera );
  33161. const renderList = this._renderLists.get( scene, camera );
  33162. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  33163. const material = scene.overrideMaterial || object.material;
  33164. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  33165. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  33166. return { fragmentShader, vertexShader };
  33167. }
  33168. };
  33169. }
  33170. /**
  33171. * Initializes the renderer so it is ready for usage.
  33172. *
  33173. * @async
  33174. * @return {Promise} A Promise that resolves when the renderer has been initialized.
  33175. */
  33176. async init() {
  33177. if ( this._initialized ) {
  33178. throw new Error( 'Renderer: Backend has already been initialized.' );
  33179. }
  33180. if ( this._initPromise !== null ) {
  33181. return this._initPromise;
  33182. }
  33183. this._initPromise = new Promise( async ( resolve, reject ) => {
  33184. let backend = this.backend;
  33185. try {
  33186. await backend.init( this );
  33187. } catch ( error ) {
  33188. if ( this._getFallback !== null ) {
  33189. // try the fallback
  33190. try {
  33191. this.backend = backend = this._getFallback( error );
  33192. await backend.init( this );
  33193. } catch ( error ) {
  33194. reject( error );
  33195. return;
  33196. }
  33197. } else {
  33198. reject( error );
  33199. return;
  33200. }
  33201. }
  33202. this._nodes = new Nodes( this, backend );
  33203. this._animation = new Animation( this._nodes, this.info );
  33204. this._attributes = new Attributes( backend );
  33205. this._background = new Background( this, this._nodes );
  33206. this._geometries = new Geometries( this._attributes, this.info );
  33207. this._textures = new Textures( this, backend, this.info );
  33208. this._pipelines = new Pipelines( backend, this._nodes );
  33209. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  33210. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  33211. this._renderLists = new RenderLists( this.lighting );
  33212. this._bundles = new RenderBundles();
  33213. this._renderContexts = new RenderContexts();
  33214. //
  33215. this._animation.start();
  33216. this._initialized = true;
  33217. resolve();
  33218. } );
  33219. return this._initPromise;
  33220. }
  33221. /**
  33222. * The coordinate system of the renderer. The value of this property
  33223. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  33224. * `THREE.WebGPUCoordinateSystem`.
  33225. *
  33226. * @readonly
  33227. * @type {Number}
  33228. */
  33229. get coordinateSystem() {
  33230. return this.backend.coordinateSystem;
  33231. }
  33232. /**
  33233. * Compiles all materials in the given scene. This can be useful to avoid a
  33234. * phenomenon which is called "shader compilation stutter", which occurs when
  33235. * rendering an object with a new shader for the first time.
  33236. *
  33237. * If you want to add a 3D object to an existing scene, use the third optional
  33238. * parameter for applying the target scene. Note that the (target) scene's lighting
  33239. * and environment must be configured before calling this method.
  33240. *
  33241. * @async
  33242. * @param {Object3D} scene - The scene or 3D object to precompile.
  33243. * @param {Camera} camera - The camera that is used to render the scene.
  33244. * @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.
  33245. * @return {Promise} A Promise that resolves when the compile has been finished.
  33246. */
  33247. async compileAsync( scene, camera, targetScene = null ) {
  33248. if ( this._isDeviceLost === true ) return;
  33249. if ( this._initialized === false ) await this.init();
  33250. // preserve render tree
  33251. const nodeFrame = this._nodes.nodeFrame;
  33252. const previousRenderId = nodeFrame.renderId;
  33253. const previousRenderContext = this._currentRenderContext;
  33254. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  33255. const previousCompilationPromises = this._compilationPromises;
  33256. //
  33257. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  33258. if ( targetScene === null ) targetScene = scene;
  33259. const renderTarget = this._renderTarget;
  33260. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  33261. const activeMipmapLevel = this._activeMipmapLevel;
  33262. const compilationPromises = [];
  33263. this._currentRenderContext = renderContext;
  33264. this._currentRenderObjectFunction = this.renderObject;
  33265. this._handleObjectFunction = this._createObjectPipeline;
  33266. this._compilationPromises = compilationPromises;
  33267. nodeFrame.renderId ++;
  33268. //
  33269. nodeFrame.update();
  33270. //
  33271. renderContext.depth = this.depth;
  33272. renderContext.stencil = this.stencil;
  33273. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  33274. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  33275. //
  33276. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  33277. //
  33278. const renderList = this._renderLists.get( scene, camera );
  33279. renderList.begin();
  33280. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  33281. // include lights from target scene
  33282. if ( targetScene !== scene ) {
  33283. targetScene.traverseVisible( function ( object ) {
  33284. if ( object.isLight && object.layers.test( camera.layers ) ) {
  33285. renderList.pushLight( object );
  33286. }
  33287. } );
  33288. }
  33289. renderList.finish();
  33290. //
  33291. if ( renderTarget !== null ) {
  33292. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  33293. const renderTargetData = this._textures.get( renderTarget );
  33294. renderContext.textures = renderTargetData.textures;
  33295. renderContext.depthTexture = renderTargetData.depthTexture;
  33296. } else {
  33297. renderContext.textures = null;
  33298. renderContext.depthTexture = null;
  33299. }
  33300. //
  33301. this._background.update( sceneRef, renderList, renderContext );
  33302. // process render lists
  33303. const opaqueObjects = renderList.opaque;
  33304. const transparentObjects = renderList.transparent;
  33305. const transparentDoublePassObjects = renderList.transparentDoublePass;
  33306. const lightsNode = renderList.lightsNode;
  33307. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  33308. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  33309. // restore render tree
  33310. nodeFrame.renderId = previousRenderId;
  33311. this._currentRenderContext = previousRenderContext;
  33312. this._currentRenderObjectFunction = previousRenderObjectFunction;
  33313. this._compilationPromises = previousCompilationPromises;
  33314. this._handleObjectFunction = this._renderObjectDirect;
  33315. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  33316. await Promise.all( compilationPromises );
  33317. }
  33318. /**
  33319. * Renders the scene in an async fashion.
  33320. *
  33321. * @async
  33322. * @param {Object3D} scene - The scene or 3D object to render.
  33323. * @param {Camera} camera - The camera.
  33324. * @return {Promise} A Promise that resolves when the render has been finished.
  33325. */
  33326. async renderAsync( scene, camera ) {
  33327. if ( this._initialized === false ) await this.init();
  33328. const renderContext = this._renderScene( scene, camera );
  33329. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  33330. }
  33331. /**
  33332. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  33333. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  33334. *
  33335. * @async
  33336. * @return {Promise} A Promise that resolves when synchronization has been finished.
  33337. */
  33338. async waitForGPU() {
  33339. await this.backend.waitForGPU();
  33340. }
  33341. /**
  33342. * Sets the given MRT configuration.
  33343. *
  33344. * @param {MRTNode} mrt - The MRT node to set.
  33345. * @return {Renderer} A reference to this renderer.
  33346. */
  33347. setMRT( mrt ) {
  33348. this._mrt = mrt;
  33349. return this;
  33350. }
  33351. /**
  33352. * Returns the MRT configuration.
  33353. *
  33354. * @return {MRTNode} The MRT configuration.
  33355. */
  33356. getMRT() {
  33357. return this._mrt;
  33358. }
  33359. /**
  33360. * Default implementation of the device lost callback.
  33361. *
  33362. * @private
  33363. * @param {Object} info - Information about the context lost.
  33364. */
  33365. _onDeviceLost( info ) {
  33366. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  33367. if ( info.reason ) {
  33368. errorMessage += `\nReason: ${info.reason}`;
  33369. }
  33370. console.error( errorMessage );
  33371. this._isDeviceLost = true;
  33372. }
  33373. /**
  33374. * Renders the given render bundle.
  33375. *
  33376. * @private
  33377. * @param {Object} bundle - Render bundle data.
  33378. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  33379. * @param {LightsNode} lightsNode - The current lights node.
  33380. */
  33381. _renderBundle( bundle, sceneRef, lightsNode ) {
  33382. const { bundleGroup, camera, renderList } = bundle;
  33383. const renderContext = this._currentRenderContext;
  33384. //
  33385. const renderBundle = this._bundles.get( bundleGroup, camera );
  33386. const renderBundleData = this.backend.get( renderBundle );
  33387. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  33388. //
  33389. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  33390. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  33391. renderBundleData.renderContexts.add( renderContext );
  33392. if ( renderBundleNeedsUpdate ) {
  33393. this.backend.beginBundle( renderContext );
  33394. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  33395. renderBundleData.renderObjects = [];
  33396. }
  33397. this._currentRenderBundle = renderBundle;
  33398. const opaqueObjects = renderList.opaque;
  33399. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  33400. this._currentRenderBundle = null;
  33401. //
  33402. this.backend.finishBundle( renderContext, renderBundle );
  33403. renderBundleData.version = bundleGroup.version;
  33404. } else {
  33405. const { renderObjects } = renderBundleData;
  33406. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  33407. const renderObject = renderObjects[ i ];
  33408. if ( this._nodes.needsRefresh( renderObject ) ) {
  33409. this._nodes.updateBefore( renderObject );
  33410. this._nodes.updateForRender( renderObject );
  33411. this._bindings.updateForRender( renderObject );
  33412. this._nodes.updateAfter( renderObject );
  33413. }
  33414. }
  33415. }
  33416. this.backend.addBundle( renderContext, renderBundle );
  33417. }
  33418. /**
  33419. * Renders the scene or 3D object with the given camera. This method can only be called
  33420. * if the renderer has been initialized.
  33421. *
  33422. * The target of the method is the default framebuffer (meaning the canvas)
  33423. * or alternatively a render target when specified via `setRenderTarget()`.
  33424. *
  33425. * @param {Object3D} scene - The scene or 3D object to render.
  33426. * @param {Camera} camera - The camera to render the scene with.
  33427. * @return {Promise?} A Promise that resolve when the scene has been rendered.
  33428. * Only returned when the renderer has not been initialized.
  33429. */
  33430. render( scene, camera ) {
  33431. if ( this._initialized === false ) {
  33432. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  33433. return this.renderAsync( scene, camera );
  33434. }
  33435. this._renderScene( scene, camera );
  33436. }
  33437. /**
  33438. * Returns an internal render target which is used when computing the output tone mapping
  33439. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  33440. * pass and not inline to achieve more correct results.
  33441. *
  33442. * @private
  33443. * @return {RenderTarget?} The render target. The method returns `null` if no output conversion should be applied.
  33444. */
  33445. _getFrameBufferTarget() {
  33446. const { currentToneMapping, currentColorSpace } = this;
  33447. const useToneMapping = currentToneMapping !== NoToneMapping;
  33448. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  33449. if ( useToneMapping === false && useColorSpace === false ) return null;
  33450. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  33451. const { depth, stencil } = this;
  33452. let frameBufferTarget = this._frameBufferTarget;
  33453. if ( frameBufferTarget === null ) {
  33454. frameBufferTarget = new RenderTarget( width, height, {
  33455. depthBuffer: depth,
  33456. stencilBuffer: stencil,
  33457. type: HalfFloatType, // FloatType
  33458. format: RGBAFormat,
  33459. colorSpace: LinearSRGBColorSpace,
  33460. generateMipmaps: false,
  33461. minFilter: LinearFilter,
  33462. magFilter: LinearFilter,
  33463. samples: this.samples
  33464. } );
  33465. frameBufferTarget.isPostProcessingRenderTarget = true;
  33466. this._frameBufferTarget = frameBufferTarget;
  33467. }
  33468. frameBufferTarget.depthBuffer = depth;
  33469. frameBufferTarget.stencilBuffer = stencil;
  33470. frameBufferTarget.setSize( width, height );
  33471. frameBufferTarget.viewport.copy( this._viewport );
  33472. frameBufferTarget.scissor.copy( this._scissor );
  33473. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  33474. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  33475. frameBufferTarget.scissorTest = this._scissorTest;
  33476. return frameBufferTarget;
  33477. }
  33478. /**
  33479. * Renders the scene or 3D object with the given camera.
  33480. *
  33481. * @private
  33482. * @param {Object3D} scene - The scene or 3D object to render.
  33483. * @param {Camera} camera - The camera to render the scene with.
  33484. * @param {Boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  33485. * @return {RenderContext} The current render context.
  33486. */
  33487. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  33488. if ( this._isDeviceLost === true ) return;
  33489. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  33490. // preserve render tree
  33491. const nodeFrame = this._nodes.nodeFrame;
  33492. const previousRenderId = nodeFrame.renderId;
  33493. const previousRenderContext = this._currentRenderContext;
  33494. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  33495. //
  33496. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  33497. const outputRenderTarget = this._renderTarget;
  33498. const activeCubeFace = this._activeCubeFace;
  33499. const activeMipmapLevel = this._activeMipmapLevel;
  33500. //
  33501. let renderTarget;
  33502. if ( frameBufferTarget !== null ) {
  33503. renderTarget = frameBufferTarget;
  33504. this.setRenderTarget( renderTarget );
  33505. } else {
  33506. renderTarget = outputRenderTarget;
  33507. }
  33508. //
  33509. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  33510. this._currentRenderContext = renderContext;
  33511. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  33512. //
  33513. this.info.calls ++;
  33514. this.info.render.calls ++;
  33515. this.info.render.frameCalls ++;
  33516. nodeFrame.renderId = this.info.calls;
  33517. //
  33518. const coordinateSystem = this.coordinateSystem;
  33519. if ( camera.coordinateSystem !== coordinateSystem ) {
  33520. camera.coordinateSystem = coordinateSystem;
  33521. camera.updateProjectionMatrix();
  33522. }
  33523. //
  33524. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  33525. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  33526. //
  33527. let viewport = this._viewport;
  33528. let scissor = this._scissor;
  33529. let pixelRatio = this._pixelRatio;
  33530. if ( renderTarget !== null ) {
  33531. viewport = renderTarget.viewport;
  33532. scissor = renderTarget.scissor;
  33533. pixelRatio = 1;
  33534. }
  33535. this.getDrawingBufferSize( _drawingBufferSize );
  33536. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  33537. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  33538. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  33539. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  33540. renderContext.viewportValue.width >>= activeMipmapLevel;
  33541. renderContext.viewportValue.height >>= activeMipmapLevel;
  33542. renderContext.viewportValue.minDepth = minDepth;
  33543. renderContext.viewportValue.maxDepth = maxDepth;
  33544. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  33545. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  33546. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  33547. renderContext.scissorValue.width >>= activeMipmapLevel;
  33548. renderContext.scissorValue.height >>= activeMipmapLevel;
  33549. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  33550. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  33551. //
  33552. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  33553. //
  33554. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  33555. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  33556. const renderList = this._renderLists.get( scene, camera );
  33557. renderList.begin();
  33558. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  33559. renderList.finish();
  33560. if ( this.sortObjects === true ) {
  33561. renderList.sort( this._opaqueSort, this._transparentSort );
  33562. }
  33563. //
  33564. if ( renderTarget !== null ) {
  33565. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  33566. const renderTargetData = this._textures.get( renderTarget );
  33567. renderContext.textures = renderTargetData.textures;
  33568. renderContext.depthTexture = renderTargetData.depthTexture;
  33569. renderContext.width = renderTargetData.width;
  33570. renderContext.height = renderTargetData.height;
  33571. renderContext.renderTarget = renderTarget;
  33572. renderContext.depth = renderTarget.depthBuffer;
  33573. renderContext.stencil = renderTarget.stencilBuffer;
  33574. } else {
  33575. renderContext.textures = null;
  33576. renderContext.depthTexture = null;
  33577. renderContext.width = this.domElement.width;
  33578. renderContext.height = this.domElement.height;
  33579. renderContext.depth = this.depth;
  33580. renderContext.stencil = this.stencil;
  33581. }
  33582. renderContext.width >>= activeMipmapLevel;
  33583. renderContext.height >>= activeMipmapLevel;
  33584. renderContext.activeCubeFace = activeCubeFace;
  33585. renderContext.activeMipmapLevel = activeMipmapLevel;
  33586. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  33587. //
  33588. this._background.update( sceneRef, renderList, renderContext );
  33589. //
  33590. this.backend.beginRender( renderContext );
  33591. // process render lists
  33592. const {
  33593. bundles,
  33594. lightsNode,
  33595. transparentDoublePass: transparentDoublePassObjects,
  33596. transparent: transparentObjects,
  33597. opaque: opaqueObjects
  33598. } = renderList;
  33599. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  33600. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  33601. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  33602. // finish render pass
  33603. this.backend.finishRender( renderContext );
  33604. // restore render tree
  33605. nodeFrame.renderId = previousRenderId;
  33606. this._currentRenderContext = previousRenderContext;
  33607. this._currentRenderObjectFunction = previousRenderObjectFunction;
  33608. //
  33609. if ( frameBufferTarget !== null ) {
  33610. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  33611. const quad = this._quad;
  33612. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  33613. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  33614. quad.material.needsUpdate = true;
  33615. }
  33616. this._renderScene( quad, quad.camera, false );
  33617. }
  33618. //
  33619. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  33620. //
  33621. return renderContext;
  33622. }
  33623. /**
  33624. * Returns the maximum available anisotropy for texture filtering.
  33625. *
  33626. * @return {Number} The maximum available anisotropy.
  33627. */
  33628. getMaxAnisotropy() {
  33629. return this.backend.getMaxAnisotropy();
  33630. }
  33631. /**
  33632. * Returns the active cube face.
  33633. *
  33634. * @return {Number} The active cube face.
  33635. */
  33636. getActiveCubeFace() {
  33637. return this._activeCubeFace;
  33638. }
  33639. /**
  33640. * Returns the active mipmap level.
  33641. *
  33642. * @return {Number} The active mipmap level.
  33643. */
  33644. getActiveMipmapLevel() {
  33645. return this._activeMipmapLevel;
  33646. }
  33647. /**
  33648. * Applications are advised to always define the animation loop
  33649. * with this method and not manually with `requestAnimationFrame()`
  33650. * for best compatibility.
  33651. *
  33652. * @async
  33653. * @param {Function} callback - The application's animation loop.
  33654. * @return {Promise} A Promise that resolves when the set has been executed.
  33655. */
  33656. async setAnimationLoop( callback ) {
  33657. if ( this._initialized === false ) await this.init();
  33658. this._animation.setAnimationLoop( callback );
  33659. }
  33660. /**
  33661. * Can be used to transfer buffer data from a storage buffer attribute
  33662. * from the GPU to the CPU in context of compute shaders.
  33663. *
  33664. * @async
  33665. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  33666. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  33667. */
  33668. async getArrayBufferAsync( attribute ) {
  33669. return await this.backend.getArrayBufferAsync( attribute );
  33670. }
  33671. /**
  33672. * Returns the rendering context.
  33673. *
  33674. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  33675. */
  33676. getContext() {
  33677. return this.backend.getContext();
  33678. }
  33679. /**
  33680. * Returns the pixel ratio.
  33681. *
  33682. * @return {Number} The pixel ratio.
  33683. */
  33684. getPixelRatio() {
  33685. return this._pixelRatio;
  33686. }
  33687. /**
  33688. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  33689. *
  33690. * @param {Vector2} target - The method writes the result in this target object.
  33691. * @return {Vector2} The drawing buffer size.
  33692. */
  33693. getDrawingBufferSize( target ) {
  33694. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  33695. }
  33696. /**
  33697. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  33698. *
  33699. * @param {Vector2} target - The method writes the result in this target object.
  33700. * @return {Vector2} The drawing buffer size.
  33701. */
  33702. getSize( target ) {
  33703. return target.set( this._width, this._height );
  33704. }
  33705. /**
  33706. * Sets the given pixel ration and resizes the canvas if necessary.
  33707. *
  33708. * @param {Number} [value=1] - The pixel ratio.
  33709. */
  33710. setPixelRatio( value = 1 ) {
  33711. if ( this._pixelRatio === value ) return;
  33712. this._pixelRatio = value;
  33713. this.setSize( this._width, this._height, false );
  33714. }
  33715. /**
  33716. * This method allows to define the drawing buffer size by specifying
  33717. * width, height and pixel ratio all at once. The size of the drawing
  33718. * buffer is computed with this formula:
  33719. * ````
  33720. * size.x = width * pixelRatio;
  33721. * size.y = height * pixelRatio;
  33722. *```
  33723. *
  33724. * @param {Number} width - The width in logical pixels.
  33725. * @param {Number} height - The height in logical pixels.
  33726. * @param {Number} pixelRatio - The pixel ratio.
  33727. */
  33728. setDrawingBufferSize( width, height, pixelRatio ) {
  33729. this._width = width;
  33730. this._height = height;
  33731. this._pixelRatio = pixelRatio;
  33732. this.domElement.width = Math.floor( width * pixelRatio );
  33733. this.domElement.height = Math.floor( height * pixelRatio );
  33734. this.setViewport( 0, 0, width, height );
  33735. if ( this._initialized ) this.backend.updateSize();
  33736. }
  33737. /**
  33738. * Sets the size of the renderer.
  33739. *
  33740. * @param {Number} width - The width in logical pixels.
  33741. * @param {Number} height - The height in logical pixels.
  33742. * @param {Boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  33743. */
  33744. setSize( width, height, updateStyle = true ) {
  33745. this._width = width;
  33746. this._height = height;
  33747. this.domElement.width = Math.floor( width * this._pixelRatio );
  33748. this.domElement.height = Math.floor( height * this._pixelRatio );
  33749. if ( updateStyle === true ) {
  33750. this.domElement.style.width = width + 'px';
  33751. this.domElement.style.height = height + 'px';
  33752. }
  33753. this.setViewport( 0, 0, width, height );
  33754. if ( this._initialized ) this.backend.updateSize();
  33755. }
  33756. /**
  33757. * Defines a manual sort function for the opaque render list.
  33758. * Pass `null` to use the default sort.
  33759. *
  33760. * @param {Function} method - The sort function.
  33761. */
  33762. setOpaqueSort( method ) {
  33763. this._opaqueSort = method;
  33764. }
  33765. /**
  33766. * Defines a manual sort function for the transparent render list.
  33767. * Pass `null` to use the default sort.
  33768. *
  33769. * @param {Function} method - The sort function.
  33770. */
  33771. setTransparentSort( method ) {
  33772. this._transparentSort = method;
  33773. }
  33774. /**
  33775. * Returns the scissor rectangle.
  33776. *
  33777. * @param {Vector4} target - The method writes the result in this target object.
  33778. * @return {Vector4} The scissor rectangle.
  33779. */
  33780. getScissor( target ) {
  33781. const scissor = this._scissor;
  33782. target.x = scissor.x;
  33783. target.y = scissor.y;
  33784. target.width = scissor.width;
  33785. target.height = scissor.height;
  33786. return target;
  33787. }
  33788. /**
  33789. * Defines the scissor rectangle.
  33790. *
  33791. * @param {Number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  33792. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  33793. * @param {Number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  33794. * @param {Number} width - The width of the scissor box in logical pixel unit.
  33795. * @param {Number} height - The height of the scissor box in logical pixel unit.
  33796. */
  33797. setScissor( x, y, width, height ) {
  33798. const scissor = this._scissor;
  33799. if ( x.isVector4 ) {
  33800. scissor.copy( x );
  33801. } else {
  33802. scissor.set( x, y, width, height );
  33803. }
  33804. }
  33805. /**
  33806. * Returns the scissor test value.
  33807. *
  33808. * @return {Boolean} Whether the scissor test should be enabled or not.
  33809. */
  33810. getScissorTest() {
  33811. return this._scissorTest;
  33812. }
  33813. /**
  33814. * Defines the scissor test.
  33815. *
  33816. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  33817. */
  33818. setScissorTest( boolean ) {
  33819. this._scissorTest = boolean;
  33820. this.backend.setScissorTest( boolean );
  33821. }
  33822. /**
  33823. * Returns the viewport definition.
  33824. *
  33825. * @param {Vector4} target - The method writes the result in this target object.
  33826. * @return {Vector4} The viewport definition.
  33827. */
  33828. getViewport( target ) {
  33829. return target.copy( this._viewport );
  33830. }
  33831. /**
  33832. * Defines the viewport.
  33833. *
  33834. * @param {Number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  33835. * @param {Number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  33836. * @param {Number} width - The width of the viewport in logical pixel unit.
  33837. * @param {Number} height - The height of the viewport in logical pixel unit.
  33838. * @param {Number} minDepth - The minimum depth value of the viewport. WebGPU only.
  33839. * @param {Number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  33840. */
  33841. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  33842. const viewport = this._viewport;
  33843. if ( x.isVector4 ) {
  33844. viewport.copy( x );
  33845. } else {
  33846. viewport.set( x, y, width, height );
  33847. }
  33848. viewport.minDepth = minDepth;
  33849. viewport.maxDepth = maxDepth;
  33850. }
  33851. /**
  33852. * Returns the clear color.
  33853. *
  33854. * @param {Color} target - The method writes the result in this target object.
  33855. * @return {Color} The clear color.
  33856. */
  33857. getClearColor( target ) {
  33858. return target.copy( this._clearColor );
  33859. }
  33860. /**
  33861. * Defines the clear color and optionally the clear alpha.
  33862. *
  33863. * @param {Color} color - The clear color.
  33864. * @param {Number} [alpha=1] - The clear alpha.
  33865. */
  33866. setClearColor( color, alpha = 1 ) {
  33867. this._clearColor.set( color );
  33868. this._clearColor.a = alpha;
  33869. }
  33870. /**
  33871. * Returns the clear alpha.
  33872. *
  33873. * @return {Number} The clear alpha.
  33874. */
  33875. getClearAlpha() {
  33876. return this._clearColor.a;
  33877. }
  33878. /**
  33879. * Defines the clear alpha.
  33880. *
  33881. * @param {Number} alpha - The clear alpha.
  33882. */
  33883. setClearAlpha( alpha ) {
  33884. this._clearColor.a = alpha;
  33885. }
  33886. /**
  33887. * Returns the clear depth.
  33888. *
  33889. * @return {Number} The clear depth.
  33890. */
  33891. getClearDepth() {
  33892. return this._clearDepth;
  33893. }
  33894. /**
  33895. * Defines the clear depth.
  33896. *
  33897. * @param {Number} depth - The clear depth.
  33898. */
  33899. setClearDepth( depth ) {
  33900. this._clearDepth = depth;
  33901. }
  33902. /**
  33903. * Returns the clear stencil.
  33904. *
  33905. * @return {Number} The clear stencil.
  33906. */
  33907. getClearStencil() {
  33908. return this._clearStencil;
  33909. }
  33910. /**
  33911. * Defines the clear stencil.
  33912. *
  33913. * @param {Number} stencil - The clear stencil.
  33914. */
  33915. setClearStencil( stencil ) {
  33916. this._clearStencil = stencil;
  33917. }
  33918. /**
  33919. * This method performs an occlusion query for the given 3D object.
  33920. * It returns `true` if the given 3D object is fully occluded by other
  33921. * 3D objects in the scene.
  33922. *
  33923. * @param {Object3D} object - The 3D object to test.
  33924. * @return {Boolean} Whether the 3D object is fully occluded or not.
  33925. */
  33926. isOccluded( object ) {
  33927. const renderContext = this._currentRenderContext;
  33928. return renderContext && this.backend.isOccluded( renderContext, object );
  33929. }
  33930. /**
  33931. * Performs a manual clear operation. This method ignores `autoClear` properties.
  33932. *
  33933. * @param {Boolean} [color=true] - Whether the color buffer should be cleared or not.
  33934. * @param {Boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  33935. * @param {Boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  33936. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  33937. * Only returned when the renderer has not been initialized.
  33938. */
  33939. clear( color = true, depth = true, stencil = true ) {
  33940. if ( this._initialized === false ) {
  33941. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  33942. return this.clearAsync( color, depth, stencil );
  33943. }
  33944. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  33945. let renderContext = null;
  33946. if ( renderTarget !== null ) {
  33947. this._textures.updateRenderTarget( renderTarget );
  33948. const renderTargetData = this._textures.get( renderTarget );
  33949. renderContext = this._renderContexts.getForClear( renderTarget );
  33950. renderContext.textures = renderTargetData.textures;
  33951. renderContext.depthTexture = renderTargetData.depthTexture;
  33952. renderContext.width = renderTargetData.width;
  33953. renderContext.height = renderTargetData.height;
  33954. renderContext.renderTarget = renderTarget;
  33955. renderContext.depth = renderTarget.depthBuffer;
  33956. renderContext.stencil = renderTarget.stencilBuffer;
  33957. }
  33958. this.backend.clear( color, depth, stencil, renderContext );
  33959. if ( renderTarget !== null && this._renderTarget === null ) {
  33960. // If a color space transform or tone mapping is required,
  33961. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  33962. const quad = this._quad;
  33963. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  33964. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  33965. quad.material.needsUpdate = true;
  33966. }
  33967. this._renderScene( quad, quad.camera, false );
  33968. }
  33969. }
  33970. /**
  33971. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  33972. *
  33973. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  33974. * Only returned when the renderer has not been initialized.
  33975. */
  33976. clearColor() {
  33977. return this.clear( true, false, false );
  33978. }
  33979. /**
  33980. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  33981. *
  33982. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  33983. * Only returned when the renderer has not been initialized.
  33984. */
  33985. clearDepth() {
  33986. return this.clear( false, true, false );
  33987. }
  33988. /**
  33989. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  33990. *
  33991. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  33992. * Only returned when the renderer has not been initialized.
  33993. */
  33994. clearStencil() {
  33995. return this.clear( false, false, true );
  33996. }
  33997. /**
  33998. * Async version of {@link module:Renderer~Renderer#clear}.
  33999. *
  34000. * @async
  34001. * @param {Boolean} [color=true] - Whether the color buffer should be cleared or not.
  34002. * @param {Boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  34003. * @param {Boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  34004. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  34005. */
  34006. async clearAsync( color = true, depth = true, stencil = true ) {
  34007. if ( this._initialized === false ) await this.init();
  34008. this.clear( color, depth, stencil );
  34009. }
  34010. /**
  34011. * Async version of {@link module:Renderer~Renderer#clearColor}.
  34012. *
  34013. * @async
  34014. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  34015. */
  34016. async clearColorAsync() {
  34017. this.clearAsync( true, false, false );
  34018. }
  34019. /**
  34020. * Async version of {@link module:Renderer~Renderer#clearDepth}.
  34021. *
  34022. * @async
  34023. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  34024. */
  34025. async clearDepthAsync() {
  34026. this.clearAsync( false, true, false );
  34027. }
  34028. /**
  34029. * Async version of {@link module:Renderer~Renderer#clearStencil}.
  34030. *
  34031. * @async
  34032. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  34033. */
  34034. async clearStencilAsync() {
  34035. this.clearAsync( false, false, true );
  34036. }
  34037. /**
  34038. * The current output tone mapping of the renderer. When a render target is set,
  34039. * the output tone mapping is always `NoToneMapping`.
  34040. *
  34041. * @type {Number}
  34042. */
  34043. get currentToneMapping() {
  34044. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  34045. }
  34046. /**
  34047. * The current output color space of the renderer. When a render target is set,
  34048. * the output color space is always `LinearSRGBColorSpace`.
  34049. *
  34050. * @type {String}
  34051. */
  34052. get currentColorSpace() {
  34053. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  34054. }
  34055. /**
  34056. * Frees all internal resources of the renderer. Call this method if the renderer
  34057. * is no longer in use by your app.
  34058. */
  34059. dispose() {
  34060. this.info.dispose();
  34061. this.backend.dispose();
  34062. this._animation.dispose();
  34063. this._objects.dispose();
  34064. this._pipelines.dispose();
  34065. this._nodes.dispose();
  34066. this._bindings.dispose();
  34067. this._renderLists.dispose();
  34068. this._renderContexts.dispose();
  34069. this._textures.dispose();
  34070. this.setRenderTarget( null );
  34071. this.setAnimationLoop( null );
  34072. }
  34073. /**
  34074. * Sets the given render target. Calling this method means the renderer does not
  34075. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  34076. * Use `null` as the first argument to reset the state.
  34077. *
  34078. * @param {RenderTarget?} renderTarget - The render target to set.
  34079. * @param {Number} [activeCubeFace=0] - The active cube face.
  34080. * @param {Number} [activeMipmapLevel=0] - The active mipmap level.
  34081. */
  34082. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  34083. this._renderTarget = renderTarget;
  34084. this._activeCubeFace = activeCubeFace;
  34085. this._activeMipmapLevel = activeMipmapLevel;
  34086. }
  34087. /**
  34088. * Returns the current render target.
  34089. *
  34090. * @return {RenderTarget?} The render target. Returns `null` if no render target is set.
  34091. */
  34092. getRenderTarget() {
  34093. return this._renderTarget;
  34094. }
  34095. /**
  34096. * Callback for {@link module:Renderer~Renderer#setRenderObjectFunction}.
  34097. *
  34098. * @callback renderObjectFunction
  34099. * @param {Object3D} object - The 3D object.
  34100. * @param {Scene} scene - The scene the 3D object belongs to.
  34101. * @param {Camera} camera - The camera the object should be rendered with.
  34102. * @param {BufferGeometry} geometry - The object's geometry.
  34103. * @param {Material} material - The object's material.
  34104. * @param {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  34105. * @param {LightsNode} lightsNode - The current lights node.
  34106. * @param {ClippingContext} clippingContext - The clipping context.
  34107. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  34108. */
  34109. /**
  34110. * Sets the given render object function. Calling this method overwrites the default implementation
  34111. * which is {@link module:Renderer~Renderer#renderObject}. Defining a custom function can be useful
  34112. * if you want to modify the way objects are rendered. For example you can define things like "every
  34113. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  34114. * The custom function must always call `renderObject()` in its implementation.
  34115. *
  34116. * Use `null` as the first argument to reset the state.
  34117. *
  34118. * @param {module:Renderer~renderObjectFunction?} renderObjectFunction - The render object function.
  34119. */
  34120. setRenderObjectFunction( renderObjectFunction ) {
  34121. this._renderObjectFunction = renderObjectFunction;
  34122. }
  34123. /**
  34124. * Returns the current render object function.
  34125. *
  34126. * @return {Function?} The current render object function. Returns `null` if no function is set.
  34127. */
  34128. getRenderObjectFunction() {
  34129. return this._renderObjectFunction;
  34130. }
  34131. /**
  34132. * Execute a single or an array of compute nodes. This method can only be called
  34133. * if the renderer has been initialized.
  34134. *
  34135. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  34136. * @return {Promise?} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  34137. */
  34138. compute( computeNodes ) {
  34139. if ( this.isDeviceLost === true ) return;
  34140. if ( this._initialized === false ) {
  34141. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  34142. return this.computeAsync( computeNodes );
  34143. }
  34144. //
  34145. const nodeFrame = this._nodes.nodeFrame;
  34146. const previousRenderId = nodeFrame.renderId;
  34147. //
  34148. this.info.calls ++;
  34149. this.info.compute.calls ++;
  34150. this.info.compute.frameCalls ++;
  34151. nodeFrame.renderId = this.info.calls;
  34152. //
  34153. const backend = this.backend;
  34154. const pipelines = this._pipelines;
  34155. const bindings = this._bindings;
  34156. const nodes = this._nodes;
  34157. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  34158. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  34159. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  34160. }
  34161. backend.beginCompute( computeNodes );
  34162. for ( const computeNode of computeList ) {
  34163. // onInit
  34164. if ( pipelines.has( computeNode ) === false ) {
  34165. const dispose = () => {
  34166. computeNode.removeEventListener( 'dispose', dispose );
  34167. pipelines.delete( computeNode );
  34168. bindings.delete( computeNode );
  34169. nodes.delete( computeNode );
  34170. };
  34171. computeNode.addEventListener( 'dispose', dispose );
  34172. //
  34173. const onInitFn = computeNode.onInitFunction;
  34174. if ( onInitFn !== null ) {
  34175. onInitFn.call( computeNode, { renderer: this } );
  34176. }
  34177. }
  34178. nodes.updateForCompute( computeNode );
  34179. bindings.updateForCompute( computeNode );
  34180. const computeBindings = bindings.getForCompute( computeNode );
  34181. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  34182. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  34183. }
  34184. backend.finishCompute( computeNodes );
  34185. //
  34186. nodeFrame.renderId = previousRenderId;
  34187. }
  34188. /**
  34189. * Execute a single or an array of compute nodes.
  34190. *
  34191. * @async
  34192. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  34193. * @return {Promise?} A Promise that resolve when the compute has finished.
  34194. */
  34195. async computeAsync( computeNodes ) {
  34196. if ( this._initialized === false ) await this.init();
  34197. this.compute( computeNodes );
  34198. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  34199. }
  34200. /**
  34201. * Checks if the given feature is supported by the selected backend.
  34202. *
  34203. * @async
  34204. * @param {String} name - The feature's name.
  34205. * @return {Promise<Boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  34206. */
  34207. async hasFeatureAsync( name ) {
  34208. if ( this._initialized === false ) await this.init();
  34209. return this.backend.hasFeature( name );
  34210. }
  34211. /**
  34212. * Checks if the given feature is supported by the selected backend. If the
  34213. * renderer has not been initialized, this method always returns `false`.
  34214. *
  34215. * @param {String} name - The feature's name.
  34216. * @return {Boolean} Whether the feature is supported or not.
  34217. */
  34218. hasFeature( name ) {
  34219. if ( this._initialized === false ) {
  34220. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  34221. return false;
  34222. }
  34223. return this.backend.hasFeature( name );
  34224. }
  34225. /**
  34226. * Returns `true` when the renderer has been initialized.
  34227. *
  34228. * @return {Boolean} Whether the renderer has been initialized or not.
  34229. */
  34230. hasInitialized() {
  34231. return this._initialized;
  34232. }
  34233. /**
  34234. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  34235. * (which can cause noticeable lags due to decode and GPU upload overhead).
  34236. *
  34237. * @async
  34238. * @param {Texture} texture - The texture.
  34239. * @return {Promise} A Promise that resolves when the texture has been initialized.
  34240. */
  34241. async initTextureAsync( texture ) {
  34242. if ( this._initialized === false ) await this.init();
  34243. this._textures.updateTexture( texture );
  34244. }
  34245. /**
  34246. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  34247. * (which can cause noticeable lags due to decode and GPU upload overhead).
  34248. *
  34249. * This method can only be used if the renderer has been initialized.
  34250. *
  34251. * @param {Texture} texture - The texture.
  34252. */
  34253. initTexture( texture ) {
  34254. if ( this._initialized === false ) {
  34255. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  34256. }
  34257. this._textures.updateTexture( texture );
  34258. }
  34259. /**
  34260. * Copies the current bound framebuffer into the given texture.
  34261. *
  34262. * @param {FramebufferTexture} framebufferTexture - The texture.
  34263. * @param {Vector2|Vector4} rectangle - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  34264. */
  34265. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  34266. if ( rectangle !== null ) {
  34267. if ( rectangle.isVector2 ) {
  34268. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  34269. } else if ( rectangle.isVector4 ) {
  34270. rectangle = _vector4.copy( rectangle ).floor();
  34271. } else {
  34272. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  34273. return;
  34274. }
  34275. } else {
  34276. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  34277. }
  34278. //
  34279. let renderContext = this._currentRenderContext;
  34280. let renderTarget;
  34281. if ( renderContext !== null ) {
  34282. renderTarget = renderContext.renderTarget;
  34283. } else {
  34284. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  34285. if ( renderTarget !== null ) {
  34286. this._textures.updateRenderTarget( renderTarget );
  34287. renderContext = this._textures.get( renderTarget );
  34288. }
  34289. }
  34290. //
  34291. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  34292. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  34293. }
  34294. /**
  34295. * Copies data of source texture into a destination texture.
  34296. *
  34297. * @param {Texture} srcTexture - The source texture.
  34298. * @param {Texture} dstTexture - The destination texture.
  34299. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  34300. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  34301. * @param {Number} level - The mipmap level to copy.
  34302. */
  34303. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  34304. this._textures.updateTexture( srcTexture );
  34305. this._textures.updateTexture( dstTexture );
  34306. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  34307. }
  34308. /**
  34309. * Reads pixel data from the given render target.
  34310. *
  34311. * @async
  34312. * @param {RenderTarget} renderTarget - The render target to read from.
  34313. * @param {Number} x - The `x` coordinate of the copy region's origin.
  34314. * @param {Number} y - The `y` coordinate of the copy region's origin.
  34315. * @param {Number} width - The width of the copy region.
  34316. * @param {Number} height - The height of the copy region.
  34317. * @param {Number} [textureIndex=0] - The texture index of a MRT render target.
  34318. * @param {Number} [faceIndex=0] - The active cube face index.
  34319. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  34320. */
  34321. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  34322. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  34323. }
  34324. /**
  34325. * Analyzes the given 3D object's hierarchy and builds render lists from the
  34326. * processed hierarchy.
  34327. *
  34328. * @param {Object3D} object - The 3D object to process (usually a scene).
  34329. * @param {Camera} camera - The camera the object is rendered with.
  34330. * @param {Number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  34331. * @param {RenderList} renderList - The current render list.
  34332. * @param {ClippingContext} clippingContext - The current clipping context.
  34333. */
  34334. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  34335. if ( object.visible === false ) return;
  34336. const visible = object.layers.test( camera.layers );
  34337. if ( visible ) {
  34338. if ( object.isGroup ) {
  34339. groupOrder = object.renderOrder;
  34340. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  34341. } else if ( object.isLOD ) {
  34342. if ( object.autoUpdate === true ) object.update( camera );
  34343. } else if ( object.isLight ) {
  34344. renderList.pushLight( object );
  34345. } else if ( object.isSprite ) {
  34346. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  34347. if ( this.sortObjects === true ) {
  34348. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  34349. }
  34350. const { geometry, material } = object;
  34351. if ( material.visible ) {
  34352. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  34353. }
  34354. }
  34355. } else if ( object.isLineLoop ) {
  34356. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  34357. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  34358. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  34359. const { geometry, material } = object;
  34360. if ( this.sortObjects === true ) {
  34361. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  34362. _vector4
  34363. .copy( geometry.boundingSphere.center )
  34364. .applyMatrix4( object.matrixWorld )
  34365. .applyMatrix4( _projScreenMatrix );
  34366. }
  34367. if ( Array.isArray( material ) ) {
  34368. const groups = geometry.groups;
  34369. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  34370. const group = groups[ i ];
  34371. const groupMaterial = material[ group.materialIndex ];
  34372. if ( groupMaterial && groupMaterial.visible ) {
  34373. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  34374. }
  34375. }
  34376. } else if ( material.visible ) {
  34377. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  34378. }
  34379. }
  34380. }
  34381. }
  34382. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  34383. const baseRenderList = renderList;
  34384. // replace render list
  34385. renderList = this._renderLists.get( object, camera );
  34386. renderList.begin();
  34387. baseRenderList.pushBundle( {
  34388. bundleGroup: object,
  34389. camera,
  34390. renderList,
  34391. } );
  34392. renderList.finish();
  34393. }
  34394. const children = object.children;
  34395. for ( let i = 0, l = children.length; i < l; i ++ ) {
  34396. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  34397. }
  34398. }
  34399. /**
  34400. * Renders the given render bundles.
  34401. *
  34402. * @private
  34403. * @param {Array<Object>} bundles - Array with render bundle data.
  34404. * @param {Scene} sceneRef - The scene the render bundles belong to.
  34405. * @param {LightsNode} lightsNode - The current lights node.
  34406. */
  34407. _renderBundles( bundles, sceneRef, lightsNode ) {
  34408. for ( const bundle of bundles ) {
  34409. this._renderBundle( bundle, sceneRef, lightsNode );
  34410. }
  34411. }
  34412. /**
  34413. * Renders the transparent objects from the given render lists.
  34414. *
  34415. * @private
  34416. * @param {Array<Object>} renderList - The transparent render list.
  34417. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  34418. * @param {Camera} camera - The camera the render list should be rendered with.
  34419. * @param {Scene} scene - The scene the render list belongs to.
  34420. * @param {LightsNode} lightsNode - The current lights node.
  34421. */
  34422. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  34423. if ( doublePassList.length > 0 ) {
  34424. // render back side
  34425. for ( const { material } of doublePassList ) {
  34426. material.side = BackSide;
  34427. }
  34428. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  34429. // render front side
  34430. for ( const { material } of doublePassList ) {
  34431. material.side = FrontSide;
  34432. }
  34433. this._renderObjects( renderList, camera, scene, lightsNode );
  34434. // restore
  34435. for ( const { material } of doublePassList ) {
  34436. material.side = DoubleSide;
  34437. }
  34438. } else {
  34439. this._renderObjects( renderList, camera, scene, lightsNode );
  34440. }
  34441. }
  34442. /**
  34443. * Renders the objects from the given render list.
  34444. *
  34445. * @private
  34446. * @param {Array<Object>} renderList - The render list.
  34447. * @param {Camera} camera - The camera the render list should be rendered with.
  34448. * @param {Scene} scene - The scene the render list belongs to.
  34449. * @param {LightsNode} lightsNode - The current lights node.
  34450. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  34451. */
  34452. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  34453. // process renderable objects
  34454. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  34455. const renderItem = renderList[ i ];
  34456. // @TODO: Add support for multiple materials per object. This will require to extract
  34457. // the material from the renderItem object and pass it with its group data to renderObject().
  34458. const { object, geometry, material, group, clippingContext } = renderItem;
  34459. if ( camera.isArrayCamera ) {
  34460. const cameras = camera.cameras;
  34461. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  34462. const camera2 = cameras[ j ];
  34463. if ( object.layers.test( camera2.layers ) ) {
  34464. const vp = camera2.viewport;
  34465. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  34466. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  34467. const viewportValue = this._currentRenderContext.viewportValue;
  34468. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  34469. viewportValue.minDepth = minDepth;
  34470. viewportValue.maxDepth = maxDepth;
  34471. this.backend.updateViewport( this._currentRenderContext );
  34472. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode, clippingContext, passId );
  34473. }
  34474. }
  34475. } else {
  34476. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  34477. }
  34478. }
  34479. }
  34480. /**
  34481. * This method represents the default render object function that manages the render lifecycle
  34482. * of the object.
  34483. *
  34484. * @param {Object3D} object - The 3D object.
  34485. * @param {Scene} scene - The scene the 3D object belongs to.
  34486. * @param {Camera} camera - The camera the object should be rendered with.
  34487. * @param {BufferGeometry} geometry - The object's geometry.
  34488. * @param {Material} material - The object's material.
  34489. * @param {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  34490. * @param {LightsNode} lightsNode - The current lights node.
  34491. * @param {ClippingContext} clippingContext - The clipping context.
  34492. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  34493. */
  34494. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  34495. let overridePositionNode;
  34496. let overrideColorNode;
  34497. let overrideDepthNode;
  34498. //
  34499. object.onBeforeRender( this, scene, camera, geometry, material, group );
  34500. //
  34501. if ( scene.overrideMaterial !== null ) {
  34502. const overrideMaterial = scene.overrideMaterial;
  34503. if ( material.positionNode && material.positionNode.isNode ) {
  34504. overridePositionNode = overrideMaterial.positionNode;
  34505. overrideMaterial.positionNode = material.positionNode;
  34506. }
  34507. overrideMaterial.alphaTest = material.alphaTest;
  34508. overrideMaterial.alphaMap = material.alphaMap;
  34509. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  34510. if ( overrideMaterial.isShadowNodeMaterial ) {
  34511. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  34512. if ( material.depthNode && material.depthNode.isNode ) {
  34513. overrideDepthNode = overrideMaterial.depthNode;
  34514. overrideMaterial.depthNode = material.depthNode;
  34515. }
  34516. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  34517. overrideColorNode = overrideMaterial.colorNode;
  34518. overrideMaterial.colorNode = material.castShadowNode;
  34519. }
  34520. }
  34521. material = overrideMaterial;
  34522. }
  34523. //
  34524. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  34525. material.side = BackSide;
  34526. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  34527. material.side = FrontSide;
  34528. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  34529. material.side = DoubleSide;
  34530. } else {
  34531. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  34532. }
  34533. //
  34534. if ( overridePositionNode !== undefined ) {
  34535. scene.overrideMaterial.positionNode = overridePositionNode;
  34536. }
  34537. if ( overrideDepthNode !== undefined ) {
  34538. scene.overrideMaterial.depthNode = overrideDepthNode;
  34539. }
  34540. if ( overrideColorNode !== undefined ) {
  34541. scene.overrideMaterial.colorNode = overrideColorNode;
  34542. }
  34543. //
  34544. object.onAfterRender( this, scene, camera, geometry, material, group );
  34545. }
  34546. /**
  34547. * This method represents the default `_handleObjectFunction` implementation which creates
  34548. * a render object from the given data and performs the draw command with the selected backend.
  34549. *
  34550. * @private
  34551. * @param {Object3D} object - The 3D object.
  34552. * @param {Material} material - The object's material.
  34553. * @param {Scene} scene - The scene the 3D object belongs to.
  34554. * @param {Camera} camera - The camera the object should be rendered with.
  34555. * @param {LightsNode} lightsNode - The current lights node.
  34556. * @param {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  34557. * @param {ClippingContext} clippingContext - The clipping context.
  34558. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  34559. */
  34560. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  34561. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  34562. renderObject.drawRange = object.geometry.drawRange;
  34563. renderObject.group = group;
  34564. //
  34565. const needsRefresh = this._nodes.needsRefresh( renderObject );
  34566. if ( needsRefresh ) {
  34567. this._nodes.updateBefore( renderObject );
  34568. this._geometries.updateForRender( renderObject );
  34569. this._nodes.updateForRender( renderObject );
  34570. this._bindings.updateForRender( renderObject );
  34571. }
  34572. this._pipelines.updateForRender( renderObject );
  34573. //
  34574. if ( this._currentRenderBundle !== null ) {
  34575. const renderBundleData = this.backend.get( this._currentRenderBundle );
  34576. renderBundleData.renderObjects.push( renderObject );
  34577. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  34578. }
  34579. this.backend.draw( renderObject, this.info );
  34580. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  34581. }
  34582. /**
  34583. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  34584. * Used in `compileAsync()`.
  34585. *
  34586. * @private
  34587. * @param {Object3D} object - The 3D object.
  34588. * @param {Material} material - The object's material.
  34589. * @param {Scene} scene - The scene the 3D object belongs to.
  34590. * @param {Camera} camera - The camera the object should be rendered with.
  34591. * @param {LightsNode} lightsNode - The current lights node.
  34592. * @param {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  34593. * @param {ClippingContext} clippingContext - The clipping context.
  34594. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  34595. */
  34596. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  34597. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  34598. renderObject.drawRange = object.geometry.drawRange;
  34599. renderObject.group = group;
  34600. //
  34601. this._nodes.updateBefore( renderObject );
  34602. this._geometries.updateForRender( renderObject );
  34603. this._nodes.updateForRender( renderObject );
  34604. this._bindings.updateForRender( renderObject );
  34605. this._pipelines.getForRender( renderObject, this._compilationPromises );
  34606. this._nodes.updateAfter( renderObject );
  34607. }
  34608. /**
  34609. * Alias for `compileAsync()`.
  34610. *
  34611. * @method
  34612. * @param {Object3D} scene - The scene or 3D object to precompile.
  34613. * @param {Camera} camera - The camera that is used to render the scene.
  34614. * @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.
  34615. * @return {Promise} A Promise that resolves when the compile has been finished.
  34616. */
  34617. get compile() {
  34618. return this.compileAsync;
  34619. }
  34620. }
  34621. /**
  34622. * A binding represents the connection between a resource (like a texture, sampler
  34623. * or uniform buffer) and the resource definition in a shader stage.
  34624. *
  34625. * This module is an abstract base class for all concrete bindings types.
  34626. *
  34627. * @abstract
  34628. * @private
  34629. */
  34630. class Binding {
  34631. /**
  34632. * Constructs a new binding.
  34633. *
  34634. * @param {String} [name=''] - The binding's name.
  34635. */
  34636. constructor( name = '' ) {
  34637. /**
  34638. * The binding's name.
  34639. *
  34640. * @type {String}
  34641. */
  34642. this.name = name;
  34643. /**
  34644. * A bitmask that defines in what shader stages the
  34645. * binding's resource is accessible.
  34646. *
  34647. * @type {String}
  34648. */
  34649. this.visibility = 0;
  34650. }
  34651. /**
  34652. * Makes sure binding's resource is visible for the given shader stage.
  34653. *
  34654. * @param {Number} visibility - The shader stage.
  34655. */
  34656. setVisibility( visibility ) {
  34657. this.visibility |= visibility;
  34658. }
  34659. /**
  34660. * Clones the binding.
  34661. *
  34662. * @return {Binding} The cloned binding.
  34663. */
  34664. clone() {
  34665. return Object.assign( new this.constructor(), this );
  34666. }
  34667. }
  34668. /** @module BufferUtils **/
  34669. /**
  34670. * This function is usually called with the length in bytes of an array buffer.
  34671. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  34672. *
  34673. * @function
  34674. * @param {Number} floatLength - The buffer length.
  34675. * @return {Number} The padded length.
  34676. */
  34677. function getFloatLength( floatLength ) {
  34678. // ensure chunk size alignment (STD140 layout)
  34679. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  34680. }
  34681. /**
  34682. * Represents a buffer binding type.
  34683. *
  34684. * @private
  34685. * @abstract
  34686. * @augments Binding
  34687. */
  34688. class Buffer extends Binding {
  34689. /**
  34690. * Constructs a new buffer.
  34691. *
  34692. * @param {String} name - The buffer's name.
  34693. * @param {TypedArray} [buffer=null] - The buffer.
  34694. */
  34695. constructor( name, buffer = null ) {
  34696. super( name );
  34697. /**
  34698. * This flag can be used for type testing.
  34699. *
  34700. * @type {Boolean}
  34701. * @readonly
  34702. * @default true
  34703. */
  34704. this.isBuffer = true;
  34705. /**
  34706. * The bytes per element.
  34707. *
  34708. * @type {Number}
  34709. */
  34710. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  34711. /**
  34712. * A reference to the internal buffer.
  34713. *
  34714. * @private
  34715. * @type {TypedArray}
  34716. */
  34717. this._buffer = buffer;
  34718. }
  34719. /**
  34720. * The buffer's byte length.
  34721. *
  34722. * @type {Number}
  34723. * @readonly
  34724. */
  34725. get byteLength() {
  34726. return getFloatLength( this._buffer.byteLength );
  34727. }
  34728. /**
  34729. * A reference to the internal buffer.
  34730. *
  34731. * @type {Float32Array}
  34732. * @readonly
  34733. */
  34734. get buffer() {
  34735. return this._buffer;
  34736. }
  34737. /**
  34738. * Updates the binding.
  34739. *
  34740. * @return {Boolean} Whether the buffer has been updated and must be
  34741. * uploaded to the GPU.
  34742. */
  34743. update() {
  34744. return true;
  34745. }
  34746. }
  34747. /**
  34748. * Represents a uniform buffer binding type.
  34749. *
  34750. * @private
  34751. * @augments Buffer
  34752. */
  34753. class UniformBuffer extends Buffer {
  34754. /**
  34755. * Constructs a new uniform buffer.
  34756. *
  34757. * @param {String} name - The buffer's name.
  34758. * @param {TypedArray} [buffer=null] - The buffer.
  34759. */
  34760. constructor( name, buffer = null ) {
  34761. super( name, buffer );
  34762. /**
  34763. * This flag can be used for type testing.
  34764. *
  34765. * @type {Boolean}
  34766. * @readonly
  34767. * @default true
  34768. */
  34769. this.isUniformBuffer = true;
  34770. }
  34771. }
  34772. let _id$4 = 0;
  34773. /**
  34774. * A special form of uniform buffer binding type.
  34775. * It's buffer value is managed by a node object.
  34776. *
  34777. * @private
  34778. * @augments UniformBuffer
  34779. */
  34780. class NodeUniformBuffer extends UniformBuffer {
  34781. /**
  34782. * Constructs a new node-based uniform buffer.
  34783. *
  34784. * @param {BufferNode} nodeUniform - The uniform buffer node.
  34785. * @param {UniformGroupNode} groupNode - The uniform group node.
  34786. */
  34787. constructor( nodeUniform, groupNode ) {
  34788. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  34789. /**
  34790. * The uniform buffer node.
  34791. *
  34792. * @type {BufferNode}
  34793. */
  34794. this.nodeUniform = nodeUniform;
  34795. /**
  34796. * The uniform group node.
  34797. *
  34798. * @type {UniformGroupNode}
  34799. */
  34800. this.groupNode = groupNode;
  34801. }
  34802. /**
  34803. * The uniform buffer.
  34804. *
  34805. * @type {Float32Array}
  34806. */
  34807. get buffer() {
  34808. return this.nodeUniform.value;
  34809. }
  34810. }
  34811. /**
  34812. * This class represents a uniform buffer binding but with
  34813. * an API that allows to maintain individual uniform objects.
  34814. *
  34815. * @private
  34816. * @augments UniformBuffer
  34817. */
  34818. class UniformsGroup extends UniformBuffer {
  34819. /**
  34820. * Constructs a new uniforms group.
  34821. *
  34822. * @param {String} name - The group's name.
  34823. */
  34824. constructor( name ) {
  34825. super( name );
  34826. /**
  34827. * This flag can be used for type testing.
  34828. *
  34829. * @type {Boolean}
  34830. * @readonly
  34831. * @default true
  34832. */
  34833. this.isUniformsGroup = true;
  34834. /**
  34835. * An array with the raw uniform values.
  34836. *
  34837. * @private
  34838. * @type {Array<Number>?}
  34839. * @default null
  34840. */
  34841. this._values = null;
  34842. /**
  34843. * An array of uniform objects.
  34844. *
  34845. * The order of uniforms in this array must match the order of uniforms in the shader.
  34846. *
  34847. * @type {Array<Uniform>}
  34848. */
  34849. this.uniforms = [];
  34850. }
  34851. /**
  34852. * Adds a uniform to this group.
  34853. *
  34854. * @param {Uniform} uniform - The uniform to add.
  34855. * @return {UniformsGroup} A reference to this group.
  34856. */
  34857. addUniform( uniform ) {
  34858. this.uniforms.push( uniform );
  34859. return this;
  34860. }
  34861. /**
  34862. * Removes a uniform from this group.
  34863. *
  34864. * @param {Uniform} uniform - The uniform to remove.
  34865. * @return {UniformsGroup} A reference to this group.
  34866. */
  34867. removeUniform( uniform ) {
  34868. const index = this.uniforms.indexOf( uniform );
  34869. if ( index !== - 1 ) {
  34870. this.uniforms.splice( index, 1 );
  34871. }
  34872. return this;
  34873. }
  34874. /**
  34875. * An array with the raw uniform values.
  34876. *
  34877. * @type {Array<Number>}
  34878. */
  34879. get values() {
  34880. if ( this._values === null ) {
  34881. this._values = Array.from( this.buffer );
  34882. }
  34883. return this._values;
  34884. }
  34885. /**
  34886. * A Float32 array buffer with the uniform values.
  34887. *
  34888. * @type {Float32Array}
  34889. */
  34890. get buffer() {
  34891. let buffer = this._buffer;
  34892. if ( buffer === null ) {
  34893. const byteLength = this.byteLength;
  34894. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  34895. this._buffer = buffer;
  34896. }
  34897. return buffer;
  34898. }
  34899. /**
  34900. * The byte length of the buffer with correct buffer alignment.
  34901. *
  34902. * @type {Number}
  34903. */
  34904. get byteLength() {
  34905. let offset = 0; // global buffer offset in bytes
  34906. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  34907. const uniform = this.uniforms[ i ];
  34908. const { boundary, itemSize } = uniform;
  34909. // offset within a single chunk in bytes
  34910. const chunkOffset = offset % GPU_CHUNK_BYTES;
  34911. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  34912. // conformance tests
  34913. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  34914. // check for chunk overflow
  34915. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  34916. } else if ( chunkOffset % boundary !== 0 ) {
  34917. // check for correct alignment
  34918. offset += ( chunkOffset % boundary );
  34919. }
  34920. uniform.offset = ( offset / this.bytesPerElement );
  34921. offset += ( itemSize * this.bytesPerElement );
  34922. }
  34923. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  34924. }
  34925. /**
  34926. * Updates this group by updating each uniform object of
  34927. * the internal uniform list. The uniform objects check if their
  34928. * values has actually changed so this method only returns
  34929. * `true` if there is a real value change.
  34930. *
  34931. * @return {Boolean} Whether the uniforms have been updated and
  34932. * must be uploaded to the GPU.
  34933. */
  34934. update() {
  34935. let updated = false;
  34936. for ( const uniform of this.uniforms ) {
  34937. if ( this.updateByType( uniform ) === true ) {
  34938. updated = true;
  34939. }
  34940. }
  34941. return updated;
  34942. }
  34943. /**
  34944. * Updates a given uniform by calling an update method matching
  34945. * the uniforms type.
  34946. *
  34947. * @param {Uniform} uniform - The uniform to update.
  34948. * @return {Boolean} Whether the uniform has been updated or not.
  34949. */
  34950. updateByType( uniform ) {
  34951. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  34952. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  34953. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  34954. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  34955. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  34956. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  34957. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  34958. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  34959. }
  34960. /**
  34961. * Updates a given Number uniform.
  34962. *
  34963. * @param {NumberUniform} uniform - The Number uniform.
  34964. * @return {Boolean} Whether the uniform has been updated or not.
  34965. */
  34966. updateNumber( uniform ) {
  34967. let updated = false;
  34968. const a = this.values;
  34969. const v = uniform.getValue();
  34970. const offset = uniform.offset;
  34971. const type = uniform.getType();
  34972. if ( a[ offset ] !== v ) {
  34973. const b = this._getBufferForType( type );
  34974. b[ offset ] = a[ offset ] = v;
  34975. updated = true;
  34976. }
  34977. return updated;
  34978. }
  34979. /**
  34980. * Updates a given Vector2 uniform.
  34981. *
  34982. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  34983. * @return {Boolean} Whether the uniform has been updated or not.
  34984. */
  34985. updateVector2( uniform ) {
  34986. let updated = false;
  34987. const a = this.values;
  34988. const v = uniform.getValue();
  34989. const offset = uniform.offset;
  34990. const type = uniform.getType();
  34991. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  34992. const b = this._getBufferForType( type );
  34993. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  34994. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  34995. updated = true;
  34996. }
  34997. return updated;
  34998. }
  34999. /**
  35000. * Updates a given Vector3 uniform.
  35001. *
  35002. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  35003. * @return {Boolean} Whether the uniform has been updated or not.
  35004. */
  35005. updateVector3( uniform ) {
  35006. let updated = false;
  35007. const a = this.values;
  35008. const v = uniform.getValue();
  35009. const offset = uniform.offset;
  35010. const type = uniform.getType();
  35011. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  35012. const b = this._getBufferForType( type );
  35013. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  35014. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  35015. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  35016. updated = true;
  35017. }
  35018. return updated;
  35019. }
  35020. /**
  35021. * Updates a given Vector4 uniform.
  35022. *
  35023. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  35024. * @return {Boolean} Whether the uniform has been updated or not.
  35025. */
  35026. updateVector4( uniform ) {
  35027. let updated = false;
  35028. const a = this.values;
  35029. const v = uniform.getValue();
  35030. const offset = uniform.offset;
  35031. const type = uniform.getType();
  35032. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  35033. const b = this._getBufferForType( type );
  35034. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  35035. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  35036. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  35037. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  35038. updated = true;
  35039. }
  35040. return updated;
  35041. }
  35042. /**
  35043. * Updates a given Color uniform.
  35044. *
  35045. * @param {ColorUniform} uniform - The Color uniform.
  35046. * @return {Boolean} Whether the uniform has been updated or not.
  35047. */
  35048. updateColor( uniform ) {
  35049. let updated = false;
  35050. const a = this.values;
  35051. const c = uniform.getValue();
  35052. const offset = uniform.offset;
  35053. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  35054. const b = this.buffer;
  35055. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  35056. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  35057. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  35058. updated = true;
  35059. }
  35060. return updated;
  35061. }
  35062. /**
  35063. * Updates a given Matrix3 uniform.
  35064. *
  35065. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  35066. * @return {Boolean} Whether the uniform has been updated or not.
  35067. */
  35068. updateMatrix3( uniform ) {
  35069. let updated = false;
  35070. const a = this.values;
  35071. const e = uniform.getValue().elements;
  35072. const offset = uniform.offset;
  35073. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  35074. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  35075. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  35076. const b = this.buffer;
  35077. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  35078. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  35079. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  35080. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  35081. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  35082. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  35083. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  35084. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  35085. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  35086. updated = true;
  35087. }
  35088. return updated;
  35089. }
  35090. /**
  35091. * Updates a given Matrix4 uniform.
  35092. *
  35093. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  35094. * @return {Boolean} Whether the uniform has been updated or not.
  35095. */
  35096. updateMatrix4( uniform ) {
  35097. let updated = false;
  35098. const a = this.values;
  35099. const e = uniform.getValue().elements;
  35100. const offset = uniform.offset;
  35101. if ( arraysEqual( a, e, offset ) === false ) {
  35102. const b = this.buffer;
  35103. b.set( e, offset );
  35104. setArray( a, e, offset );
  35105. updated = true;
  35106. }
  35107. return updated;
  35108. }
  35109. /**
  35110. * Returns a typed array that matches the given data type.
  35111. *
  35112. * @param {String} type - The data type.
  35113. * @return {TypedArray} The typed array.
  35114. */
  35115. _getBufferForType( type ) {
  35116. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  35117. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  35118. return this.buffer;
  35119. }
  35120. }
  35121. /**
  35122. * Sets the values of the second array to the first array.
  35123. *
  35124. * @private
  35125. * @param {TypedArray} a - The first array.
  35126. * @param {TypedArray} b - The second array.
  35127. * @param {Number} offset - An index offset for the first array.
  35128. */
  35129. function setArray( a, b, offset ) {
  35130. for ( let i = 0, l = b.length; i < l; i ++ ) {
  35131. a[ offset + i ] = b[ i ];
  35132. }
  35133. }
  35134. /**
  35135. * Returns `true` if the given arrays are equal.
  35136. *
  35137. * @private
  35138. * @param {TypedArray} a - The first array.
  35139. * @param {TypedArray} b - The second array.
  35140. * @param {Number} offset - An index offset for the first array.
  35141. * @return {Boolean} Whether the given arrays are equal or not.
  35142. */
  35143. function arraysEqual( a, b, offset ) {
  35144. for ( let i = 0, l = b.length; i < l; i ++ ) {
  35145. if ( a[ offset + i ] !== b[ i ] ) return false;
  35146. }
  35147. return true;
  35148. }
  35149. let _id$3 = 0;
  35150. /**
  35151. * A special form of uniforms group that represents
  35152. * the individual uniforms as node-based uniforms.
  35153. *
  35154. * @private
  35155. * @augments UniformsGroup
  35156. */
  35157. class NodeUniformsGroup extends UniformsGroup {
  35158. /**
  35159. * Constructs a new node-based uniforms group.
  35160. *
  35161. * @param {String} name - The group's name.
  35162. * @param {UniformGroupNode} groupNode - The uniform group node.
  35163. */
  35164. constructor( name, groupNode ) {
  35165. super( name );
  35166. /**
  35167. * The group's ID.
  35168. *
  35169. * @type {Number}
  35170. */
  35171. this.id = _id$3 ++;
  35172. /**
  35173. * The uniform group node.
  35174. *
  35175. * @type {UniformGroupNode}
  35176. */
  35177. this.groupNode = groupNode;
  35178. /**
  35179. * This flag can be used for type testing.
  35180. *
  35181. * @type {Boolean}
  35182. * @readonly
  35183. * @default true
  35184. */
  35185. this.isNodeUniformsGroup = true;
  35186. }
  35187. }
  35188. let _id$2 = 0;
  35189. /**
  35190. * Represents a sampled texture binding type.
  35191. *
  35192. * @private
  35193. * @augments Binding
  35194. */
  35195. class SampledTexture extends Binding {
  35196. /**
  35197. * Constructs a new sampled texture.
  35198. *
  35199. * @param {String} name - The sampled texture's name.
  35200. * @param {Texture?} texture - The texture this binding is referring to.
  35201. */
  35202. constructor( name, texture ) {
  35203. super( name );
  35204. /**
  35205. * This identifier.
  35206. *
  35207. * @type {Number}
  35208. */
  35209. this.id = _id$2 ++;
  35210. /**
  35211. * The texture this binding is referring to.
  35212. *
  35213. * @type {Texture?}
  35214. */
  35215. this.texture = texture;
  35216. /**
  35217. * The binding's version.
  35218. *
  35219. * @type {Number}
  35220. */
  35221. this.version = texture ? texture.version : 0;
  35222. /**
  35223. * Whether the texture is a storage texture or not.
  35224. *
  35225. * @type {Boolean}
  35226. * @default false
  35227. */
  35228. this.store = false;
  35229. /**
  35230. * The binding's generation which is an additional version
  35231. * qualifier.
  35232. *
  35233. * @type {Number?}
  35234. * @default null
  35235. */
  35236. this.generation = null;
  35237. /**
  35238. * This flag can be used for type testing.
  35239. *
  35240. * @type {Boolean}
  35241. * @readonly
  35242. * @default true
  35243. */
  35244. this.isSampledTexture = true;
  35245. }
  35246. /**
  35247. * Returns `true` whether this binding requires an update for the
  35248. * given generation.
  35249. *
  35250. * @param {Number} generation - The generation.
  35251. * @return {Boolean} Whether an update is required or not.
  35252. */
  35253. needsBindingsUpdate( generation ) {
  35254. const { texture } = this;
  35255. if ( generation !== this.generation ) {
  35256. this.generation = generation;
  35257. return true;
  35258. }
  35259. return texture.isVideoTexture;
  35260. }
  35261. /**
  35262. * Updates the binding.
  35263. *
  35264. * @param {Number} generation - The generation.
  35265. * @return {Boolean} Whether the texture has been updated and must be
  35266. * uploaded to the GPU.
  35267. */
  35268. update() {
  35269. const { texture, version } = this;
  35270. if ( version !== texture.version ) {
  35271. this.version = texture.version;
  35272. return true;
  35273. }
  35274. return false;
  35275. }
  35276. }
  35277. /**
  35278. * A special form of sampled texture binding type.
  35279. * It's texture value is managed by a node object.
  35280. *
  35281. * @private
  35282. * @augments SampledTexture
  35283. */
  35284. class NodeSampledTexture extends SampledTexture {
  35285. /**
  35286. * Constructs a new node-based sampled texture.
  35287. *
  35288. * @param {String} name - The textures's name.
  35289. * @param {TextureNode} textureNode - The texture node.
  35290. * @param {UniformGroupNode} groupNode - The uniform group node.
  35291. * @param {String?} [access=null] - The access type.
  35292. */
  35293. constructor( name, textureNode, groupNode, access = null ) {
  35294. super( name, textureNode ? textureNode.value : null );
  35295. /**
  35296. * The texture node.
  35297. *
  35298. * @type {TextureNode}
  35299. */
  35300. this.textureNode = textureNode;
  35301. /**
  35302. * The uniform group node.
  35303. *
  35304. * @type {UniformGroupNode}
  35305. */
  35306. this.groupNode = groupNode;
  35307. /**
  35308. * The access type.
  35309. *
  35310. * @type {String?}
  35311. * @default null
  35312. */
  35313. this.access = access;
  35314. }
  35315. /**
  35316. * Overwrites the default to additionally check if the node value has changed.
  35317. *
  35318. * @param {Number} generation - The generation.
  35319. * @return {Boolean} Whether an update is required or not.
  35320. */
  35321. needsBindingsUpdate( generation ) {
  35322. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  35323. }
  35324. /**
  35325. * Updates the binding.
  35326. *
  35327. * @param {Number} generation - The generation.
  35328. * @return {Boolean} Whether the texture has been updated and must be
  35329. * uploaded to the GPU.
  35330. */
  35331. update() {
  35332. const { textureNode } = this;
  35333. if ( this.texture !== textureNode.value ) {
  35334. this.texture = textureNode.value;
  35335. return true;
  35336. }
  35337. return super.update();
  35338. }
  35339. }
  35340. /**
  35341. * A special form of sampled cube texture binding type.
  35342. * It's texture value is managed by a node object.
  35343. *
  35344. * @private
  35345. * @augments NodeSampledTexture
  35346. */
  35347. class NodeSampledCubeTexture extends NodeSampledTexture {
  35348. /**
  35349. * Constructs a new node-based sampled cube texture.
  35350. *
  35351. * @param {String} name - The textures's name.
  35352. * @param {TextureNode} textureNode - The texture node.
  35353. * @param {UniformGroupNode} groupNode - The uniform group node.
  35354. * @param {String?} [access=null] - The access type.
  35355. */
  35356. constructor( name, textureNode, groupNode, access = null ) {
  35357. super( name, textureNode, groupNode, access );
  35358. /**
  35359. * This flag can be used for type testing.
  35360. *
  35361. * @type {Boolean}
  35362. * @readonly
  35363. * @default true
  35364. */
  35365. this.isSampledCubeTexture = true;
  35366. }
  35367. }
  35368. /**
  35369. * A special form of sampled 3D texture binding type.
  35370. * It's texture value is managed by a node object.
  35371. *
  35372. * @private
  35373. * @augments NodeSampledTexture
  35374. */
  35375. class NodeSampledTexture3D extends NodeSampledTexture {
  35376. /**
  35377. * Constructs a new node-based sampled 3D texture.
  35378. *
  35379. * @param {String} name - The textures's name.
  35380. * @param {TextureNode} textureNode - The texture node.
  35381. * @param {UniformGroupNode} groupNode - The uniform group node.
  35382. * @param {String?} [access=null] - The access type.
  35383. */
  35384. constructor( name, textureNode, groupNode, access = null ) {
  35385. super( name, textureNode, groupNode, access );
  35386. /**
  35387. * This flag can be used for type testing.
  35388. *
  35389. * @type {Boolean}
  35390. * @readonly
  35391. * @default true
  35392. */
  35393. this.isSampledTexture3D = true;
  35394. }
  35395. }
  35396. const glslMethods = {
  35397. textureDimensions: 'textureSize',
  35398. equals: 'equal'
  35399. };
  35400. const precisionLib = {
  35401. low: 'lowp',
  35402. medium: 'mediump',
  35403. high: 'highp'
  35404. };
  35405. const supports$1 = {
  35406. swizzleAssign: true,
  35407. storageBuffer: false
  35408. };
  35409. const defaultPrecisions = `
  35410. precision highp float;
  35411. precision highp int;
  35412. precision highp sampler2D;
  35413. precision highp sampler3D;
  35414. precision highp samplerCube;
  35415. precision highp sampler2DArray;
  35416. precision highp usampler2D;
  35417. precision highp usampler3D;
  35418. precision highp usamplerCube;
  35419. precision highp usampler2DArray;
  35420. precision highp isampler2D;
  35421. precision highp isampler3D;
  35422. precision highp isamplerCube;
  35423. precision highp isampler2DArray;
  35424. precision lowp sampler2DShadow;
  35425. `;
  35426. /**
  35427. * A node builder targeting GLSL.
  35428. *
  35429. * This module generates GLSL shader code from node materials and also
  35430. * generates the respective bindings and vertex buffer definitions. These
  35431. * data are later used by the renderer to create render and compute pipelines
  35432. * for render objects.
  35433. *
  35434. * @augments NodeBuilder
  35435. */
  35436. class GLSLNodeBuilder extends NodeBuilder {
  35437. /**
  35438. * Constructs a new GLSL node builder renderer.
  35439. *
  35440. * @param {Object3D} object - The 3D object.
  35441. * @param {Renderer} renderer - The renderer.
  35442. */
  35443. constructor( object, renderer ) {
  35444. super( object, renderer, new GLSLNodeParser() );
  35445. /**
  35446. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  35447. * another dictionary which manages UBOs per group ('render','frame','object').
  35448. *
  35449. * @type {Object<String,Object<String,NodeUniformsGroup>>}
  35450. */
  35451. this.uniformGroups = {};
  35452. /**
  35453. * An array that holds objects defining the varying and attribute data in
  35454. * context of Transform Feedback.
  35455. *
  35456. * @type {Object<String,Map<String,Object>>}
  35457. */
  35458. this.transforms = [];
  35459. /**
  35460. * A dictionary that holds for each shader stage a Map of used extensions.
  35461. *
  35462. * @type {Object<String,Map<String,Object>>}
  35463. */
  35464. this.extensions = {};
  35465. /**
  35466. * A dictionary that holds for each shader stage an Array of used builtins.
  35467. *
  35468. * @type {Object<String,Array<String>>}
  35469. */
  35470. this.builtins = { vertex: [], fragment: [], compute: [] };
  35471. /**
  35472. * Whether comparison in shader code are generated with methods or not.
  35473. *
  35474. * @type {Boolean}
  35475. * @default true
  35476. */
  35477. this.useComparisonMethod = true;
  35478. }
  35479. /**
  35480. * Checks if the given texture requires a manual conversion to the working color space.
  35481. *
  35482. * @param {Texture} texture - The texture to check.
  35483. * @return {Boolean} Whether the given texture requires a conversion to working color space or not.
  35484. */
  35485. needsToWorkingColorSpace( texture ) {
  35486. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  35487. }
  35488. /**
  35489. * Returns the native shader method name for a given generic name.
  35490. *
  35491. * @param {String} method - The method name to resolve.
  35492. * @return {String} The resolved GLSL method name.
  35493. */
  35494. getMethod( method ) {
  35495. return glslMethods[ method ] || method;
  35496. }
  35497. /**
  35498. * Returns the output struct name. Not relevant for GLSL.
  35499. *
  35500. * @return {String}
  35501. */
  35502. getOutputStructName() {
  35503. return '';
  35504. }
  35505. /**
  35506. * Builds the given shader node.
  35507. *
  35508. * @param {ShaderNodeInternal} shaderNode - The shader node.
  35509. * @return {String} The GLSL function code.
  35510. */
  35511. buildFunctionCode( shaderNode ) {
  35512. const layout = shaderNode.layout;
  35513. const flowData = this.flowShaderNode( shaderNode );
  35514. const parameters = [];
  35515. for ( const input of layout.inputs ) {
  35516. parameters.push( this.getType( input.type ) + ' ' + input.name );
  35517. }
  35518. //
  35519. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  35520. ${ flowData.vars }
  35521. ${ flowData.code }
  35522. return ${ flowData.result };
  35523. }`;
  35524. //
  35525. return code;
  35526. }
  35527. /**
  35528. * Setups the Pixel Buffer Object (PBO) for the given storage
  35529. * buffer node.
  35530. *
  35531. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  35532. */
  35533. setupPBO( storageBufferNode ) {
  35534. const attribute = storageBufferNode.value;
  35535. if ( attribute.pbo === undefined ) {
  35536. const originalArray = attribute.array;
  35537. const numElements = attribute.count * attribute.itemSize;
  35538. const { itemSize } = attribute;
  35539. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  35540. let format = isInteger ? RedIntegerFormat : RedFormat;
  35541. if ( itemSize === 2 ) {
  35542. format = isInteger ? RGIntegerFormat : RGFormat;
  35543. } else if ( itemSize === 3 ) {
  35544. format = isInteger ? RGBIntegerFormat : RGBFormat;
  35545. } else if ( itemSize === 4 ) {
  35546. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  35547. }
  35548. const typeMap = {
  35549. Float32Array: FloatType,
  35550. Uint8Array: UnsignedByteType,
  35551. Uint16Array: UnsignedShortType,
  35552. Uint32Array: UnsignedIntType,
  35553. Int8Array: ByteType,
  35554. Int16Array: ShortType,
  35555. Int32Array: IntType,
  35556. Uint8ClampedArray: UnsignedByteType,
  35557. };
  35558. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  35559. let height = Math.ceil( ( numElements / itemSize ) / width );
  35560. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  35561. const newSize = width * height * itemSize;
  35562. const newArray = new originalArray.constructor( newSize );
  35563. newArray.set( originalArray, 0 );
  35564. attribute.array = newArray;
  35565. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  35566. pboTexture.needsUpdate = true;
  35567. pboTexture.isPBOTexture = true;
  35568. const pbo = new TextureNode( pboTexture, null, null );
  35569. pbo.setPrecision( 'high' );
  35570. attribute.pboNode = pbo;
  35571. attribute.pbo = pbo.value;
  35572. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  35573. }
  35574. }
  35575. /**
  35576. * Returns a GLSL snippet that represents the property name of the given node.
  35577. *
  35578. * @param {Node} node - The node.
  35579. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  35580. * @return {String} The property name.
  35581. */
  35582. getPropertyName( node, shaderStage = this.shaderStage ) {
  35583. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  35584. return shaderStage.charAt( 0 ) + '_' + node.name;
  35585. }
  35586. return super.getPropertyName( node, shaderStage );
  35587. }
  35588. /**
  35589. * Setups the Pixel Buffer Object (PBO) for the given storage
  35590. * buffer node.
  35591. *
  35592. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  35593. * @return {String} The property name.
  35594. */
  35595. generatePBO( storageArrayElementNode ) {
  35596. const { node, indexNode } = storageArrayElementNode;
  35597. const attribute = node.value;
  35598. if ( this.renderer.backend.has( attribute ) ) {
  35599. const attributeData = this.renderer.backend.get( attribute );
  35600. attributeData.pbo = attribute.pbo;
  35601. }
  35602. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  35603. const textureName = this.getPropertyName( nodeUniform );
  35604. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  35605. const indexSnippet = indexNode.build( this, 'uint' );
  35606. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  35607. let propertyName = elementNodeData.propertyName;
  35608. if ( propertyName === undefined ) {
  35609. // property element
  35610. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  35611. propertyName = this.getPropertyName( nodeVar );
  35612. // property size
  35613. const bufferNodeData = this.getDataFromNode( node );
  35614. let propertySizeName = bufferNodeData.propertySizeName;
  35615. if ( propertySizeName === undefined ) {
  35616. propertySizeName = propertyName + 'Size';
  35617. this.getVarFromNode( node, propertySizeName, 'uint' );
  35618. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  35619. bufferNodeData.propertySizeName = propertySizeName;
  35620. }
  35621. //
  35622. const { itemSize } = attribute;
  35623. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  35624. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  35625. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  35626. //
  35627. let prefix = 'vec4';
  35628. if ( attribute.pbo.type === UnsignedIntType ) {
  35629. prefix = 'uvec4';
  35630. } else if ( attribute.pbo.type === IntType ) {
  35631. prefix = 'ivec4';
  35632. }
  35633. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  35634. elementNodeData.propertyName = propertyName;
  35635. }
  35636. return propertyName;
  35637. }
  35638. /**
  35639. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  35640. *
  35641. * @param {Texture} texture - The texture.
  35642. * @param {String} textureProperty - The name of the texture uniform in the shader.
  35643. * @param {String} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  35644. * @param {String?} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  35645. * @param {String} [levelSnippet='0u'] - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  35646. * @return {String} The GLSL snippet.
  35647. */
  35648. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  35649. if ( depthSnippet ) {
  35650. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  35651. } else {
  35652. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  35653. }
  35654. }
  35655. /**
  35656. * Generates the GLSL snippet for sampling/loading the given texture.
  35657. *
  35658. * @param {Texture} texture - The texture.
  35659. * @param {String} textureProperty - The name of the texture uniform in the shader.
  35660. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  35661. * @param {String?} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  35662. * @return {String} The GLSL snippet.
  35663. */
  35664. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  35665. if ( texture.isDepthTexture ) {
  35666. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  35667. } else {
  35668. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  35669. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  35670. }
  35671. }
  35672. /**
  35673. * Generates the GLSL snippet when sampling textures with explicit mip level.
  35674. *
  35675. * @param {Texture} texture - The texture.
  35676. * @param {String} textureProperty - The name of the texture uniform in the shader.
  35677. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  35678. * @param {String} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  35679. * @return {String} The GLSL snippet.
  35680. */
  35681. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  35682. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  35683. }
  35684. /**
  35685. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  35686. *
  35687. * @param {Texture} texture - The texture.
  35688. * @param {String} textureProperty - The name of the texture uniform in the shader.
  35689. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  35690. * @param {String} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  35691. * @return {String} The GLSL snippet.
  35692. */
  35693. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  35694. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  35695. }
  35696. /**
  35697. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  35698. *
  35699. * @param {Texture} texture - The texture.
  35700. * @param {String} textureProperty - The name of the texture uniform in the shader.
  35701. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  35702. * @param {Array<String>} gradSnippet - An array holding both gradient GLSL snippets.
  35703. * @return {String} The GLSL snippet.
  35704. */
  35705. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  35706. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  35707. }
  35708. /**
  35709. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  35710. * against a reference value.
  35711. *
  35712. * @param {Texture} texture - The texture.
  35713. * @param {String} textureProperty - The name of the texture uniform in the shader.
  35714. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  35715. * @param {String} compareSnippet - A GLSL snippet that represents the reference value.
  35716. * @param {String?} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  35717. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  35718. * @return {String} The GLSL snippet.
  35719. */
  35720. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  35721. if ( shaderStage === 'fragment' ) {
  35722. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  35723. } else {
  35724. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  35725. }
  35726. }
  35727. /**
  35728. * Returns the variables of the given shader stage as a GLSL string.
  35729. *
  35730. * @param {String} shaderStage - The shader stage.
  35731. * @return {String} The GLSL snippet that defines the variables.
  35732. */
  35733. getVars( shaderStage ) {
  35734. const snippets = [];
  35735. const vars = this.vars[ shaderStage ];
  35736. if ( vars !== undefined ) {
  35737. for ( const variable of vars ) {
  35738. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  35739. }
  35740. }
  35741. return snippets.join( '\n\t' );
  35742. }
  35743. /**
  35744. * Returns the uniforms of the given shader stage as a GLSL string.
  35745. *
  35746. * @param {String} shaderStage - The shader stage.
  35747. * @return {String} The GLSL snippet that defines the uniforms.
  35748. */
  35749. getUniforms( shaderStage ) {
  35750. const uniforms = this.uniforms[ shaderStage ];
  35751. const bindingSnippets = [];
  35752. const uniformGroups = {};
  35753. for ( const uniform of uniforms ) {
  35754. let snippet = null;
  35755. let group = false;
  35756. if ( uniform.type === 'texture' ) {
  35757. const texture = uniform.node.value;
  35758. let typePrefix = '';
  35759. if ( texture.isDataTexture === true ) {
  35760. if ( texture.type === UnsignedIntType ) {
  35761. typePrefix = 'u';
  35762. } else if ( texture.type === IntType ) {
  35763. typePrefix = 'i';
  35764. }
  35765. }
  35766. if ( texture.compareFunction ) {
  35767. snippet = `sampler2DShadow ${ uniform.name };`;
  35768. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  35769. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  35770. } else {
  35771. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  35772. }
  35773. } else if ( uniform.type === 'cubeTexture' ) {
  35774. snippet = `samplerCube ${ uniform.name };`;
  35775. } else if ( uniform.type === 'texture3D' ) {
  35776. snippet = `sampler3D ${ uniform.name };`;
  35777. } else if ( uniform.type === 'buffer' ) {
  35778. const bufferNode = uniform.node;
  35779. const bufferType = this.getType( bufferNode.bufferType );
  35780. const bufferCount = bufferNode.bufferCount;
  35781. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  35782. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  35783. } else {
  35784. const vectorType = this.getVectorType( uniform.type );
  35785. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  35786. group = true;
  35787. }
  35788. const precision = uniform.node.precision;
  35789. if ( precision !== null ) {
  35790. snippet = precisionLib[ precision ] + ' ' + snippet;
  35791. }
  35792. if ( group ) {
  35793. snippet = '\t' + snippet;
  35794. const groupName = uniform.groupNode.name;
  35795. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  35796. groupSnippets.push( snippet );
  35797. } else {
  35798. snippet = 'uniform ' + snippet;
  35799. bindingSnippets.push( snippet );
  35800. }
  35801. }
  35802. let output = '';
  35803. for ( const name in uniformGroups ) {
  35804. const groupSnippets = uniformGroups[ name ];
  35805. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  35806. }
  35807. output += bindingSnippets.join( '\n' );
  35808. return output;
  35809. }
  35810. /**
  35811. * Returns the type for a given buffer attribute.
  35812. *
  35813. * @param {BufferAttribute} attribute - The buffer attribute.
  35814. * @return {String} The type.
  35815. */
  35816. getTypeFromAttribute( attribute ) {
  35817. let nodeType = super.getTypeFromAttribute( attribute );
  35818. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  35819. let dataAttribute = attribute;
  35820. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  35821. const array = dataAttribute.array;
  35822. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  35823. nodeType = nodeType.slice( 1 );
  35824. }
  35825. }
  35826. return nodeType;
  35827. }
  35828. /**
  35829. * Returns the shader attributes of the given shader stage as a GLSL string.
  35830. *
  35831. * @param {String} shaderStage - The shader stage.
  35832. * @return {String} The GLSL snippet that defines the shader attributes.
  35833. */
  35834. getAttributes( shaderStage ) {
  35835. let snippet = '';
  35836. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  35837. const attributes = this.getAttributesArray();
  35838. let location = 0;
  35839. for ( const attribute of attributes ) {
  35840. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  35841. }
  35842. }
  35843. return snippet;
  35844. }
  35845. /**
  35846. * Returns the members of the given struct type node as a GLSL string.
  35847. *
  35848. * @param {StructTypeNode} struct - The struct type node.
  35849. * @return {String} The GLSL snippet that defines the struct members.
  35850. */
  35851. getStructMembers( struct ) {
  35852. const snippets = [];
  35853. const members = struct.getMemberTypes();
  35854. for ( let i = 0; i < members.length; i ++ ) {
  35855. const member = members[ i ];
  35856. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  35857. }
  35858. return snippets.join( '\n' );
  35859. }
  35860. /**
  35861. * Returns the structs of the given shader stage as a GLSL string.
  35862. *
  35863. * @param {String} shaderStage - The shader stage.
  35864. * @return {String} The GLSL snippet that defines the structs.
  35865. */
  35866. getStructs( shaderStage ) {
  35867. const snippets = [];
  35868. const structs = this.structs[ shaderStage ];
  35869. if ( structs.length === 0 ) {
  35870. return 'layout( location = 0 ) out vec4 fragColor;\n';
  35871. }
  35872. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  35873. const struct = structs[ index ];
  35874. let snippet = '\n';
  35875. snippet += this.getStructMembers( struct );
  35876. snippet += '\n';
  35877. snippets.push( snippet );
  35878. }
  35879. return snippets.join( '\n\n' );
  35880. }
  35881. /**
  35882. * Returns the varyings of the given shader stage as a GLSL string.
  35883. *
  35884. * @param {String} shaderStage - The shader stage.
  35885. * @return {String} The GLSL snippet that defines the varyings.
  35886. */
  35887. getVaryings( shaderStage ) {
  35888. let snippet = '';
  35889. const varyings = this.varyings;
  35890. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  35891. for ( const varying of varyings ) {
  35892. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  35893. const type = this.getType( varying.type );
  35894. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  35895. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  35896. }
  35897. } else if ( shaderStage === 'fragment' ) {
  35898. for ( const varying of varyings ) {
  35899. if ( varying.needsInterpolation ) {
  35900. const type = this.getType( varying.type );
  35901. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  35902. snippet += `${flat}in ${type} ${varying.name};\n`;
  35903. }
  35904. }
  35905. }
  35906. for ( const builtin of this.builtins[ shaderStage ] ) {
  35907. snippet += `${builtin};\n`;
  35908. }
  35909. return snippet;
  35910. }
  35911. /**
  35912. * Returns the vertex index builtin.
  35913. *
  35914. * @return {String} The vertex index.
  35915. */
  35916. getVertexIndex() {
  35917. return 'uint( gl_VertexID )';
  35918. }
  35919. /**
  35920. * Returns the instance index builtin.
  35921. *
  35922. * @return {String} The instance index.
  35923. */
  35924. getInstanceIndex() {
  35925. return 'uint( gl_InstanceID )';
  35926. }
  35927. /**
  35928. * Returns the invocation local index builtin.
  35929. *
  35930. * @return {String} The invocation local index.
  35931. */
  35932. getInvocationLocalIndex() {
  35933. const workgroupSize = this.object.workgroupSize;
  35934. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  35935. return `uint( gl_InstanceID ) % ${size}u`;
  35936. }
  35937. /**
  35938. * Returns the draw index builtin.
  35939. *
  35940. * @return {String?} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  35941. */
  35942. getDrawIndex() {
  35943. const extensions = this.renderer.backend.extensions;
  35944. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  35945. return 'uint( gl_DrawID )';
  35946. }
  35947. return null;
  35948. }
  35949. /**
  35950. * Returns the front facing builtin.
  35951. *
  35952. * @return {String} The front facing builtin.
  35953. */
  35954. getFrontFacing() {
  35955. return 'gl_FrontFacing';
  35956. }
  35957. /**
  35958. * Returns the frag coord builtin.
  35959. *
  35960. * @return {String} The frag coord builtin.
  35961. */
  35962. getFragCoord() {
  35963. return 'gl_FragCoord.xy';
  35964. }
  35965. /**
  35966. * Returns the frag depth builtin.
  35967. *
  35968. * @return {String} The frag depth builtin.
  35969. */
  35970. getFragDepth() {
  35971. return 'gl_FragDepth';
  35972. }
  35973. /**
  35974. * Enables the given extension.
  35975. *
  35976. * @param {String} name - The extension name.
  35977. * @param {String} behavior - The extension behavior.
  35978. * @param {String} [shaderStage=this.shaderStage] - The shader stage.
  35979. */
  35980. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  35981. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  35982. if ( map.has( name ) === false ) {
  35983. map.set( name, {
  35984. name,
  35985. behavior
  35986. } );
  35987. }
  35988. }
  35989. /**
  35990. * Returns the enabled extensions of the given shader stage as a GLSL string.
  35991. *
  35992. * @param {String} shaderStage - The shader stage.
  35993. * @return {String} The GLSL snippet that defines the enabled extensions.
  35994. */
  35995. getExtensions( shaderStage ) {
  35996. const snippets = [];
  35997. if ( shaderStage === 'vertex' ) {
  35998. const ext = this.renderer.backend.extensions;
  35999. const isBatchedMesh = this.object.isBatchedMesh;
  36000. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  36001. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  36002. }
  36003. }
  36004. const extensions = this.extensions[ shaderStage ];
  36005. if ( extensions !== undefined ) {
  36006. for ( const { name, behavior } of extensions.values() ) {
  36007. snippets.push( `#extension ${name} : ${behavior}` );
  36008. }
  36009. }
  36010. return snippets.join( '\n' );
  36011. }
  36012. /**
  36013. * Returns the clip distances builtin.
  36014. *
  36015. * @return {String} The clip distances builtin.
  36016. */
  36017. getClipDistance() {
  36018. return 'gl_ClipDistance';
  36019. }
  36020. /**
  36021. * Whether the requested feature is available or not.
  36022. *
  36023. * @param {String} name - The requested feature.
  36024. * @return {Boolean} Whether the requested feature is supported or not.
  36025. */
  36026. isAvailable( name ) {
  36027. let result = supports$1[ name ];
  36028. if ( result === undefined ) {
  36029. let extensionName;
  36030. result = false;
  36031. switch ( name ) {
  36032. case 'float32Filterable':
  36033. extensionName = 'OES_texture_float_linear';
  36034. break;
  36035. case 'clipDistance':
  36036. extensionName = 'WEBGL_clip_cull_distance';
  36037. break;
  36038. }
  36039. if ( extensionName !== undefined ) {
  36040. const extensions = this.renderer.backend.extensions;
  36041. if ( extensions.has( extensionName ) ) {
  36042. extensions.get( extensionName );
  36043. result = true;
  36044. }
  36045. }
  36046. supports$1[ name ] = result;
  36047. }
  36048. return result;
  36049. }
  36050. /**
  36051. * Whether to flip texture data along its vertical axis or not.
  36052. *
  36053. * @return {Boolean} Returns always `true` in context of GLSL.
  36054. */
  36055. isFlipY() {
  36056. return true;
  36057. }
  36058. /**
  36059. * Enables hardware clipping.
  36060. *
  36061. * @param {String} planeCount - The clipping plane count.
  36062. */
  36063. enableHardwareClipping( planeCount ) {
  36064. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  36065. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  36066. }
  36067. /**
  36068. * Registers a transform in context of Transform Feedback.
  36069. *
  36070. * @param {String} varyingName - The varying name.
  36071. * @param {AttributeNode} attributeNode - The attribute node.
  36072. */
  36073. registerTransform( varyingName, attributeNode ) {
  36074. this.transforms.push( { varyingName, attributeNode } );
  36075. }
  36076. /**
  36077. * Returns the transforms of the given shader stage as a GLSL string.
  36078. *
  36079. * @param {String} shaderStage - The shader stage.
  36080. * @return {String} The GLSL snippet that defines the transforms.
  36081. */
  36082. getTransforms( /* shaderStage */ ) {
  36083. const transforms = this.transforms;
  36084. let snippet = '';
  36085. for ( let i = 0; i < transforms.length; i ++ ) {
  36086. const transform = transforms[ i ];
  36087. const attributeName = this.getPropertyName( transform.attributeNode );
  36088. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  36089. }
  36090. return snippet;
  36091. }
  36092. /**
  36093. * Returns a GLSL struct based on the given name and variables.
  36094. *
  36095. * @private
  36096. * @param {String} name - The struct name.
  36097. * @param {String} vars - The struct variables.
  36098. * @return {String} The GLSL snippet representing a struct.
  36099. */
  36100. _getGLSLUniformStruct( name, vars ) {
  36101. return `
  36102. layout( std140 ) uniform ${name} {
  36103. ${vars}
  36104. };`;
  36105. }
  36106. /**
  36107. * Returns a GLSL vertex shader based on the given shader data.
  36108. *
  36109. * @private
  36110. * @param {Object} shaderData - The shader data.
  36111. * @return {String} The vertex shader.
  36112. */
  36113. _getGLSLVertexCode( shaderData ) {
  36114. return `#version 300 es
  36115. ${ this.getSignature() }
  36116. // extensions
  36117. ${shaderData.extensions}
  36118. // precision
  36119. ${ defaultPrecisions }
  36120. // uniforms
  36121. ${shaderData.uniforms}
  36122. // varyings
  36123. ${shaderData.varyings}
  36124. // attributes
  36125. ${shaderData.attributes}
  36126. // codes
  36127. ${shaderData.codes}
  36128. void main() {
  36129. // vars
  36130. ${shaderData.vars}
  36131. // transforms
  36132. ${shaderData.transforms}
  36133. // flow
  36134. ${shaderData.flow}
  36135. gl_PointSize = 1.0;
  36136. }
  36137. `;
  36138. }
  36139. /**
  36140. * Returns a GLSL fragment shader based on the given shader data.
  36141. *
  36142. * @private
  36143. * @param {Object} shaderData - The shader data.
  36144. * @return {String} The vertex shader.
  36145. */
  36146. _getGLSLFragmentCode( shaderData ) {
  36147. return `#version 300 es
  36148. ${ this.getSignature() }
  36149. // precision
  36150. ${ defaultPrecisions }
  36151. // uniforms
  36152. ${shaderData.uniforms}
  36153. // varyings
  36154. ${shaderData.varyings}
  36155. // codes
  36156. ${shaderData.codes}
  36157. ${shaderData.structs}
  36158. void main() {
  36159. // vars
  36160. ${shaderData.vars}
  36161. // flow
  36162. ${shaderData.flow}
  36163. }
  36164. `;
  36165. }
  36166. /**
  36167. * Controls the code build of the shader stages.
  36168. */
  36169. buildCode() {
  36170. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  36171. this.sortBindingGroups();
  36172. for ( const shaderStage in shadersData ) {
  36173. let flow = '// code\n\n';
  36174. flow += this.flowCode[ shaderStage ];
  36175. const flowNodes = this.flowNodes[ shaderStage ];
  36176. const mainNode = flowNodes[ flowNodes.length - 1 ];
  36177. for ( const node of flowNodes ) {
  36178. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  36179. const slotName = node.name;
  36180. if ( slotName ) {
  36181. if ( flow.length > 0 ) flow += '\n';
  36182. flow += `\t// flow -> ${ slotName }\n\t`;
  36183. }
  36184. flow += `${ flowSlotData.code }\n\t`;
  36185. if ( node === mainNode && shaderStage !== 'compute' ) {
  36186. flow += '// result\n\t';
  36187. if ( shaderStage === 'vertex' ) {
  36188. flow += 'gl_Position = ';
  36189. flow += `${ flowSlotData.result };`;
  36190. } else if ( shaderStage === 'fragment' ) {
  36191. if ( ! node.outputNode.isOutputStructNode ) {
  36192. flow += 'fragColor = ';
  36193. flow += `${ flowSlotData.result };`;
  36194. }
  36195. }
  36196. }
  36197. }
  36198. const stageData = shadersData[ shaderStage ];
  36199. stageData.extensions = this.getExtensions( shaderStage );
  36200. stageData.uniforms = this.getUniforms( shaderStage );
  36201. stageData.attributes = this.getAttributes( shaderStage );
  36202. stageData.varyings = this.getVaryings( shaderStage );
  36203. stageData.vars = this.getVars( shaderStage );
  36204. stageData.structs = this.getStructs( shaderStage );
  36205. stageData.codes = this.getCodes( shaderStage );
  36206. stageData.transforms = this.getTransforms( shaderStage );
  36207. stageData.flow = flow;
  36208. }
  36209. if ( this.material !== null ) {
  36210. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  36211. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  36212. } else {
  36213. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  36214. }
  36215. }
  36216. /**
  36217. * This method is one of the more important ones since it's responsible
  36218. * for generating a matching binding instance for the given uniform node.
  36219. *
  36220. * These bindings are later used in the renderer to create bind groups
  36221. * and layouts.
  36222. *
  36223. * @param {UniformNode} node - The uniform node.
  36224. * @param {String} type - The node data type.
  36225. * @param {String} shaderStage - The shader stage.
  36226. * @param {String?} [name=null] - An optional uniform name.
  36227. * @return {NodeUniform} The node uniform object.
  36228. */
  36229. getUniformFromNode( node, type, shaderStage, name = null ) {
  36230. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  36231. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  36232. let uniformGPU = nodeData.uniformGPU;
  36233. if ( uniformGPU === undefined ) {
  36234. const group = node.groupNode;
  36235. const groupName = group.name;
  36236. const bindings = this.getBindGroupArray( groupName, shaderStage );
  36237. if ( type === 'texture' ) {
  36238. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  36239. bindings.push( uniformGPU );
  36240. } else if ( type === 'cubeTexture' ) {
  36241. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  36242. bindings.push( uniformGPU );
  36243. } else if ( type === 'texture3D' ) {
  36244. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  36245. bindings.push( uniformGPU );
  36246. } else if ( type === 'buffer' ) {
  36247. node.name = `NodeBuffer_${ node.id }`;
  36248. uniformNode.name = `buffer${ node.id }`;
  36249. const buffer = new NodeUniformBuffer( node, group );
  36250. buffer.name = node.name;
  36251. bindings.push( buffer );
  36252. uniformGPU = buffer;
  36253. } else {
  36254. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  36255. let uniformsGroup = uniformsStage[ groupName ];
  36256. if ( uniformsGroup === undefined ) {
  36257. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  36258. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  36259. uniformsStage[ groupName ] = uniformsGroup;
  36260. bindings.push( uniformsGroup );
  36261. }
  36262. uniformGPU = this.getNodeUniform( uniformNode, type );
  36263. uniformsGroup.addUniform( uniformGPU );
  36264. }
  36265. nodeData.uniformGPU = uniformGPU;
  36266. }
  36267. return uniformNode;
  36268. }
  36269. }
  36270. let _vector2 = null;
  36271. let _color4 = null;
  36272. /**
  36273. * Most of the rendering related logic is implemented in the
  36274. * {@link module:Renderer} module and related management components.
  36275. * Sometimes it is required though to execute commands which are
  36276. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  36277. * This abstract base class defines an interface that encapsulates
  36278. * all backend-related logic. Derived classes for each backend must
  36279. * implement the interface.
  36280. *
  36281. * @abstract
  36282. * @private
  36283. */
  36284. class Backend {
  36285. /**
  36286. * Constructs a new backend.
  36287. *
  36288. * @param {Object} parameters - An object holding parameters for the backend.
  36289. */
  36290. constructor( parameters = {} ) {
  36291. /**
  36292. * The parameters of the backend.
  36293. *
  36294. * @type {Object}
  36295. */
  36296. this.parameters = Object.assign( {}, parameters );
  36297. /**
  36298. * This weak map holds backend-specific data of objects
  36299. * like textures, attributes or render targets.
  36300. *
  36301. * @type {WeakMap}
  36302. */
  36303. this.data = new WeakMap();
  36304. /**
  36305. * A reference to the renderer.
  36306. *
  36307. * @type {Renderer?}
  36308. * @default null
  36309. */
  36310. this.renderer = null;
  36311. /**
  36312. * A reference to the canvas element the renderer is drawing to.
  36313. *
  36314. * @type {(HTMLCanvasElement|OffscreenCanvas)?}
  36315. * @default null
  36316. */
  36317. this.domElement = null;
  36318. }
  36319. /**
  36320. * Initializes the backend so it is ready for usage. Concrete backends
  36321. * are supposed to implement their rendering context creation and related
  36322. * operations in this method.
  36323. *
  36324. * @async
  36325. * @param {Renderer} renderer - The renderer.
  36326. * @return {Promise} A Promise that resolves when the backend has been initialized.
  36327. */
  36328. async init( renderer ) {
  36329. this.renderer = renderer;
  36330. }
  36331. /**
  36332. * The coordinate system of the backend.
  36333. *
  36334. * @abstract
  36335. * @type {Number}
  36336. * @readonly
  36337. */
  36338. get coordinateSystem() {}
  36339. // render context
  36340. /**
  36341. * This method is executed at the beginning of a render call and
  36342. * can be used by the backend to prepare the state for upcoming
  36343. * draw calls.
  36344. *
  36345. * @abstract
  36346. * @param {RenderContext} renderContext - The render context.
  36347. */
  36348. beginRender( /*renderContext*/ ) {}
  36349. /**
  36350. * This method is executed at the end of a render call and
  36351. * can be used by the backend to finalize work after draw
  36352. * calls.
  36353. *
  36354. * @abstract
  36355. * @param {RenderContext} renderContext - The render context.
  36356. */
  36357. finishRender( /*renderContext*/ ) {}
  36358. /**
  36359. * This method is executed at the beginning of a compute call and
  36360. * can be used by the backend to prepare the state for upcoming
  36361. * compute tasks.
  36362. *
  36363. * @abstract
  36364. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  36365. */
  36366. beginCompute( /*computeGroup*/ ) {}
  36367. /**
  36368. * This method is executed at the end of a compute call and
  36369. * can be used by the backend to finalize work after compute
  36370. * tasks.
  36371. *
  36372. * @abstract
  36373. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  36374. */
  36375. finishCompute( /*computeGroup*/ ) {}
  36376. // render object
  36377. /**
  36378. * Executes a draw command for the given render object.
  36379. *
  36380. * @abstract
  36381. * @param {RenderObject} renderObject - The render object to draw.
  36382. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  36383. */
  36384. draw( /*renderObject, info*/ ) { }
  36385. // compute node
  36386. /**
  36387. * Executes a compute command for the given compute node.
  36388. *
  36389. * @abstract
  36390. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  36391. * @param {Node} computeNode - The compute node.
  36392. * @param {Array<BindGroup>} bindings - The bindings.
  36393. * @param {ComputePipeline} computePipeline - The compute pipeline.
  36394. */
  36395. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  36396. // program
  36397. /**
  36398. * Creates a shader program from the given programmable stage.
  36399. *
  36400. * @abstract
  36401. * @param {ProgrammableStage} program - The programmable stage.
  36402. */
  36403. createProgram( /*program*/ ) { }
  36404. /**
  36405. * Destroys the shader program of the given programmable stage.
  36406. *
  36407. * @abstract
  36408. * @param {ProgrammableStage} program - The programmable stage.
  36409. */
  36410. destroyProgram( /*program*/ ) { }
  36411. // bindings
  36412. /**
  36413. * Creates bindings from the given bind group definition.
  36414. *
  36415. * @abstract
  36416. * @param {BindGroup} bindGroup - The bind group.
  36417. * @param {Array<BindGroup>} bindings - Array of bind groups.
  36418. * @param {Number} cacheIndex - The cache index.
  36419. * @param {Number} version - The version.
  36420. */
  36421. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  36422. /**
  36423. * Updates the given bind group definition.
  36424. *
  36425. * @abstract
  36426. * @param {BindGroup} bindGroup - The bind group.
  36427. * @param {Array<BindGroup>} bindings - Array of bind groups.
  36428. * @param {Number} cacheIndex - The cache index.
  36429. * @param {Number} version - The version.
  36430. */
  36431. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  36432. /**
  36433. * Updates a buffer binding.
  36434. *
  36435. * @abstract
  36436. * @param {Buffer} binding - The buffer binding to update.
  36437. */
  36438. updateBinding( /*binding*/ ) { }
  36439. // pipeline
  36440. /**
  36441. * Creates a render pipeline for the given render object.
  36442. *
  36443. * @abstract
  36444. * @param {RenderObject} renderObject - The render object.
  36445. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  36446. */
  36447. createRenderPipeline( /*renderObject, promises*/ ) { }
  36448. /**
  36449. * Creates a compute pipeline for the given compute node.
  36450. *
  36451. * @abstract
  36452. * @param {ComputePipeline} computePipeline - The compute pipeline.
  36453. * @param {Array<BindGroup>} bindings - The bindings.
  36454. */
  36455. createComputePipeline( /*computePipeline, bindings*/ ) { }
  36456. // cache key
  36457. /**
  36458. * Returns `true` if the render pipeline requires an update.
  36459. *
  36460. * @abstract
  36461. * @param {RenderObject} renderObject - The render object.
  36462. * @return {Boolean} Whether the render pipeline requires an update or not.
  36463. */
  36464. needsRenderUpdate( /*renderObject*/ ) { }
  36465. /**
  36466. * Returns a cache key that is used to identify render pipelines.
  36467. *
  36468. * @abstract
  36469. * @param {RenderObject} renderObject - The render object.
  36470. * @return {String} The cache key.
  36471. */
  36472. getRenderCacheKey( /*renderObject*/ ) { }
  36473. // node builder
  36474. /**
  36475. * Returns a node builder for the given render object.
  36476. *
  36477. * @abstract
  36478. * @param {RenderObject} renderObject - The render object.
  36479. * @param {Renderer} renderer - The renderer.
  36480. * @return {NodeBuilder} The node builder.
  36481. */
  36482. createNodeBuilder( /*renderObject, renderer*/ ) { }
  36483. // textures
  36484. /**
  36485. * Creates a GPU sampler for the given texture.
  36486. *
  36487. * @abstract
  36488. * @param {Texture} texture - The texture to create the sampler for.
  36489. */
  36490. createSampler( /*texture*/ ) { }
  36491. /**
  36492. * Destroys the GPU sampler for the given texture.
  36493. *
  36494. * @abstract
  36495. * @param {Texture} texture - The texture to destroy the sampler for.
  36496. */
  36497. destroySampler( /*texture*/ ) {}
  36498. /**
  36499. * Creates a default texture for the given texture that can be used
  36500. * as a placeholder until the actual texture is ready for usage.
  36501. *
  36502. * @abstract
  36503. * @param {Texture} texture - The texture to create a default texture for.
  36504. */
  36505. createDefaultTexture( /*texture*/ ) { }
  36506. /**
  36507. * Defines a texture on the GPU for the given texture object.
  36508. *
  36509. * @abstract
  36510. * @param {Texture} texture - The texture.
  36511. * @param {Object} [options={}] - Optional configuration parameter.
  36512. */
  36513. createTexture( /*texture, options={}*/ ) { }
  36514. /**
  36515. * Uploads the updated texture data to the GPU.
  36516. *
  36517. * @abstract
  36518. * @param {Texture} texture - The texture.
  36519. * @param {Object} [options={}] - Optional configuration parameter.
  36520. */
  36521. updateTexture( /*texture, options = {}*/ ) { }
  36522. /**
  36523. * Generates mipmaps for the given texture.
  36524. *
  36525. * @abstract
  36526. * @param {Texture} texture - The texture.
  36527. */
  36528. generateMipmaps( /*texture*/ ) { }
  36529. /**
  36530. * Destroys the GPU data for the given texture object.
  36531. *
  36532. * @abstract
  36533. * @param {Texture} texture - The texture.
  36534. */
  36535. destroyTexture( /*texture*/ ) { }
  36536. /**
  36537. * Returns texture data as a typed array.
  36538. *
  36539. * @abstract
  36540. * @async
  36541. * @param {Texture} texture - The texture to copy.
  36542. * @param {Number} x - The x coordinate of the copy origin.
  36543. * @param {Number} y - The y coordinate of the copy origin.
  36544. * @param {Number} width - The width of the copy.
  36545. * @param {Number} height - The height of the copy.
  36546. * @param {Number} faceIndex - The face index.
  36547. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  36548. */
  36549. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  36550. /**
  36551. * Copies data of the given source texture to the given destination texture.
  36552. *
  36553. * @abstract
  36554. * @param {Texture} srcTexture - The source texture.
  36555. * @param {Texture} dstTexture - The destination texture.
  36556. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  36557. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  36558. * @param {Number} [level=0] - The mip level to copy.
  36559. */
  36560. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0*/ ) {}
  36561. /**
  36562. * Copies the current bound framebuffer to the given texture.
  36563. *
  36564. * @abstract
  36565. * @param {Texture} texture - The destination texture.
  36566. * @param {RenderContext} renderContext - The render context.
  36567. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  36568. */
  36569. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  36570. // attributes
  36571. /**
  36572. * Creates the GPU buffer of a shader attribute.
  36573. *
  36574. * @abstract
  36575. * @param {BufferAttribute} attribute - The buffer attribute.
  36576. */
  36577. createAttribute( /*attribute*/ ) { }
  36578. /**
  36579. * Creates the GPU buffer of an indexed shader attribute.
  36580. *
  36581. * @abstract
  36582. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  36583. */
  36584. createIndexAttribute( /*attribute*/ ) { }
  36585. /**
  36586. * Creates the GPU buffer of a storage attribute.
  36587. *
  36588. * @abstract
  36589. * @param {BufferAttribute} attribute - The buffer attribute.
  36590. */
  36591. createStorageAttribute( /*attribute*/ ) { }
  36592. /**
  36593. * Updates the GPU buffer of a shader attribute.
  36594. *
  36595. * @abstract
  36596. * @param {BufferAttribute} attribute - The buffer attribute to update.
  36597. */
  36598. updateAttribute( /*attribute*/ ) { }
  36599. /**
  36600. * Destroys the GPU buffer of a shader attribute.
  36601. *
  36602. * @abstract
  36603. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  36604. */
  36605. destroyAttribute( /*attribute*/ ) { }
  36606. // canvas
  36607. /**
  36608. * Returns the backend's rendering context.
  36609. *
  36610. * @abstract
  36611. * @return {Object} The rendering context.
  36612. */
  36613. getContext() { }
  36614. /**
  36615. * Backends can use this method if they have to run
  36616. * logic when the renderer gets resized.
  36617. *
  36618. * @abstract
  36619. */
  36620. updateSize() { }
  36621. /**
  36622. * Updates the viewport with the values from the given render context.
  36623. *
  36624. * @abstract
  36625. * @param {RenderContext} renderContext - The render context.
  36626. */
  36627. updateViewport( /*renderContext*/ ) {}
  36628. // utils
  36629. /**
  36630. * Returns `true` if the given 3D object is fully occluded by other
  36631. * 3D objects in the scene. Backends must implement this method by using
  36632. * a Occlusion Query API.
  36633. *
  36634. * @abstract
  36635. * @param {RenderContext} renderContext - The render context.
  36636. * @param {Object3D} object - The 3D object to test.
  36637. * @return {Boolean} Whether the 3D object is fully occluded or not.
  36638. */
  36639. isOccluded( /*renderContext, object*/ ) {}
  36640. /**
  36641. * Resolves the time stamp for the given render context and type.
  36642. *
  36643. * @async
  36644. * @abstract
  36645. * @param {RenderContext} renderContext - The render context.
  36646. * @param {String} type - The render context.
  36647. * @return {Promise} A Promise that resolves when the time stamp has been computed.
  36648. */
  36649. async resolveTimestampAsync( /*renderContext, type*/ ) { }
  36650. /**
  36651. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  36652. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  36653. *
  36654. * @async
  36655. * @abstract
  36656. * @return {Promise} A Promise that resolves when synchronization has been finished.
  36657. */
  36658. async waitForGPU() {}
  36659. /**
  36660. * This method performs a readback operation by moving buffer data from
  36661. * a storage buffer attribute from the GPU to the CPU.
  36662. *
  36663. * @async
  36664. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  36665. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  36666. */
  36667. async getArrayBufferAsync( /* attribute */ ) {}
  36668. /**
  36669. * Checks if the given feature is supported by the backend.
  36670. *
  36671. * @async
  36672. * @abstract
  36673. * @param {String} name - The feature's name.
  36674. * @return {Promise<Boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  36675. */
  36676. async hasFeatureAsync( /*name*/ ) { }
  36677. /**
  36678. * Checks if the given feature is supported by the backend.
  36679. *
  36680. * @abstract
  36681. * @param {String} name - The feature's name.
  36682. * @return {Boolean} Whether the feature is supported or not.
  36683. */
  36684. hasFeature( /*name*/ ) {}
  36685. /**
  36686. * Returns the maximum anisotropy texture filtering value.
  36687. *
  36688. * @abstract
  36689. * @return {Number} The maximum anisotropy texture filtering value.
  36690. */
  36691. getMaxAnisotropy() {}
  36692. /**
  36693. * Returns the drawing buffer size.
  36694. *
  36695. * @return {Vector2} The drawing buffer size.
  36696. */
  36697. getDrawingBufferSize() {
  36698. _vector2 = _vector2 || new Vector2();
  36699. return this.renderer.getDrawingBufferSize( _vector2 );
  36700. }
  36701. /**
  36702. * Defines the scissor test.
  36703. *
  36704. * @abstract
  36705. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  36706. */
  36707. setScissorTest( /*boolean*/ ) { }
  36708. /**
  36709. * Returns the clear color and alpha into a single
  36710. * color object.
  36711. *
  36712. * @return {Color4} The clear color.
  36713. */
  36714. getClearColor() {
  36715. const renderer = this.renderer;
  36716. _color4 = _color4 || new Color4();
  36717. renderer.getClearColor( _color4 );
  36718. _color4.getRGB( _color4, this.renderer.currentColorSpace );
  36719. return _color4;
  36720. }
  36721. /**
  36722. * Returns the DOM element. If no DOM element exists, the backend
  36723. * creates a new one.
  36724. *
  36725. * @return {HTMLCanvasElement} The DOM element.
  36726. */
  36727. getDomElement() {
  36728. let domElement = this.domElement;
  36729. if ( domElement === null ) {
  36730. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  36731. // OffscreenCanvas does not have setAttribute, see #22811
  36732. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  36733. this.domElement = domElement;
  36734. }
  36735. return domElement;
  36736. }
  36737. /**
  36738. * Sets a dictionary for the given object into the
  36739. * internal data structure.
  36740. *
  36741. * @param {Object} object - The object.
  36742. * @param {Object} value - The dictionary to set.
  36743. */
  36744. set( object, value ) {
  36745. this.data.set( object, value );
  36746. }
  36747. /**
  36748. * Returns the dictionary for the given object.
  36749. *
  36750. * @param {Object} object - The object.
  36751. * @return {Object} The object's dictionary.
  36752. */
  36753. get( object ) {
  36754. let map = this.data.get( object );
  36755. if ( map === undefined ) {
  36756. map = {};
  36757. this.data.set( object, map );
  36758. }
  36759. return map;
  36760. }
  36761. /**
  36762. * Checks if the given object has a dictionary
  36763. * with data defined.
  36764. *
  36765. * @param {Object} object - The object.
  36766. * @return {Boolean} Whether a dictionary for the given object as been defined or not.
  36767. */
  36768. has( object ) {
  36769. return this.data.has( object );
  36770. }
  36771. /**
  36772. * Deletes an object from the internal data structure.
  36773. *
  36774. * @param {Object} object - The object to delete.
  36775. */
  36776. delete( object ) {
  36777. this.data.delete( object );
  36778. }
  36779. /**
  36780. * Frees internal resources.
  36781. *
  36782. * @abstract
  36783. */
  36784. dispose() { }
  36785. }
  36786. let _id$1 = 0;
  36787. /**
  36788. * This module is internally used in context of compute shaders.
  36789. * This type of shader is not natively supported in WebGL 2 and
  36790. * thus implemented via Transform Feedback. `DualAttributeData`
  36791. * manages the related data.
  36792. *
  36793. * @private
  36794. */
  36795. class DualAttributeData {
  36796. constructor( attributeData, dualBuffer ) {
  36797. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  36798. this.type = attributeData.type;
  36799. this.bufferType = attributeData.bufferType;
  36800. this.pbo = attributeData.pbo;
  36801. this.byteLength = attributeData.byteLength;
  36802. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  36803. this.version = attributeData.version;
  36804. this.isInteger = attributeData.isInteger;
  36805. this.activeBufferIndex = 0;
  36806. this.baseId = attributeData.id;
  36807. }
  36808. get id() {
  36809. return `${ this.baseId }|${ this.activeBufferIndex }`;
  36810. }
  36811. get bufferGPU() {
  36812. return this.buffers[ this.activeBufferIndex ];
  36813. }
  36814. get transformBuffer() {
  36815. return this.buffers[ this.activeBufferIndex ^ 1 ];
  36816. }
  36817. switchBuffers() {
  36818. this.activeBufferIndex ^= 1;
  36819. }
  36820. }
  36821. /**
  36822. * A WebGL 2 backend utility module for managing shader attributes.
  36823. *
  36824. * @private
  36825. */
  36826. class WebGLAttributeUtils {
  36827. /**
  36828. * Constructs a new utility object.
  36829. *
  36830. * @param {WebGLBackend} backend - The WebGL 2 backend.
  36831. */
  36832. constructor( backend ) {
  36833. /**
  36834. * A reference to the WebGL 2 backend.
  36835. *
  36836. * @type {WebGLBackend}
  36837. */
  36838. this.backend = backend;
  36839. }
  36840. /**
  36841. * Creates the GPU buffer for the given buffer attribute.
  36842. *
  36843. * @param {BufferAttribute} attribute - The buffer attribute.
  36844. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  36845. */
  36846. createAttribute( attribute, bufferType ) {
  36847. const backend = this.backend;
  36848. const { gl } = backend;
  36849. const array = attribute.array;
  36850. const usage = attribute.usage || gl.STATIC_DRAW;
  36851. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  36852. const bufferData = backend.get( bufferAttribute );
  36853. let bufferGPU = bufferData.bufferGPU;
  36854. if ( bufferGPU === undefined ) {
  36855. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  36856. bufferData.bufferGPU = bufferGPU;
  36857. bufferData.bufferType = bufferType;
  36858. bufferData.version = bufferAttribute.version;
  36859. }
  36860. //attribute.onUploadCallback();
  36861. let type;
  36862. if ( array instanceof Float32Array ) {
  36863. type = gl.FLOAT;
  36864. } else if ( array instanceof Uint16Array ) {
  36865. if ( attribute.isFloat16BufferAttribute ) {
  36866. type = gl.HALF_FLOAT;
  36867. } else {
  36868. type = gl.UNSIGNED_SHORT;
  36869. }
  36870. } else if ( array instanceof Int16Array ) {
  36871. type = gl.SHORT;
  36872. } else if ( array instanceof Uint32Array ) {
  36873. type = gl.UNSIGNED_INT;
  36874. } else if ( array instanceof Int32Array ) {
  36875. type = gl.INT;
  36876. } else if ( array instanceof Int8Array ) {
  36877. type = gl.BYTE;
  36878. } else if ( array instanceof Uint8Array ) {
  36879. type = gl.UNSIGNED_BYTE;
  36880. } else if ( array instanceof Uint8ClampedArray ) {
  36881. type = gl.UNSIGNED_BYTE;
  36882. } else {
  36883. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  36884. }
  36885. let attributeData = {
  36886. bufferGPU,
  36887. bufferType,
  36888. type,
  36889. byteLength: array.byteLength,
  36890. bytesPerElement: array.BYTES_PER_ELEMENT,
  36891. version: attribute.version,
  36892. pbo: attribute.pbo,
  36893. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  36894. id: _id$1 ++
  36895. };
  36896. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  36897. // create buffer for transform feedback use
  36898. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  36899. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  36900. }
  36901. backend.set( attribute, attributeData );
  36902. }
  36903. /**
  36904. * Updates the GPU buffer of the given buffer attribute.
  36905. *
  36906. * @param {BufferAttribute} attribute - The buffer attribute.
  36907. */
  36908. updateAttribute( attribute ) {
  36909. const backend = this.backend;
  36910. const { gl } = backend;
  36911. const array = attribute.array;
  36912. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  36913. const bufferData = backend.get( bufferAttribute );
  36914. const bufferType = bufferData.bufferType;
  36915. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  36916. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  36917. if ( updateRanges.length === 0 ) {
  36918. // Not using update ranges
  36919. gl.bufferSubData( bufferType, 0, array );
  36920. } else {
  36921. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  36922. const range = updateRanges[ i ];
  36923. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  36924. array, range.start, range.count );
  36925. }
  36926. bufferAttribute.clearUpdateRanges();
  36927. }
  36928. gl.bindBuffer( bufferType, null );
  36929. bufferData.version = bufferAttribute.version;
  36930. }
  36931. /**
  36932. * Destroys the GPU buffer of the given buffer attribute.
  36933. *
  36934. * @param {BufferAttribute} attribute - The buffer attribute.
  36935. */
  36936. destroyAttribute( attribute ) {
  36937. const backend = this.backend;
  36938. const { gl } = backend;
  36939. if ( attribute.isInterleavedBufferAttribute ) {
  36940. backend.delete( attribute.data );
  36941. }
  36942. const attributeData = backend.get( attribute );
  36943. gl.deleteBuffer( attributeData.bufferGPU );
  36944. backend.delete( attribute );
  36945. }
  36946. /**
  36947. * This method performs a readback operation by moving buffer data from
  36948. * a storage buffer attribute from the GPU to the CPU.
  36949. *
  36950. * @async
  36951. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  36952. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  36953. */
  36954. async getArrayBufferAsync( attribute ) {
  36955. const backend = this.backend;
  36956. const { gl } = backend;
  36957. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  36958. const { bufferGPU } = backend.get( bufferAttribute );
  36959. const array = attribute.array;
  36960. const byteLength = array.byteLength;
  36961. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  36962. const writeBuffer = gl.createBuffer();
  36963. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  36964. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  36965. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  36966. await backend.utils._clientWaitAsync();
  36967. const dstBuffer = new attribute.array.constructor( array.length );
  36968. // Ensure the buffer is bound before reading
  36969. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  36970. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  36971. gl.deleteBuffer( writeBuffer );
  36972. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  36973. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  36974. return dstBuffer.buffer;
  36975. }
  36976. /**
  36977. * Creates a WebGL buffer with the given data.
  36978. *
  36979. * @private
  36980. * @param {WebGL2RenderingContext} gl - The rendering context.
  36981. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  36982. * @param {TypedArray} array - The array of the buffer attribute.
  36983. * @param {GLenum} usage - The usage.
  36984. * @return {WebGLBuffer} The WebGL buffer.
  36985. */
  36986. _createBuffer( gl, bufferType, array, usage ) {
  36987. const bufferGPU = gl.createBuffer();
  36988. gl.bindBuffer( bufferType, bufferGPU );
  36989. gl.bufferData( bufferType, array, usage );
  36990. gl.bindBuffer( bufferType, null );
  36991. return bufferGPU;
  36992. }
  36993. }
  36994. let initialized$1 = false, equationToGL, factorToGL;
  36995. /**
  36996. * A WebGL 2 backend utility module for managing the WebGL state.
  36997. *
  36998. * The major goal of this module is to reduce the number of state changes
  36999. * by caching the WEbGL state with a series of variables. In this way, the
  37000. * renderer only executes state change commands when necessary which
  37001. * improves the overall performance.
  37002. *
  37003. * @private
  37004. */
  37005. class WebGLState {
  37006. /**
  37007. * Constructs a new utility object.
  37008. *
  37009. * @param {WebGLBackend} backend - The WebGL 2 backend.
  37010. */
  37011. constructor( backend ) {
  37012. /**
  37013. * A reference to the WebGL 2 backend.
  37014. *
  37015. * @type {WebGLBackend}
  37016. */
  37017. this.backend = backend;
  37018. /**
  37019. * A reference to the rendering context.
  37020. *
  37021. * @type {WebGL2RenderingContext}
  37022. */
  37023. this.gl = this.backend.gl;
  37024. // Below properties are intended to cache
  37025. // the WebGL state and are not explicitly
  37026. // documented for convenience reasons.
  37027. this.enabled = {};
  37028. this.currentFlipSided = null;
  37029. this.currentCullFace = null;
  37030. this.currentProgram = null;
  37031. this.currentBlendingEnabled = false;
  37032. this.currentBlending = null;
  37033. this.currentBlendSrc = null;
  37034. this.currentBlendDst = null;
  37035. this.currentBlendSrcAlpha = null;
  37036. this.currentBlendDstAlpha = null;
  37037. this.currentPremultipledAlpha = null;
  37038. this.currentPolygonOffsetFactor = null;
  37039. this.currentPolygonOffsetUnits = null;
  37040. this.currentColorMask = null;
  37041. this.currentDepthFunc = null;
  37042. this.currentDepthMask = null;
  37043. this.currentStencilFunc = null;
  37044. this.currentStencilRef = null;
  37045. this.currentStencilFuncMask = null;
  37046. this.currentStencilFail = null;
  37047. this.currentStencilZFail = null;
  37048. this.currentStencilZPass = null;
  37049. this.currentStencilMask = null;
  37050. this.currentLineWidth = null;
  37051. this.currentClippingPlanes = 0;
  37052. this.currentBoundFramebuffers = {};
  37053. this.currentDrawbuffers = new WeakMap();
  37054. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  37055. this.currentTextureSlot = null;
  37056. this.currentBoundTextures = {};
  37057. this.currentBoundBufferBases = {};
  37058. if ( initialized$1 === false ) {
  37059. this._init();
  37060. initialized$1 = true;
  37061. }
  37062. }
  37063. /**
  37064. * Inits the state of the utility.
  37065. *
  37066. * @private
  37067. */
  37068. _init() {
  37069. const gl = this.gl;
  37070. // Store only WebGL constants here.
  37071. equationToGL = {
  37072. [ AddEquation ]: gl.FUNC_ADD,
  37073. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  37074. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  37075. };
  37076. factorToGL = {
  37077. [ ZeroFactor ]: gl.ZERO,
  37078. [ OneFactor ]: gl.ONE,
  37079. [ SrcColorFactor ]: gl.SRC_COLOR,
  37080. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  37081. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  37082. [ DstColorFactor ]: gl.DST_COLOR,
  37083. [ DstAlphaFactor ]: gl.DST_ALPHA,
  37084. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  37085. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  37086. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  37087. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  37088. };
  37089. }
  37090. /**
  37091. * Enables the given WebGL capability.
  37092. *
  37093. * This method caches the capability state so
  37094. * `gl.enable()` is only called when necessary.
  37095. *
  37096. * @param {GLenum} id - The capability to enable.
  37097. */
  37098. enable( id ) {
  37099. const { enabled } = this;
  37100. if ( enabled[ id ] !== true ) {
  37101. this.gl.enable( id );
  37102. enabled[ id ] = true;
  37103. }
  37104. }
  37105. /**
  37106. * Disables the given WebGL capability.
  37107. *
  37108. * This method caches the capability state so
  37109. * `gl.disable()` is only called when necessary.
  37110. *
  37111. * @param {GLenum} id - The capability to enable.
  37112. */
  37113. disable( id ) {
  37114. const { enabled } = this;
  37115. if ( enabled[ id ] !== false ) {
  37116. this.gl.disable( id );
  37117. enabled[ id ] = false;
  37118. }
  37119. }
  37120. /**
  37121. * Specifies whether polygons are front- or back-facing
  37122. * by setting the winding orientation.
  37123. *
  37124. * This method caches the state so `gl.frontFace()` is only
  37125. * called when necessary.
  37126. *
  37127. * @param {Boolean} flipSided - Whether triangles flipped their sides or not.
  37128. */
  37129. setFlipSided( flipSided ) {
  37130. if ( this.currentFlipSided !== flipSided ) {
  37131. const { gl } = this;
  37132. if ( flipSided ) {
  37133. gl.frontFace( gl.CW );
  37134. } else {
  37135. gl.frontFace( gl.CCW );
  37136. }
  37137. this.currentFlipSided = flipSided;
  37138. }
  37139. }
  37140. /**
  37141. * Specifies whether or not front- and/or back-facing
  37142. * polygons can be culled.
  37143. *
  37144. * This method caches the state so `gl.cullFace()` is only
  37145. * called when necessary.
  37146. *
  37147. * @param {Number} cullFace - Defines which polygons are candidates for culling.
  37148. */
  37149. setCullFace( cullFace ) {
  37150. const { gl } = this;
  37151. if ( cullFace !== CullFaceNone ) {
  37152. this.enable( gl.CULL_FACE );
  37153. if ( cullFace !== this.currentCullFace ) {
  37154. if ( cullFace === CullFaceBack ) {
  37155. gl.cullFace( gl.BACK );
  37156. } else if ( cullFace === CullFaceFront ) {
  37157. gl.cullFace( gl.FRONT );
  37158. } else {
  37159. gl.cullFace( gl.FRONT_AND_BACK );
  37160. }
  37161. }
  37162. } else {
  37163. this.disable( gl.CULL_FACE );
  37164. }
  37165. this.currentCullFace = cullFace;
  37166. }
  37167. /**
  37168. * Specifies the width of line primitives.
  37169. *
  37170. * This method caches the state so `gl.lineWidth()` is only
  37171. * called when necessary.
  37172. *
  37173. * @param {Number} width - The line width.
  37174. */
  37175. setLineWidth( width ) {
  37176. const { currentLineWidth, gl } = this;
  37177. if ( width !== currentLineWidth ) {
  37178. gl.lineWidth( width );
  37179. this.currentLineWidth = width;
  37180. }
  37181. }
  37182. /**
  37183. * Defines the blending.
  37184. *
  37185. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  37186. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  37187. *
  37188. * @param {Number} blending - The blending type.
  37189. * @param {Number} blendEquation - The blending equation.
  37190. * @param {Number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  37191. * @param {Number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  37192. * @param {Number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  37193. * @param {Number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  37194. * @param {Number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  37195. * @param {Boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  37196. */
  37197. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  37198. const { gl } = this;
  37199. if ( blending === NoBlending ) {
  37200. if ( this.currentBlendingEnabled === true ) {
  37201. this.disable( gl.BLEND );
  37202. this.currentBlendingEnabled = false;
  37203. }
  37204. return;
  37205. }
  37206. if ( this.currentBlendingEnabled === false ) {
  37207. this.enable( gl.BLEND );
  37208. this.currentBlendingEnabled = true;
  37209. }
  37210. if ( blending !== CustomBlending ) {
  37211. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  37212. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  37213. gl.blendEquation( gl.FUNC_ADD );
  37214. this.currentBlendEquation = AddEquation;
  37215. this.currentBlendEquationAlpha = AddEquation;
  37216. }
  37217. if ( premultipliedAlpha ) {
  37218. switch ( blending ) {
  37219. case NormalBlending:
  37220. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  37221. break;
  37222. case AdditiveBlending:
  37223. gl.blendFunc( gl.ONE, gl.ONE );
  37224. break;
  37225. case SubtractiveBlending:
  37226. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  37227. break;
  37228. case MultiplyBlending:
  37229. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  37230. break;
  37231. default:
  37232. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  37233. break;
  37234. }
  37235. } else {
  37236. switch ( blending ) {
  37237. case NormalBlending:
  37238. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  37239. break;
  37240. case AdditiveBlending:
  37241. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  37242. break;
  37243. case SubtractiveBlending:
  37244. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  37245. break;
  37246. case MultiplyBlending:
  37247. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  37248. break;
  37249. default:
  37250. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  37251. break;
  37252. }
  37253. }
  37254. this.currentBlendSrc = null;
  37255. this.currentBlendDst = null;
  37256. this.currentBlendSrcAlpha = null;
  37257. this.currentBlendDstAlpha = null;
  37258. this.currentBlending = blending;
  37259. this.currentPremultipledAlpha = premultipliedAlpha;
  37260. }
  37261. return;
  37262. }
  37263. // custom blending
  37264. blendEquationAlpha = blendEquationAlpha || blendEquation;
  37265. blendSrcAlpha = blendSrcAlpha || blendSrc;
  37266. blendDstAlpha = blendDstAlpha || blendDst;
  37267. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  37268. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  37269. this.currentBlendEquation = blendEquation;
  37270. this.currentBlendEquationAlpha = blendEquationAlpha;
  37271. }
  37272. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  37273. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  37274. this.currentBlendSrc = blendSrc;
  37275. this.currentBlendDst = blendDst;
  37276. this.currentBlendSrcAlpha = blendSrcAlpha;
  37277. this.currentBlendDstAlpha = blendDstAlpha;
  37278. }
  37279. this.currentBlending = blending;
  37280. this.currentPremultipledAlpha = false;
  37281. }
  37282. /**
  37283. * Specifies whether colors can be written when rendering
  37284. * into a framebuffer or not.
  37285. *
  37286. * This method caches the state so `gl.colorMask()` is only
  37287. * called when necessary.
  37288. *
  37289. * @param {Boolean} colorMask - The color mask.
  37290. */
  37291. setColorMask( colorMask ) {
  37292. if ( this.currentColorMask !== colorMask ) {
  37293. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  37294. this.currentColorMask = colorMask;
  37295. }
  37296. }
  37297. /**
  37298. * Specifies whether the depth test is enabled or not.
  37299. *
  37300. * @param {Boolean} depthTest - Whether the depth test is enabled or not.
  37301. */
  37302. setDepthTest( depthTest ) {
  37303. const { gl } = this;
  37304. if ( depthTest ) {
  37305. this.enable( gl.DEPTH_TEST );
  37306. } else {
  37307. this.disable( gl.DEPTH_TEST );
  37308. }
  37309. }
  37310. /**
  37311. * Specifies whether depth values can be written when rendering
  37312. * into a framebuffer or not.
  37313. *
  37314. * This method caches the state so `gl.depthMask()` is only
  37315. * called when necessary.
  37316. *
  37317. * @param {Boolean} depthMask - The depth mask.
  37318. */
  37319. setDepthMask( depthMask ) {
  37320. if ( this.currentDepthMask !== depthMask ) {
  37321. this.gl.depthMask( depthMask );
  37322. this.currentDepthMask = depthMask;
  37323. }
  37324. }
  37325. /**
  37326. * Specifies the depth compare function.
  37327. *
  37328. * This method caches the state so `gl.depthFunc()` is only
  37329. * called when necessary.
  37330. *
  37331. * @param {Number} depthFunc - The depth compare function.
  37332. */
  37333. setDepthFunc( depthFunc ) {
  37334. if ( this.currentDepthFunc !== depthFunc ) {
  37335. const { gl } = this;
  37336. switch ( depthFunc ) {
  37337. case NeverDepth:
  37338. gl.depthFunc( gl.NEVER );
  37339. break;
  37340. case AlwaysDepth:
  37341. gl.depthFunc( gl.ALWAYS );
  37342. break;
  37343. case LessDepth:
  37344. gl.depthFunc( gl.LESS );
  37345. break;
  37346. case LessEqualDepth:
  37347. gl.depthFunc( gl.LEQUAL );
  37348. break;
  37349. case EqualDepth:
  37350. gl.depthFunc( gl.EQUAL );
  37351. break;
  37352. case GreaterEqualDepth:
  37353. gl.depthFunc( gl.GEQUAL );
  37354. break;
  37355. case GreaterDepth:
  37356. gl.depthFunc( gl.GREATER );
  37357. break;
  37358. case NotEqualDepth:
  37359. gl.depthFunc( gl.NOTEQUAL );
  37360. break;
  37361. default:
  37362. gl.depthFunc( gl.LEQUAL );
  37363. }
  37364. this.currentDepthFunc = depthFunc;
  37365. }
  37366. }
  37367. /**
  37368. * Specifies whether the stencil test is enabled or not.
  37369. *
  37370. * @param {Boolean} stencilTest - Whether the stencil test is enabled or not.
  37371. */
  37372. setStencilTest( stencilTest ) {
  37373. const { gl } = this;
  37374. if ( stencilTest ) {
  37375. this.enable( gl.STENCIL_TEST );
  37376. } else {
  37377. this.disable( gl.STENCIL_TEST );
  37378. }
  37379. }
  37380. /**
  37381. * Specifies whether stencil values can be written when rendering
  37382. * into a framebuffer or not.
  37383. *
  37384. * This method caches the state so `gl.stencilMask()` is only
  37385. * called when necessary.
  37386. *
  37387. * @param {Boolean} stencilMask - The stencil mask.
  37388. */
  37389. setStencilMask( stencilMask ) {
  37390. if ( this.currentStencilMask !== stencilMask ) {
  37391. this.gl.stencilMask( stencilMask );
  37392. this.currentStencilMask = stencilMask;
  37393. }
  37394. }
  37395. /**
  37396. * Specifies whether the stencil test functions.
  37397. *
  37398. * This method caches the state so `gl.stencilFunc()` is only
  37399. * called when necessary.
  37400. *
  37401. * @param {Number} stencilFunc - The stencil compare function.
  37402. * @param {Number} stencilRef - The reference value for the stencil test.
  37403. * @param {Number} stencilMask - A bit-wise mask that is used to AND the reference value and the stored stencil value when the test is done.
  37404. */
  37405. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  37406. if ( this.currentStencilFunc !== stencilFunc ||
  37407. this.currentStencilRef !== stencilRef ||
  37408. this.currentStencilFuncMask !== stencilMask ) {
  37409. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  37410. this.currentStencilFunc = stencilFunc;
  37411. this.currentStencilRef = stencilRef;
  37412. this.currentStencilFuncMask = stencilMask;
  37413. }
  37414. }
  37415. /**
  37416. * Specifies whether the stencil test operation.
  37417. *
  37418. * This method caches the state so `gl.stencilOp()` is only
  37419. * called when necessary.
  37420. *
  37421. * @param {Number} stencilFail - The function to use when the stencil test fails.
  37422. * @param {Number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  37423. * @param {Number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  37424. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  37425. */
  37426. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  37427. if ( this.currentStencilFail !== stencilFail ||
  37428. this.currentStencilZFail !== stencilZFail ||
  37429. this.currentStencilZPass !== stencilZPass ) {
  37430. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  37431. this.currentStencilFail = stencilFail;
  37432. this.currentStencilZFail = stencilZFail;
  37433. this.currentStencilZPass = stencilZPass;
  37434. }
  37435. }
  37436. /**
  37437. * Configures the WebGL state for the given material.
  37438. *
  37439. * @param {Material} material - The material to configure the state for.
  37440. * @param {Number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  37441. * @param {Number} hardwareClippingPlanes - The number of hardware clipping planes.
  37442. */
  37443. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  37444. const { gl } = this;
  37445. material.side === DoubleSide
  37446. ? this.disable( gl.CULL_FACE )
  37447. : this.enable( gl.CULL_FACE );
  37448. let flipSided = ( material.side === BackSide );
  37449. if ( frontFaceCW ) flipSided = ! flipSided;
  37450. this.setFlipSided( flipSided );
  37451. ( material.blending === NormalBlending && material.transparent === false )
  37452. ? this.setBlending( NoBlending )
  37453. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  37454. this.setDepthFunc( material.depthFunc );
  37455. this.setDepthTest( material.depthTest );
  37456. this.setDepthMask( material.depthWrite );
  37457. this.setColorMask( material.colorWrite );
  37458. const stencilWrite = material.stencilWrite;
  37459. this.setStencilTest( stencilWrite );
  37460. if ( stencilWrite ) {
  37461. this.setStencilMask( material.stencilWriteMask );
  37462. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  37463. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  37464. }
  37465. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  37466. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  37467. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  37468. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  37469. if ( hardwareClippingPlanes > 0 ) {
  37470. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  37471. const CLIP_DISTANCE0_WEBGL = 0x3000;
  37472. for ( let i = 0; i < 8; i ++ ) {
  37473. if ( i < hardwareClippingPlanes ) {
  37474. this.enable( CLIP_DISTANCE0_WEBGL + i );
  37475. } else {
  37476. this.disable( CLIP_DISTANCE0_WEBGL + i );
  37477. }
  37478. }
  37479. }
  37480. }
  37481. }
  37482. /**
  37483. * Specifies the polygon offset.
  37484. *
  37485. * This method caches the state so `gl.polygonOffset()` is only
  37486. * called when necessary.
  37487. *
  37488. * @param {Boolean} polygonOffset - Whether polygon offset is enabled or not.
  37489. * @param {Number} factor - The scale factor for the variable depth offset for each polygon.
  37490. * @param {Number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  37491. */
  37492. setPolygonOffset( polygonOffset, factor, units ) {
  37493. const { gl } = this;
  37494. if ( polygonOffset ) {
  37495. this.enable( gl.POLYGON_OFFSET_FILL );
  37496. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  37497. gl.polygonOffset( factor, units );
  37498. this.currentPolygonOffsetFactor = factor;
  37499. this.currentPolygonOffsetUnits = units;
  37500. }
  37501. } else {
  37502. this.disable( gl.POLYGON_OFFSET_FILL );
  37503. }
  37504. }
  37505. /**
  37506. * Defines the usage of the given WebGL program.
  37507. *
  37508. * This method caches the state so `gl.useProgram()` is only
  37509. * called when necessary.
  37510. *
  37511. * @param {WebGLProgram} program - The WebGL program to use.
  37512. * @return {Boolean} Whether a program change has been executed or not.
  37513. */
  37514. useProgram( program ) {
  37515. if ( this.currentProgram !== program ) {
  37516. this.gl.useProgram( program );
  37517. this.currentProgram = program;
  37518. return true;
  37519. }
  37520. return false;
  37521. }
  37522. // framebuffer
  37523. /**
  37524. * Binds the given framebuffer.
  37525. *
  37526. * This method caches the state so `gl.bindFramebuffer()` is only
  37527. * called when necessary.
  37528. *
  37529. * @param {Number} target - The binding point (target).
  37530. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  37531. * @return {Boolean} Whether a bind has been executed or not.
  37532. */
  37533. bindFramebuffer( target, framebuffer ) {
  37534. const { gl, currentBoundFramebuffers } = this;
  37535. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  37536. gl.bindFramebuffer( target, framebuffer );
  37537. currentBoundFramebuffers[ target ] = framebuffer;
  37538. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  37539. if ( target === gl.DRAW_FRAMEBUFFER ) {
  37540. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  37541. }
  37542. if ( target === gl.FRAMEBUFFER ) {
  37543. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  37544. }
  37545. return true;
  37546. }
  37547. return false;
  37548. }
  37549. /**
  37550. * Defines draw buffers to which fragment colors are written into.
  37551. * Configures the MRT setup of custom framebuffers.
  37552. *
  37553. * This method caches the state so `gl.drawBuffers()` is only
  37554. * called when necessary.
  37555. *
  37556. * @param {RenderContext} renderContext - The render context.
  37557. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  37558. */
  37559. drawBuffers( renderContext, framebuffer ) {
  37560. const { gl } = this;
  37561. let drawBuffers = [];
  37562. let needsUpdate = false;
  37563. if ( renderContext.textures !== null ) {
  37564. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  37565. if ( drawBuffers === undefined ) {
  37566. drawBuffers = [];
  37567. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  37568. }
  37569. const textures = renderContext.textures;
  37570. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  37571. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  37572. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  37573. }
  37574. drawBuffers.length = textures.length;
  37575. needsUpdate = true;
  37576. }
  37577. } else {
  37578. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  37579. drawBuffers[ 0 ] = gl.BACK;
  37580. needsUpdate = true;
  37581. }
  37582. }
  37583. if ( needsUpdate ) {
  37584. gl.drawBuffers( drawBuffers );
  37585. }
  37586. }
  37587. // texture
  37588. /**
  37589. * Makes the given texture unit active.
  37590. *
  37591. * This method caches the state so `gl.activeTexture()` is only
  37592. * called when necessary.
  37593. *
  37594. * @param {Number} webglSlot - The texture unit to make active.
  37595. */
  37596. activeTexture( webglSlot ) {
  37597. const { gl, currentTextureSlot, maxTextures } = this;
  37598. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  37599. if ( currentTextureSlot !== webglSlot ) {
  37600. gl.activeTexture( webglSlot );
  37601. this.currentTextureSlot = webglSlot;
  37602. }
  37603. }
  37604. /**
  37605. * Binds the given WebGL texture to a target.
  37606. *
  37607. * This method caches the state so `gl.bindTexture()` is only
  37608. * called when necessary.
  37609. *
  37610. * @param {Number} webglType - The binding point (target).
  37611. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  37612. * @param {Number} webglSlot - The texture.
  37613. */
  37614. bindTexture( webglType, webglTexture, webglSlot ) {
  37615. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  37616. if ( webglSlot === undefined ) {
  37617. if ( currentTextureSlot === null ) {
  37618. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  37619. } else {
  37620. webglSlot = currentTextureSlot;
  37621. }
  37622. }
  37623. let boundTexture = currentBoundTextures[ webglSlot ];
  37624. if ( boundTexture === undefined ) {
  37625. boundTexture = { type: undefined, texture: undefined };
  37626. currentBoundTextures[ webglSlot ] = boundTexture;
  37627. }
  37628. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  37629. if ( currentTextureSlot !== webglSlot ) {
  37630. gl.activeTexture( webglSlot );
  37631. this.currentTextureSlot = webglSlot;
  37632. }
  37633. gl.bindTexture( webglType, webglTexture );
  37634. boundTexture.type = webglType;
  37635. boundTexture.texture = webglTexture;
  37636. }
  37637. }
  37638. /**
  37639. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  37640. *
  37641. * This method caches the state so `gl.bindBufferBase()` is only
  37642. * called when necessary.
  37643. *
  37644. * @param {Number} target - The target for the bind operation.
  37645. * @param {Number} index - The index of the target.
  37646. * @param {WebGLBuffer} buffer - The WebGL buffer.
  37647. * @return {Boolean} Whether a bind has been executed or not.
  37648. */
  37649. bindBufferBase( target, index, buffer ) {
  37650. const { gl } = this;
  37651. const key = `${target}-${index}`;
  37652. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  37653. gl.bindBufferBase( target, index, buffer );
  37654. this.currentBoundBufferBases[ key ] = buffer;
  37655. return true;
  37656. }
  37657. return false;
  37658. }
  37659. /**
  37660. * Unbinds the current bound texture.
  37661. *
  37662. * This method caches the state so `gl.bindTexture()` is only
  37663. * called when necessary.
  37664. */
  37665. unbindTexture() {
  37666. const { gl, currentTextureSlot, currentBoundTextures } = this;
  37667. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  37668. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  37669. gl.bindTexture( boundTexture.type, null );
  37670. boundTexture.type = undefined;
  37671. boundTexture.texture = undefined;
  37672. }
  37673. }
  37674. }
  37675. /**
  37676. * A WebGL 2 backend utility module with common helpers.
  37677. *
  37678. * @private
  37679. */
  37680. class WebGLUtils {
  37681. /**
  37682. * Constructs a new utility object.
  37683. *
  37684. * @param {WebGLBackend} backend - The WebGL 2 backend.
  37685. */
  37686. constructor( backend ) {
  37687. /**
  37688. * A reference to the WebGL 2 backend.
  37689. *
  37690. * @type {WebGLBackend}
  37691. */
  37692. this.backend = backend;
  37693. /**
  37694. * A reference to the rendering context.
  37695. *
  37696. * @type {WebGL2RenderingContext}
  37697. */
  37698. this.gl = this.backend.gl;
  37699. /**
  37700. * A reference to a backend module holding extension-related
  37701. * utility functions.
  37702. *
  37703. * @type {WebGLExtensions}
  37704. */
  37705. this.extensions = backend.extensions;
  37706. }
  37707. /**
  37708. * Converts the given three.js constant into a WebGL constant.
  37709. * The method currently supports the conversion of texture formats
  37710. * and types.
  37711. *
  37712. * @param {Number} p - The three.js constant.
  37713. * @param {String} [colorSpace=NoColorSpace] - The color space.
  37714. * @return {Number} The corresponding WebGL constant.
  37715. */
  37716. convert( p, colorSpace = NoColorSpace ) {
  37717. const { gl, extensions } = this;
  37718. let extension;
  37719. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  37720. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  37721. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  37722. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  37723. if ( p === ByteType ) return gl.BYTE;
  37724. if ( p === ShortType ) return gl.SHORT;
  37725. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  37726. if ( p === IntType ) return gl.INT;
  37727. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  37728. if ( p === FloatType ) return gl.FLOAT;
  37729. if ( p === HalfFloatType ) {
  37730. return gl.HALF_FLOAT;
  37731. }
  37732. if ( p === AlphaFormat ) return gl.ALPHA;
  37733. if ( p === RGBFormat ) return gl.RGB;
  37734. if ( p === RGBAFormat ) return gl.RGBA;
  37735. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  37736. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  37737. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  37738. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  37739. // WebGL2 formats.
  37740. if ( p === RedFormat ) return gl.RED;
  37741. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  37742. if ( p === RGFormat ) return gl.RG;
  37743. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  37744. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  37745. // S3TC
  37746. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  37747. if ( colorSpace === SRGBColorSpace ) {
  37748. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  37749. if ( extension !== null ) {
  37750. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  37751. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  37752. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  37753. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  37754. } else {
  37755. return null;
  37756. }
  37757. } else {
  37758. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  37759. if ( extension !== null ) {
  37760. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  37761. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  37762. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  37763. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  37764. } else {
  37765. return null;
  37766. }
  37767. }
  37768. }
  37769. // PVRTC
  37770. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  37771. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  37772. if ( extension !== null ) {
  37773. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  37774. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  37775. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  37776. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  37777. } else {
  37778. return null;
  37779. }
  37780. }
  37781. // ETC
  37782. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  37783. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  37784. if ( extension !== null ) {
  37785. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  37786. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  37787. } else {
  37788. return null;
  37789. }
  37790. }
  37791. // ASTC
  37792. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  37793. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  37794. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  37795. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  37796. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  37797. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  37798. if ( extension !== null ) {
  37799. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  37800. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  37801. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  37802. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  37803. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  37804. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  37805. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  37806. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  37807. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  37808. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  37809. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  37810. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  37811. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  37812. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  37813. } else {
  37814. return null;
  37815. }
  37816. }
  37817. // BPTC
  37818. if ( p === RGBA_BPTC_Format ) {
  37819. extension = extensions.get( 'EXT_texture_compression_bptc' );
  37820. if ( extension !== null ) {
  37821. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  37822. } else {
  37823. return null;
  37824. }
  37825. }
  37826. // RGTC
  37827. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  37828. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  37829. if ( extension !== null ) {
  37830. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  37831. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  37832. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  37833. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  37834. } else {
  37835. return null;
  37836. }
  37837. }
  37838. //
  37839. if ( p === UnsignedInt248Type ) {
  37840. return gl.UNSIGNED_INT_24_8;
  37841. }
  37842. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  37843. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  37844. }
  37845. /**
  37846. * This method can be used to synchronize the CPU with the GPU by waiting until
  37847. * ongoing GPU commands have been completed.
  37848. *
  37849. * @private
  37850. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  37851. */
  37852. _clientWaitAsync() {
  37853. const { gl } = this;
  37854. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  37855. gl.flush();
  37856. return new Promise( ( resolve, reject ) => {
  37857. function test() {
  37858. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  37859. if ( res === gl.WAIT_FAILED ) {
  37860. gl.deleteSync( sync );
  37861. reject();
  37862. return;
  37863. }
  37864. if ( res === gl.TIMEOUT_EXPIRED ) {
  37865. requestAnimationFrame( test );
  37866. return;
  37867. }
  37868. gl.deleteSync( sync );
  37869. resolve();
  37870. }
  37871. test();
  37872. } );
  37873. }
  37874. }
  37875. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  37876. /**
  37877. * A WebGL 2 backend utility module for managing textures.
  37878. *
  37879. * @private
  37880. */
  37881. class WebGLTextureUtils {
  37882. /**
  37883. * Constructs a new utility object.
  37884. *
  37885. * @param {WebGLBackend} backend - The WebGL 2 backend.
  37886. */
  37887. constructor( backend ) {
  37888. /**
  37889. * A reference to the WebGL 2 backend.
  37890. *
  37891. * @type {WebGLBackend}
  37892. */
  37893. this.backend = backend;
  37894. /**
  37895. * A reference to the rendering context.
  37896. *
  37897. * @type {WebGL2RenderingContext}
  37898. */
  37899. this.gl = backend.gl;
  37900. /**
  37901. * A reference to a backend module holding extension-related
  37902. * utility functions.
  37903. *
  37904. * @type {WebGLExtensions}
  37905. */
  37906. this.extensions = backend.extensions;
  37907. /**
  37908. * A dictionary for managing default textures. The key
  37909. * is the binding point (target), the value the WEbGL texture object.
  37910. *
  37911. * @type {Object<GLenum,WebGLTexture>}
  37912. */
  37913. this.defaultTextures = {};
  37914. if ( initialized === false ) {
  37915. this._init();
  37916. initialized = true;
  37917. }
  37918. }
  37919. /**
  37920. * Inits the state of the utility.
  37921. *
  37922. * @private
  37923. */
  37924. _init() {
  37925. const gl = this.gl;
  37926. // Store only WebGL constants here.
  37927. wrappingToGL = {
  37928. [ RepeatWrapping ]: gl.REPEAT,
  37929. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  37930. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  37931. };
  37932. filterToGL = {
  37933. [ NearestFilter ]: gl.NEAREST,
  37934. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  37935. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  37936. [ LinearFilter ]: gl.LINEAR,
  37937. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  37938. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  37939. };
  37940. compareToGL = {
  37941. [ NeverCompare ]: gl.NEVER,
  37942. [ AlwaysCompare ]: gl.ALWAYS,
  37943. [ LessCompare ]: gl.LESS,
  37944. [ LessEqualCompare ]: gl.LEQUAL,
  37945. [ EqualCompare ]: gl.EQUAL,
  37946. [ GreaterEqualCompare ]: gl.GEQUAL,
  37947. [ GreaterCompare ]: gl.GREATER,
  37948. [ NotEqualCompare ]: gl.NOTEQUAL
  37949. };
  37950. }
  37951. /**
  37952. * Returns the native texture type for the given texture.
  37953. *
  37954. * @param {Texture} texture - The texture.
  37955. * @return {GLenum} The native texture type.
  37956. */
  37957. getGLTextureType( texture ) {
  37958. const { gl } = this;
  37959. let glTextureType;
  37960. if ( texture.isCubeTexture === true ) {
  37961. glTextureType = gl.TEXTURE_CUBE_MAP;
  37962. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  37963. glTextureType = gl.TEXTURE_2D_ARRAY;
  37964. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  37965. glTextureType = gl.TEXTURE_3D;
  37966. } else {
  37967. glTextureType = gl.TEXTURE_2D;
  37968. }
  37969. return glTextureType;
  37970. }
  37971. /**
  37972. * Returns the native texture type for the given texture.
  37973. *
  37974. * @param {String?} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  37975. * @param {GLenum} glFormat - The WebGL format.
  37976. * @param {GLenum} glType - The WebGL type.
  37977. * @param {String} colorSpace - The texture's color space.
  37978. * @param {Boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  37979. * @return {GLenum} The internal format.
  37980. */
  37981. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  37982. const { gl, extensions } = this;
  37983. if ( internalFormatName !== null ) {
  37984. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  37985. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  37986. }
  37987. let internalFormat = glFormat;
  37988. if ( glFormat === gl.RED ) {
  37989. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  37990. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  37991. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  37992. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  37993. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  37994. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  37995. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  37996. if ( glType === gl.INT ) internalFormat = gl.R32I;
  37997. }
  37998. if ( glFormat === gl.RED_INTEGER ) {
  37999. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  38000. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  38001. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  38002. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  38003. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  38004. if ( glType === gl.INT ) internalFormat = gl.R32I;
  38005. }
  38006. if ( glFormat === gl.RG ) {
  38007. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  38008. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  38009. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  38010. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  38011. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  38012. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  38013. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  38014. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  38015. }
  38016. if ( glFormat === gl.RG_INTEGER ) {
  38017. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  38018. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  38019. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  38020. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  38021. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  38022. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  38023. }
  38024. if ( glFormat === gl.RGB ) {
  38025. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  38026. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  38027. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  38028. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  38029. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  38030. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  38031. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  38032. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  38033. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  38034. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  38035. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  38036. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  38037. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  38038. }
  38039. if ( glFormat === gl.RGB_INTEGER ) {
  38040. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  38041. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  38042. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  38043. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  38044. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  38045. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  38046. }
  38047. if ( glFormat === gl.RGBA ) {
  38048. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  38049. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  38050. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  38051. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  38052. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  38053. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  38054. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  38055. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  38056. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  38057. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  38058. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  38059. }
  38060. if ( glFormat === gl.RGBA_INTEGER ) {
  38061. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  38062. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  38063. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  38064. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  38065. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  38066. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  38067. }
  38068. if ( glFormat === gl.DEPTH_COMPONENT ) {
  38069. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  38070. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  38071. }
  38072. if ( glFormat === gl.DEPTH_STENCIL ) {
  38073. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  38074. }
  38075. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  38076. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  38077. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  38078. extensions.get( 'EXT_color_buffer_float' );
  38079. }
  38080. return internalFormat;
  38081. }
  38082. /**
  38083. * Sets the texture parameters for the given texture.
  38084. *
  38085. * @param {GLenum} textureType - The texture type.
  38086. * @param {Texture} texture - The texture.
  38087. */
  38088. setTextureParameters( textureType, texture ) {
  38089. const { gl, extensions, backend } = this;
  38090. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  38091. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  38092. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  38093. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  38094. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  38095. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  38096. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  38097. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  38098. }
  38099. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  38100. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  38101. // follow WebGPU backend mapping for texture filtering
  38102. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  38103. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  38104. if ( texture.compareFunction ) {
  38105. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  38106. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  38107. }
  38108. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  38109. if ( texture.magFilter === NearestFilter ) return;
  38110. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  38111. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  38112. if ( texture.anisotropy > 1 ) {
  38113. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  38114. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  38115. }
  38116. }
  38117. }
  38118. /**
  38119. * Creates a default texture for the given texture that can be used
  38120. * as a placeholder until the actual texture is ready for usage.
  38121. *
  38122. * @param {Texture} texture - The texture to create a default texture for.
  38123. */
  38124. createDefaultTexture( texture ) {
  38125. const { gl, backend, defaultTextures } = this;
  38126. const glTextureType = this.getGLTextureType( texture );
  38127. let textureGPU = defaultTextures[ glTextureType ];
  38128. if ( textureGPU === undefined ) {
  38129. textureGPU = gl.createTexture();
  38130. backend.state.bindTexture( glTextureType, textureGPU );
  38131. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  38132. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  38133. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  38134. defaultTextures[ glTextureType ] = textureGPU;
  38135. }
  38136. backend.set( texture, {
  38137. textureGPU,
  38138. glTextureType,
  38139. isDefault: true
  38140. } );
  38141. }
  38142. /**
  38143. * Defines a texture on the GPU for the given texture object.
  38144. *
  38145. * @param {Texture} texture - The texture.
  38146. * @param {Object} [options={}] - Optional configuration parameter.
  38147. * @return {undefined}
  38148. */
  38149. createTexture( texture, options ) {
  38150. const { gl, backend } = this;
  38151. const { levels, width, height, depth } = options;
  38152. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  38153. const glType = backend.utils.convert( texture.type );
  38154. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  38155. const textureGPU = gl.createTexture();
  38156. const glTextureType = this.getGLTextureType( texture );
  38157. backend.state.bindTexture( glTextureType, textureGPU );
  38158. this.setTextureParameters( glTextureType, texture );
  38159. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  38160. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  38161. } else if ( texture.isData3DTexture ) {
  38162. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  38163. } else if ( ! texture.isVideoTexture ) {
  38164. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  38165. }
  38166. backend.set( texture, {
  38167. textureGPU,
  38168. glTextureType,
  38169. glFormat,
  38170. glType,
  38171. glInternalFormat
  38172. } );
  38173. }
  38174. /**
  38175. * Uploads texture buffer data to the GPU memory.
  38176. *
  38177. * @param {WebGLBuffer} buffer - The buffer data.
  38178. * @param {Texture} texture - The texture,
  38179. */
  38180. copyBufferToTexture( buffer, texture ) {
  38181. const { gl, backend } = this;
  38182. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  38183. const { width, height } = texture.source.data;
  38184. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  38185. backend.state.bindTexture( glTextureType, textureGPU );
  38186. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  38187. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  38188. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  38189. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  38190. backend.state.unbindTexture();
  38191. // debug
  38192. // const framebuffer = gl.createFramebuffer();
  38193. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  38194. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  38195. // const readout = new Float32Array( width * height * 4 );
  38196. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  38197. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  38198. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  38199. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  38200. // console.log( readout );
  38201. }
  38202. /**
  38203. * Uploads the updated texture data to the GPU.
  38204. *
  38205. * @param {Texture} texture - The texture.
  38206. * @param {Object} [options={}] - Optional configuration parameter.
  38207. */
  38208. updateTexture( texture, options ) {
  38209. const { gl } = this;
  38210. const { width, height } = options;
  38211. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  38212. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  38213. return;
  38214. const getImage = ( source ) => {
  38215. if ( source.isDataTexture ) {
  38216. return source.image.data;
  38217. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  38218. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  38219. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  38220. source instanceof OffscreenCanvas ) {
  38221. return source;
  38222. }
  38223. return source.data;
  38224. };
  38225. this.backend.state.bindTexture( glTextureType, textureGPU );
  38226. this.setTextureParameters( glTextureType, texture );
  38227. if ( texture.isCompressedTexture ) {
  38228. const mipmaps = texture.mipmaps;
  38229. const image = options.image;
  38230. for ( let i = 0; i < mipmaps.length; i ++ ) {
  38231. const mipmap = mipmaps[ i ];
  38232. if ( texture.isCompressedArrayTexture ) {
  38233. if ( texture.format !== gl.RGBA ) {
  38234. if ( glFormat !== null ) {
  38235. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  38236. } else {
  38237. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  38238. }
  38239. } else {
  38240. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  38241. }
  38242. } else {
  38243. if ( glFormat !== null ) {
  38244. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  38245. } else {
  38246. console.warn( 'Unsupported compressed texture format' );
  38247. }
  38248. }
  38249. }
  38250. } else if ( texture.isCubeTexture ) {
  38251. const images = options.images;
  38252. for ( let i = 0; i < 6; i ++ ) {
  38253. const image = getImage( images[ i ] );
  38254. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  38255. }
  38256. } else if ( texture.isDataArrayTexture ) {
  38257. const image = options.image;
  38258. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  38259. } else if ( texture.isData3DTexture ) {
  38260. const image = options.image;
  38261. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  38262. } else if ( texture.isVideoTexture ) {
  38263. texture.update();
  38264. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  38265. } else {
  38266. const image = getImage( options.image );
  38267. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  38268. }
  38269. }
  38270. /**
  38271. * Generates mipmaps for the given texture.
  38272. *
  38273. * @param {Texture} texture - The texture.
  38274. */
  38275. generateMipmaps( texture ) {
  38276. const { gl, backend } = this;
  38277. const { textureGPU, glTextureType } = backend.get( texture );
  38278. backend.state.bindTexture( glTextureType, textureGPU );
  38279. gl.generateMipmap( glTextureType );
  38280. }
  38281. /**
  38282. * Deallocates the render buffers of the given render target.
  38283. *
  38284. * @param {RenderTarget} renderTarget - The render target.
  38285. */
  38286. deallocateRenderBuffers( renderTarget ) {
  38287. const { gl, backend } = this;
  38288. // remove framebuffer reference
  38289. if ( renderTarget ) {
  38290. const renderContextData = backend.get( renderTarget );
  38291. renderContextData.renderBufferStorageSetup = undefined;
  38292. if ( renderContextData.framebuffers ) {
  38293. for ( const cacheKey in renderContextData.framebuffers ) {
  38294. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  38295. }
  38296. delete renderContextData.framebuffers;
  38297. }
  38298. if ( renderContextData.depthRenderbuffer ) {
  38299. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  38300. delete renderContextData.depthRenderbuffer;
  38301. }
  38302. if ( renderContextData.stencilRenderbuffer ) {
  38303. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  38304. delete renderContextData.stencilRenderbuffer;
  38305. }
  38306. if ( renderContextData.msaaFrameBuffer ) {
  38307. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  38308. delete renderContextData.msaaFrameBuffer;
  38309. }
  38310. if ( renderContextData.msaaRenderbuffers ) {
  38311. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  38312. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  38313. }
  38314. delete renderContextData.msaaRenderbuffers;
  38315. }
  38316. }
  38317. }
  38318. /**
  38319. * Destroys the GPU data for the given texture object.
  38320. *
  38321. * @param {Texture} texture - The texture.
  38322. */
  38323. destroyTexture( texture ) {
  38324. const { gl, backend } = this;
  38325. const { textureGPU, renderTarget } = backend.get( texture );
  38326. this.deallocateRenderBuffers( renderTarget );
  38327. gl.deleteTexture( textureGPU );
  38328. backend.delete( texture );
  38329. }
  38330. /**
  38331. * Copies data of the given source texture to the given destination texture.
  38332. *
  38333. * @param {Texture} srcTexture - The source texture.
  38334. * @param {Texture} dstTexture - The destination texture.
  38335. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  38336. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  38337. * @param {Number} [level=0] - The mip level to copy.
  38338. */
  38339. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  38340. const { gl, backend } = this;
  38341. const { state } = this.backend;
  38342. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  38343. let width, height, minX, minY;
  38344. let dstX, dstY;
  38345. if ( srcRegion !== null ) {
  38346. width = srcRegion.max.x - srcRegion.min.x;
  38347. height = srcRegion.max.y - srcRegion.min.y;
  38348. minX = srcRegion.min.x;
  38349. minY = srcRegion.min.y;
  38350. } else {
  38351. width = srcTexture.image.width;
  38352. height = srcTexture.image.height;
  38353. minX = 0;
  38354. minY = 0;
  38355. }
  38356. if ( dstPosition !== null ) {
  38357. dstX = dstPosition.x;
  38358. dstY = dstPosition.y;
  38359. } else {
  38360. dstX = 0;
  38361. dstY = 0;
  38362. }
  38363. state.bindTexture( glTextureType, dstTextureGPU );
  38364. // As another texture upload may have changed pixelStorei
  38365. // parameters, make sure they are correct for the dstTexture
  38366. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  38367. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  38368. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  38369. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  38370. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  38371. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  38372. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  38373. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  38374. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  38375. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  38376. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  38377. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  38378. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  38379. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  38380. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  38381. const srcTextureData = backend.get( srcTexture );
  38382. const dstTextureData = backend.get( dstTexture );
  38383. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  38384. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  38385. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  38386. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  38387. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  38388. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  38389. let mask = gl.COLOR_BUFFER_BIT;
  38390. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  38391. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  38392. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  38393. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  38394. } else {
  38395. if ( srcTexture.isDataTexture ) {
  38396. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  38397. } else {
  38398. if ( srcTexture.isCompressedTexture ) {
  38399. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  38400. } else {
  38401. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  38402. }
  38403. }
  38404. }
  38405. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  38406. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  38407. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  38408. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  38409. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  38410. // Generate mipmaps only when copying level 0
  38411. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  38412. state.unbindTexture();
  38413. }
  38414. /**
  38415. * Copies the current bound framebuffer to the given texture.
  38416. *
  38417. * @param {Texture} texture - The destination texture.
  38418. * @param {RenderContext} renderContext - The render context.
  38419. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  38420. */
  38421. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  38422. const { gl } = this;
  38423. const { state } = this.backend;
  38424. const { textureGPU } = this.backend.get( texture );
  38425. const { x, y, z: width, w: height } = rectangle;
  38426. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  38427. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  38428. if ( requireDrawFrameBuffer ) {
  38429. const partial = ( x !== 0 || y !== 0 );
  38430. let mask;
  38431. let attachment;
  38432. if ( texture.isDepthTexture === true ) {
  38433. mask = gl.DEPTH_BUFFER_BIT;
  38434. attachment = gl.DEPTH_ATTACHMENT;
  38435. if ( renderContext.stencil ) {
  38436. mask |= gl.STENCIL_BUFFER_BIT;
  38437. }
  38438. } else {
  38439. mask = gl.COLOR_BUFFER_BIT;
  38440. attachment = gl.COLOR_ATTACHMENT0;
  38441. }
  38442. if ( partial ) {
  38443. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  38444. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  38445. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  38446. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  38447. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  38448. const flippedY = srcHeight - y - height;
  38449. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  38450. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  38451. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  38452. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  38453. state.unbindTexture();
  38454. } else {
  38455. const fb = gl.createFramebuffer();
  38456. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  38457. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  38458. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  38459. gl.deleteFramebuffer( fb );
  38460. }
  38461. } else {
  38462. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  38463. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  38464. state.unbindTexture();
  38465. }
  38466. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  38467. this.backend._setFramebuffer( renderContext );
  38468. }
  38469. /**
  38470. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  38471. *
  38472. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  38473. * @param {RenderContext} renderContext - The render context.
  38474. */
  38475. setupRenderBufferStorage( renderbuffer, renderContext ) {
  38476. const { gl } = this;
  38477. const renderTarget = renderContext.renderTarget;
  38478. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  38479. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  38480. if ( depthBuffer && ! stencilBuffer ) {
  38481. let glInternalFormat = gl.DEPTH_COMPONENT24;
  38482. if ( samples > 0 ) {
  38483. if ( depthTexture && depthTexture.isDepthTexture ) {
  38484. if ( depthTexture.type === gl.FLOAT ) {
  38485. glInternalFormat = gl.DEPTH_COMPONENT32F;
  38486. }
  38487. }
  38488. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  38489. } else {
  38490. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  38491. }
  38492. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  38493. } else if ( depthBuffer && stencilBuffer ) {
  38494. if ( samples > 0 ) {
  38495. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  38496. } else {
  38497. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  38498. }
  38499. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  38500. }
  38501. }
  38502. /**
  38503. * Returns texture data as a typed array.
  38504. *
  38505. * @async
  38506. * @param {Texture} texture - The texture to copy.
  38507. * @param {Number} x - The x coordinate of the copy origin.
  38508. * @param {Number} y - The y coordinate of the copy origin.
  38509. * @param {Number} width - The width of the copy.
  38510. * @param {Number} height - The height of the copy.
  38511. * @param {Number} faceIndex - The face index.
  38512. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  38513. */
  38514. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  38515. const { backend, gl } = this;
  38516. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  38517. const fb = gl.createFramebuffer();
  38518. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  38519. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  38520. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  38521. const typedArrayType = this._getTypedArrayType( glType );
  38522. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  38523. const elementCount = width * height;
  38524. const byteLength = elementCount * bytesPerTexel;
  38525. const buffer = gl.createBuffer();
  38526. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  38527. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  38528. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  38529. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  38530. await backend.utils._clientWaitAsync();
  38531. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  38532. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  38533. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  38534. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  38535. gl.deleteFramebuffer( fb );
  38536. return dstBuffer;
  38537. }
  38538. /**
  38539. * Returns the corresponding typed array type for the given WebGL data type.
  38540. *
  38541. * @private
  38542. * @param {GLenum} glType - The WebGL data type.
  38543. * @return {TypedArray.constructor} The typed array type.
  38544. */
  38545. _getTypedArrayType( glType ) {
  38546. const { gl } = this;
  38547. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  38548. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  38549. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  38550. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  38551. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  38552. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  38553. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  38554. if ( glType === gl.FLOAT ) return Float32Array;
  38555. throw new Error( `Unsupported WebGL type: ${glType}` );
  38556. }
  38557. /**
  38558. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  38559. *
  38560. * @private
  38561. * @param {GLenum} glType - The WebGL data type.
  38562. * @param {GLenum} glFormat - The WebGL texture format.
  38563. * @return {Number} The bytes-per-texel.
  38564. */
  38565. _getBytesPerTexel( glType, glFormat ) {
  38566. const { gl } = this;
  38567. let bytesPerComponent = 0;
  38568. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  38569. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  38570. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  38571. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  38572. glType === gl.UNSIGNED_SHORT ||
  38573. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  38574. if ( glType === gl.UNSIGNED_INT ||
  38575. glType === gl.FLOAT ) bytesPerComponent = 4;
  38576. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  38577. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  38578. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  38579. }
  38580. }
  38581. /**
  38582. * A WebGL 2 backend utility module for managing extensions.
  38583. *
  38584. * @private
  38585. */
  38586. class WebGLExtensions {
  38587. /**
  38588. * Constructs a new utility object.
  38589. *
  38590. * @param {WebGLBackend} backend - The WebGL 2 backend.
  38591. */
  38592. constructor( backend ) {
  38593. /**
  38594. * A reference to the WebGL 2 backend.
  38595. *
  38596. * @type {WebGLBackend}
  38597. */
  38598. this.backend = backend;
  38599. /**
  38600. * A reference to the rendering context.
  38601. *
  38602. * @type {WebGL2RenderingContext}
  38603. */
  38604. this.gl = this.backend.gl;
  38605. /**
  38606. * A list with all the supported WebGL extensions.
  38607. *
  38608. * @type {Array<String>}
  38609. */
  38610. this.availableExtensions = this.gl.getSupportedExtensions();
  38611. /**
  38612. * A dictionary with requested WebGL extensions.
  38613. * The key is the name of the extension, the value
  38614. * the requested extension object.
  38615. *
  38616. * @type {Object<String,Object>}
  38617. */
  38618. this.extensions = {};
  38619. }
  38620. /**
  38621. * Returns the extension object for the given extension name.
  38622. *
  38623. * @param {String} name - The extension name.
  38624. * @return {Object} The extension object.
  38625. */
  38626. get( name ) {
  38627. let extension = this.extensions[ name ];
  38628. if ( extension === undefined ) {
  38629. extension = this.gl.getExtension( name );
  38630. this.extensions[ name ] = extension;
  38631. }
  38632. return extension;
  38633. }
  38634. /**
  38635. * Returns `true` if the requested extension is available.
  38636. *
  38637. * @param {String} name - The extension name.
  38638. * @return {Boolean} Whether the given extension is available or not.
  38639. */
  38640. has( name ) {
  38641. return this.availableExtensions.includes( name );
  38642. }
  38643. }
  38644. /**
  38645. * A WebGL 2 backend utility module for managing the device's capabilities.
  38646. *
  38647. * @private
  38648. */
  38649. class WebGLCapabilities {
  38650. /**
  38651. * Constructs a new utility object.
  38652. *
  38653. * @param {WebGLBackend} backend - The WebGL 2 backend.
  38654. */
  38655. constructor( backend ) {
  38656. /**
  38657. * A reference to the WebGL 2 backend.
  38658. *
  38659. * @type {WebGLBackend}
  38660. */
  38661. this.backend = backend;
  38662. /**
  38663. * This value holds the cached max anisotropy value.
  38664. *
  38665. * @type {Number?}
  38666. * @default null
  38667. */
  38668. this.maxAnisotropy = null;
  38669. }
  38670. /**
  38671. * Returns the maximum anisotropy texture filtering value. This value
  38672. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  38673. * WebGL extension.
  38674. *
  38675. * @return {Number} The maximum anisotropy texture filtering value.
  38676. */
  38677. getMaxAnisotropy() {
  38678. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  38679. const gl = this.backend.gl;
  38680. const extensions = this.backend.extensions;
  38681. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  38682. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  38683. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  38684. } else {
  38685. this.maxAnisotropy = 0;
  38686. }
  38687. return this.maxAnisotropy;
  38688. }
  38689. }
  38690. const GLFeatureName = {
  38691. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  38692. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  38693. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  38694. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  38695. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  38696. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  38697. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  38698. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  38699. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  38700. };
  38701. class WebGLBufferRenderer {
  38702. constructor( backend ) {
  38703. this.gl = backend.gl;
  38704. this.extensions = backend.extensions;
  38705. this.info = backend.renderer.info;
  38706. this.mode = null;
  38707. this.index = 0;
  38708. this.type = null;
  38709. this.object = null;
  38710. }
  38711. render( start, count ) {
  38712. const { gl, mode, object, type, info, index } = this;
  38713. if ( index !== 0 ) {
  38714. gl.drawElements( mode, count, type, start );
  38715. } else {
  38716. gl.drawArrays( mode, start, count );
  38717. }
  38718. info.update( object, count, mode, 1 );
  38719. }
  38720. renderInstances( start, count, primcount ) {
  38721. const { gl, mode, type, index, object, info } = this;
  38722. if ( primcount === 0 ) return;
  38723. if ( index !== 0 ) {
  38724. gl.drawElementsInstanced( mode, count, type, start, primcount );
  38725. } else {
  38726. gl.drawArraysInstanced( mode, start, count, primcount );
  38727. }
  38728. info.update( object, count, mode, primcount );
  38729. }
  38730. renderMultiDraw( starts, counts, drawCount ) {
  38731. const { extensions, mode, object, info } = this;
  38732. if ( drawCount === 0 ) return;
  38733. const extension = extensions.get( 'WEBGL_multi_draw' );
  38734. if ( extension === null ) {
  38735. for ( let i = 0; i < drawCount; i ++ ) {
  38736. this.render( starts[ i ], counts[ i ] );
  38737. }
  38738. } else {
  38739. if ( this.index !== 0 ) {
  38740. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  38741. } else {
  38742. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  38743. }
  38744. let elementCount = 0;
  38745. for ( let i = 0; i < drawCount; i ++ ) {
  38746. elementCount += counts[ i ];
  38747. }
  38748. info.update( object, elementCount, mode, 1 );
  38749. }
  38750. }
  38751. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  38752. const { extensions, mode, object, info } = this;
  38753. if ( drawCount === 0 ) return;
  38754. const extension = extensions.get( 'WEBGL_multi_draw' );
  38755. if ( extension === null ) {
  38756. for ( let i = 0; i < drawCount; i ++ ) {
  38757. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  38758. }
  38759. } else {
  38760. if ( this.index !== 0 ) {
  38761. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  38762. } else {
  38763. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  38764. }
  38765. let elementCount = 0;
  38766. for ( let i = 0; i < drawCount; i ++ ) {
  38767. elementCount += counts[ i ] * primcount[ i ];
  38768. }
  38769. info.update( object, elementCount, mode, 1 );
  38770. }
  38771. }
  38772. //
  38773. }
  38774. /**
  38775. * A backend implementation targeting WebGL 2.
  38776. *
  38777. * @private
  38778. * @augments Backend
  38779. */
  38780. class WebGLBackend extends Backend {
  38781. /**
  38782. * Constructs a new WebGPU backend.
  38783. *
  38784. * @param {Object} parameters - The configuration parameter.
  38785. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  38786. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  38787. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  38788. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  38789. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  38790. * @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.
  38791. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  38792. * @param {WebGL2RenderingContext} [parameters.context=undefined] - A WebGL 2 rendering context.
  38793. */
  38794. constructor( parameters = {} ) {
  38795. super( parameters );
  38796. /**
  38797. * This flag can be used for type testing.
  38798. *
  38799. * @type {Boolean}
  38800. * @readonly
  38801. * @default true
  38802. */
  38803. this.isWebGLBackend = true;
  38804. /**
  38805. * A reference to a backend module holding shader attribute-related
  38806. * utility functions.
  38807. *
  38808. * @type {WebGLAttributeUtils?}
  38809. * @default null
  38810. */
  38811. this.attributeUtils = null;
  38812. /**
  38813. * A reference to a backend module holding extension-related
  38814. * utility functions.
  38815. *
  38816. * @type {WebGLExtensions?}
  38817. * @default null
  38818. */
  38819. this.extensions = null;
  38820. /**
  38821. * A reference to a backend module holding capability-related
  38822. * utility functions.
  38823. *
  38824. * @type {WebGLCapabilities?}
  38825. * @default null
  38826. */
  38827. this.capabilities = null;
  38828. /**
  38829. * A reference to a backend module holding texture-related
  38830. * utility functions.
  38831. *
  38832. * @type {WebGLTextureUtils?}
  38833. * @default null
  38834. */
  38835. this.textureUtils = null;
  38836. /**
  38837. * A reference to a backend module holding renderer-related
  38838. * utility functions.
  38839. *
  38840. * @type {WebGLBufferRenderer?}
  38841. * @default null
  38842. */
  38843. this.bufferRenderer = null;
  38844. /**
  38845. * A reference to the rendering context.
  38846. *
  38847. * @type {WebGL2RenderingContext?}
  38848. * @default null
  38849. */
  38850. this.gl = null;
  38851. /**
  38852. * A reference to a backend module holding state-related
  38853. * utility functions.
  38854. *
  38855. * @type {WebGLState?}
  38856. * @default null
  38857. */
  38858. this.state = null;
  38859. /**
  38860. * A reference to a backend module holding common
  38861. * utility functions.
  38862. *
  38863. * @type {WebGLUtils?}
  38864. * @default null
  38865. */
  38866. this.utils = null;
  38867. /**
  38868. * Dictionary for caching VAOs.
  38869. *
  38870. * @type {Object<String,WebGLVertexArrayObject>}
  38871. */
  38872. this.vaoCache = {};
  38873. /**
  38874. * Dictionary for caching transform feedback objects.
  38875. *
  38876. * @type {Object<String,WebGLTransformFeedback>}
  38877. */
  38878. this.transformFeedbackCache = {};
  38879. /**
  38880. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  38881. * Only relevant when using compute shaders.
  38882. *
  38883. * @type {Boolean}
  38884. * @default false
  38885. */
  38886. this.discard = false;
  38887. /**
  38888. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  38889. * device does not support the extension.
  38890. *
  38891. * @type {EXTDisjointTimerQueryWebGL2?}
  38892. * @default null
  38893. */
  38894. this.disjoint = null;
  38895. /**
  38896. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  38897. * device does not support the extension.
  38898. *
  38899. * @type {KHRParallelShaderCompile?}
  38900. * @default null
  38901. */
  38902. this.parallel = null;
  38903. /**
  38904. * Whether to track timestamps with a Timestamp Query API or not.
  38905. *
  38906. * @type {Boolean}
  38907. * @default false
  38908. */
  38909. this.trackTimestamp = ( parameters.trackTimestamp === true );
  38910. /**
  38911. * A reference to the current render context.
  38912. *
  38913. * @private
  38914. * @type {RenderContext}
  38915. * @default null
  38916. */
  38917. this._currentContext = null;
  38918. /**
  38919. * A unique collection of bindings.
  38920. *
  38921. * @private
  38922. * @type {WeakSet}
  38923. */
  38924. this._knownBindings = new WeakSet();
  38925. }
  38926. /**
  38927. * Initializes the backend so it is ready for usage.
  38928. *
  38929. * @param {Renderer} renderer - The renderer.
  38930. */
  38931. init( renderer ) {
  38932. super.init( renderer );
  38933. //
  38934. const parameters = this.parameters;
  38935. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  38936. function onContextLost( event ) {
  38937. event.preventDefault();
  38938. const contextLossInfo = {
  38939. api: 'WebGL',
  38940. message: event.statusMessage || 'Unknown reason',
  38941. reason: null,
  38942. originalEvent: event
  38943. };
  38944. renderer.onDeviceLost( contextLossInfo );
  38945. }
  38946. this._onContextLost = onContextLost;
  38947. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  38948. this.gl = glContext;
  38949. this.extensions = new WebGLExtensions( this );
  38950. this.capabilities = new WebGLCapabilities( this );
  38951. this.attributeUtils = new WebGLAttributeUtils( this );
  38952. this.textureUtils = new WebGLTextureUtils( this );
  38953. this.bufferRenderer = new WebGLBufferRenderer( this );
  38954. this.state = new WebGLState( this );
  38955. this.utils = new WebGLUtils( this );
  38956. this.extensions.get( 'EXT_color_buffer_float' );
  38957. this.extensions.get( 'WEBGL_clip_cull_distance' );
  38958. this.extensions.get( 'OES_texture_float_linear' );
  38959. this.extensions.get( 'EXT_color_buffer_half_float' );
  38960. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  38961. this.extensions.get( 'WEBGL_render_shared_exponent' );
  38962. this.extensions.get( 'WEBGL_multi_draw' );
  38963. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  38964. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  38965. }
  38966. /**
  38967. * The coordinate system of the backend.
  38968. *
  38969. * @type {Number}
  38970. * @readonly
  38971. */
  38972. get coordinateSystem() {
  38973. return WebGLCoordinateSystem;
  38974. }
  38975. /**
  38976. * This method performs a readback operation by moving buffer data from
  38977. * a storage buffer attribute from the GPU to the CPU.
  38978. *
  38979. * @async
  38980. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  38981. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  38982. */
  38983. async getArrayBufferAsync( attribute ) {
  38984. return await this.attributeUtils.getArrayBufferAsync( attribute );
  38985. }
  38986. /**
  38987. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  38988. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  38989. *
  38990. * @async
  38991. * @return {Promise} A Promise that resolves when synchronization has been finished.
  38992. */
  38993. async waitForGPU() {
  38994. await this.utils._clientWaitAsync();
  38995. }
  38996. /**
  38997. * Inits a time stamp query for the given render context.
  38998. *
  38999. * @param {RenderContext} renderContext - The render context.
  39000. */
  39001. initTimestampQuery( renderContext ) {
  39002. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  39003. const renderContextData = this.get( renderContext );
  39004. if ( this.queryRunning ) {
  39005. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  39006. renderContextData.queryQueue.push( renderContext );
  39007. return;
  39008. }
  39009. if ( renderContextData.activeQuery ) {
  39010. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  39011. renderContextData.activeQuery = null;
  39012. }
  39013. renderContextData.activeQuery = this.gl.createQuery();
  39014. if ( renderContextData.activeQuery !== null ) {
  39015. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  39016. this.queryRunning = true;
  39017. }
  39018. }
  39019. // timestamp utils
  39020. /**
  39021. * Prepares the timestamp buffer.
  39022. *
  39023. * @param {RenderContext} renderContext - The render context.
  39024. */
  39025. prepareTimestampBuffer( renderContext ) {
  39026. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  39027. const renderContextData = this.get( renderContext );
  39028. if ( renderContextData.activeQuery ) {
  39029. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  39030. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  39031. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  39032. renderContextData.activeQuery = null;
  39033. this.queryRunning = false;
  39034. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  39035. const nextRenderContext = renderContextData.queryQueue.shift();
  39036. this.initTimestampQuery( nextRenderContext );
  39037. }
  39038. }
  39039. }
  39040. /**
  39041. * Resolves the time stamp for the given render context and type.
  39042. *
  39043. * @async
  39044. * @param {RenderContext} renderContext - The render context.
  39045. * @param {String} type - The render context.
  39046. * @return {Promise} A Promise that resolves when the time stamp has been computed.
  39047. */
  39048. async resolveTimestampAsync( renderContext, type = 'render' ) {
  39049. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  39050. const renderContextData = this.get( renderContext );
  39051. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  39052. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  39053. const queryInfo = renderContextData.gpuQueries[ i ];
  39054. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  39055. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  39056. if ( available && ! disjoint ) {
  39057. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  39058. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  39059. this.gl.deleteQuery( queryInfo.query );
  39060. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  39061. i --;
  39062. this.renderer.info.updateTimestamp( type, duration );
  39063. }
  39064. }
  39065. }
  39066. /**
  39067. * Returns the backend's rendering context.
  39068. *
  39069. * @return {WebGL2RenderingContext} The rendering context.
  39070. */
  39071. getContext() {
  39072. return this.gl;
  39073. }
  39074. /**
  39075. * This method is executed at the beginning of a render call and prepares
  39076. * the WebGL state for upcoming render calls
  39077. *
  39078. * @param {RenderContext} renderContext - The render context.
  39079. */
  39080. beginRender( renderContext ) {
  39081. const { gl } = this;
  39082. const renderContextData = this.get( renderContext );
  39083. //
  39084. //
  39085. this.initTimestampQuery( renderContext );
  39086. renderContextData.previousContext = this._currentContext;
  39087. this._currentContext = renderContext;
  39088. this._setFramebuffer( renderContext );
  39089. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  39090. //
  39091. if ( renderContext.viewport ) {
  39092. this.updateViewport( renderContext );
  39093. } else {
  39094. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  39095. }
  39096. if ( renderContext.scissor ) {
  39097. const { x, y, width, height } = renderContext.scissorValue;
  39098. gl.scissor( x, renderContext.height - height - y, width, height );
  39099. }
  39100. const occlusionQueryCount = renderContext.occlusionQueryCount;
  39101. if ( occlusionQueryCount > 0 ) {
  39102. // Get a reference to the array of objects with queries. The renderContextData property
  39103. // can be changed by another render pass before the async reading of all previous queries complete
  39104. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  39105. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  39106. renderContextData.lastOcclusionObject = null;
  39107. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  39108. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  39109. renderContextData.occlusionQueryIndex = 0;
  39110. }
  39111. }
  39112. /**
  39113. * This method is executed at the end of a render call and finalizes work
  39114. * after draw calls.
  39115. *
  39116. * @param {RenderContext} renderContext - The render context.
  39117. */
  39118. finishRender( renderContext ) {
  39119. const { gl, state } = this;
  39120. const renderContextData = this.get( renderContext );
  39121. const previousContext = renderContextData.previousContext;
  39122. const occlusionQueryCount = renderContext.occlusionQueryCount;
  39123. if ( occlusionQueryCount > 0 ) {
  39124. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  39125. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  39126. }
  39127. this.resolveOccludedAsync( renderContext );
  39128. }
  39129. const textures = renderContext.textures;
  39130. if ( textures !== null ) {
  39131. for ( let i = 0; i < textures.length; i ++ ) {
  39132. const texture = textures[ i ];
  39133. if ( texture.generateMipmaps ) {
  39134. this.generateMipmaps( texture );
  39135. }
  39136. }
  39137. }
  39138. this._currentContext = previousContext;
  39139. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  39140. const renderTargetContextData = this.get( renderContext.renderTarget );
  39141. const { samples } = renderContext.renderTarget;
  39142. if ( samples > 0 ) {
  39143. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  39144. const mask = gl.COLOR_BUFFER_BIT;
  39145. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  39146. const textures = renderContext.textures;
  39147. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  39148. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  39149. for ( let i = 0; i < textures.length; i ++ ) {
  39150. // TODO Add support for MRT
  39151. if ( renderContext.scissor ) {
  39152. const { x, y, width, height } = renderContext.scissorValue;
  39153. const viewY = renderContext.height - height - y;
  39154. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  39155. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  39156. } else {
  39157. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  39158. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  39159. }
  39160. }
  39161. }
  39162. }
  39163. if ( previousContext !== null ) {
  39164. this._setFramebuffer( previousContext );
  39165. if ( previousContext.viewport ) {
  39166. this.updateViewport( previousContext );
  39167. } else {
  39168. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  39169. }
  39170. }
  39171. this.prepareTimestampBuffer( renderContext );
  39172. }
  39173. /**
  39174. * This method processes the result of occlusion queries and writes it
  39175. * into render context data.
  39176. *
  39177. * @async
  39178. * @param {RenderContext} renderContext - The render context.
  39179. */
  39180. resolveOccludedAsync( renderContext ) {
  39181. const renderContextData = this.get( renderContext );
  39182. // handle occlusion query results
  39183. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  39184. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  39185. const occluded = new WeakSet();
  39186. const { gl } = this;
  39187. renderContextData.currentOcclusionQueryObjects = null;
  39188. renderContextData.currentOcclusionQueries = null;
  39189. const check = () => {
  39190. let completed = 0;
  39191. // check all queries and requeue as appropriate
  39192. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  39193. const query = currentOcclusionQueries[ i ];
  39194. if ( query === null ) continue;
  39195. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  39196. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  39197. currentOcclusionQueries[ i ] = null;
  39198. gl.deleteQuery( query );
  39199. completed ++;
  39200. }
  39201. }
  39202. if ( completed < currentOcclusionQueries.length ) {
  39203. requestAnimationFrame( check );
  39204. } else {
  39205. renderContextData.occluded = occluded;
  39206. }
  39207. };
  39208. check();
  39209. }
  39210. }
  39211. /**
  39212. * Returns `true` if the given 3D object is fully occluded by other
  39213. * 3D objects in the scene.
  39214. *
  39215. * @param {RenderContext} renderContext - The render context.
  39216. * @param {Object3D} object - The 3D object to test.
  39217. * @return {Boolean} Whether the 3D object is fully occluded or not.
  39218. */
  39219. isOccluded( renderContext, object ) {
  39220. const renderContextData = this.get( renderContext );
  39221. return renderContextData.occluded && renderContextData.occluded.has( object );
  39222. }
  39223. /**
  39224. * Updates the viewport with the values from the given render context.
  39225. *
  39226. * @param {RenderContext} renderContext - The render context.
  39227. */
  39228. updateViewport( renderContext ) {
  39229. const gl = this.gl;
  39230. const { x, y, width, height } = renderContext.viewportValue;
  39231. gl.viewport( x, renderContext.height - height - y, width, height );
  39232. }
  39233. /**
  39234. * Defines the scissor test.
  39235. *
  39236. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  39237. */
  39238. setScissorTest( boolean ) {
  39239. const gl = this.gl;
  39240. if ( boolean ) {
  39241. gl.enable( gl.SCISSOR_TEST );
  39242. } else {
  39243. gl.disable( gl.SCISSOR_TEST );
  39244. }
  39245. }
  39246. /**
  39247. * Performs a clear operation.
  39248. *
  39249. * @param {Boolean} color - Whether the color buffer should be cleared or not.
  39250. * @param {Boolean} depth - Whether the depth buffer should be cleared or not.
  39251. * @param {Boolean} stencil - Whether the stencil buffer should be cleared or not.
  39252. * @param {Object?} [descriptor=null] - The render context of the current set render target.
  39253. * @param {Boolean} [setFrameBuffer=true] - TODO.
  39254. */
  39255. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  39256. const { gl } = this;
  39257. if ( descriptor === null ) {
  39258. const clearColor = this.getClearColor();
  39259. // premultiply alpha
  39260. clearColor.r *= clearColor.a;
  39261. clearColor.g *= clearColor.a;
  39262. clearColor.b *= clearColor.a;
  39263. descriptor = {
  39264. textures: null,
  39265. clearColorValue: clearColor
  39266. };
  39267. }
  39268. //
  39269. let clear = 0;
  39270. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  39271. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  39272. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  39273. if ( clear !== 0 ) {
  39274. let clearColor;
  39275. if ( descriptor.clearColorValue ) {
  39276. clearColor = descriptor.clearColorValue;
  39277. } else {
  39278. clearColor = this.getClearColor();
  39279. // premultiply alpha
  39280. clearColor.r *= clearColor.a;
  39281. clearColor.g *= clearColor.a;
  39282. clearColor.b *= clearColor.a;
  39283. }
  39284. if ( depth ) this.state.setDepthMask( true );
  39285. if ( descriptor.textures === null ) {
  39286. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  39287. gl.clear( clear );
  39288. } else {
  39289. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  39290. if ( color ) {
  39291. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  39292. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  39293. }
  39294. }
  39295. if ( depth && stencil ) {
  39296. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  39297. } else if ( depth ) {
  39298. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  39299. } else if ( stencil ) {
  39300. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  39301. }
  39302. }
  39303. }
  39304. }
  39305. /**
  39306. * This method is executed at the beginning of a compute call and
  39307. * prepares the state for upcoming compute tasks.
  39308. *
  39309. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  39310. */
  39311. beginCompute( computeGroup ) {
  39312. const { state, gl } = this;
  39313. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  39314. this.initTimestampQuery( computeGroup );
  39315. }
  39316. /**
  39317. * Executes a compute command for the given compute node.
  39318. *
  39319. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  39320. * @param {Node} computeNode - The compute node.
  39321. * @param {Array<BindGroup>} bindings - The bindings.
  39322. * @param {ComputePipeline} pipeline - The compute pipeline.
  39323. */
  39324. compute( computeGroup, computeNode, bindings, pipeline ) {
  39325. const { state, gl } = this;
  39326. if ( this.discard === false ) {
  39327. // required here to handle async behaviour of render.compute()
  39328. gl.enable( gl.RASTERIZER_DISCARD );
  39329. this.discard = true;
  39330. }
  39331. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  39332. const vaoKey = this._getVaoKey( null, attributes );
  39333. const vaoGPU = this.vaoCache[ vaoKey ];
  39334. if ( vaoGPU === undefined ) {
  39335. this._createVao( null, attributes );
  39336. } else {
  39337. gl.bindVertexArray( vaoGPU );
  39338. }
  39339. state.useProgram( programGPU );
  39340. this._bindUniforms( bindings );
  39341. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  39342. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  39343. gl.beginTransformFeedback( gl.POINTS );
  39344. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  39345. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  39346. } else {
  39347. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  39348. }
  39349. gl.endTransformFeedback();
  39350. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  39351. // switch active buffers
  39352. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  39353. const dualAttributeData = transformBuffers[ i ];
  39354. if ( dualAttributeData.pbo ) {
  39355. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  39356. }
  39357. dualAttributeData.switchBuffers();
  39358. }
  39359. }
  39360. /**
  39361. * This method is executed at the end of a compute call and
  39362. * finalizes work after compute tasks.
  39363. *
  39364. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  39365. */
  39366. finishCompute( computeGroup ) {
  39367. const gl = this.gl;
  39368. this.discard = false;
  39369. gl.disable( gl.RASTERIZER_DISCARD );
  39370. this.prepareTimestampBuffer( computeGroup );
  39371. if ( this._currentContext ) {
  39372. this._setFramebuffer( this._currentContext );
  39373. }
  39374. }
  39375. /**
  39376. * Executes a draw command for the given render object.
  39377. *
  39378. * @param {RenderObject} renderObject - The render object to draw.
  39379. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  39380. */
  39381. draw( renderObject/*, info*/ ) {
  39382. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  39383. const { programGPU } = this.get( pipeline );
  39384. const { gl, state } = this;
  39385. const contextData = this.get( context );
  39386. const drawParams = renderObject.getDrawParameters();
  39387. if ( drawParams === null ) return;
  39388. //
  39389. this._bindUniforms( renderObject.getBindings() );
  39390. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  39391. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  39392. state.useProgram( programGPU );
  39393. //
  39394. const renderObjectData = this.get( renderObject );
  39395. let vaoGPU = renderObjectData.staticVao;
  39396. if ( vaoGPU === undefined || renderObjectData.geometryId !== renderObject.geometry.id ) {
  39397. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  39398. vaoGPU = this.vaoCache[ vaoKey ];
  39399. if ( vaoGPU === undefined ) {
  39400. let staticVao;
  39401. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  39402. if ( staticVao ) {
  39403. renderObjectData.staticVao = vaoGPU;
  39404. renderObjectData.geometryId = renderObject.geometry.id;
  39405. }
  39406. }
  39407. }
  39408. gl.bindVertexArray( vaoGPU );
  39409. //
  39410. const index = renderObject.getIndex();
  39411. //
  39412. const lastObject = contextData.lastOcclusionObject;
  39413. if ( lastObject !== object && lastObject !== undefined ) {
  39414. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  39415. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  39416. contextData.occlusionQueryIndex ++;
  39417. }
  39418. if ( object.occlusionTest === true ) {
  39419. const query = gl.createQuery();
  39420. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  39421. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  39422. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  39423. }
  39424. contextData.lastOcclusionObject = object;
  39425. }
  39426. //
  39427. const renderer = this.bufferRenderer;
  39428. if ( object.isPoints ) renderer.mode = gl.POINTS;
  39429. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  39430. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  39431. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  39432. else {
  39433. if ( material.wireframe === true ) {
  39434. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  39435. renderer.mode = gl.LINES;
  39436. } else {
  39437. renderer.mode = gl.TRIANGLES;
  39438. }
  39439. }
  39440. //
  39441. const { vertexCount, instanceCount } = drawParams;
  39442. let { firstVertex } = drawParams;
  39443. renderer.object = object;
  39444. if ( index !== null ) {
  39445. firstVertex *= index.array.BYTES_PER_ELEMENT;
  39446. const indexData = this.get( index );
  39447. renderer.index = index.count;
  39448. renderer.type = indexData.type;
  39449. } else {
  39450. renderer.index = 0;
  39451. }
  39452. if ( object.isBatchedMesh ) {
  39453. if ( object._multiDrawInstances !== null ) {
  39454. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  39455. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  39456. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  39457. } else {
  39458. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  39459. }
  39460. } else if ( instanceCount > 1 ) {
  39461. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  39462. } else {
  39463. renderer.render( firstVertex, vertexCount );
  39464. }
  39465. //
  39466. gl.bindVertexArray( null );
  39467. }
  39468. /**
  39469. * Explain why always null is returned.
  39470. *
  39471. * @param {RenderObject} renderObject - The render object.
  39472. * @return {Boolean} Whether the render pipeline requires an update or not.
  39473. */
  39474. needsRenderUpdate( /*renderObject*/ ) {
  39475. return false;
  39476. }
  39477. /**
  39478. * Explain why no cache key is computed.
  39479. *
  39480. * @param {RenderObject} renderObject - The render object.
  39481. * @return {String} The cache key.
  39482. */
  39483. getRenderCacheKey( /*renderObject*/ ) {
  39484. return '';
  39485. }
  39486. // textures
  39487. /**
  39488. * Creates a default texture for the given texture that can be used
  39489. * as a placeholder until the actual texture is ready for usage.
  39490. *
  39491. * @param {Texture} texture - The texture to create a default texture for.
  39492. */
  39493. createDefaultTexture( texture ) {
  39494. this.textureUtils.createDefaultTexture( texture );
  39495. }
  39496. /**
  39497. * Defines a texture on the GPU for the given texture object.
  39498. *
  39499. * @param {Texture} texture - The texture.
  39500. * @param {Object} [options={}] - Optional configuration parameter.
  39501. */
  39502. createTexture( texture, options ) {
  39503. this.textureUtils.createTexture( texture, options );
  39504. }
  39505. /**
  39506. * Uploads the updated texture data to the GPU.
  39507. *
  39508. * @param {Texture} texture - The texture.
  39509. * @param {Object} [options={}] - Optional configuration parameter.
  39510. */
  39511. updateTexture( texture, options ) {
  39512. this.textureUtils.updateTexture( texture, options );
  39513. }
  39514. /**
  39515. * Generates mipmaps for the given texture.
  39516. *
  39517. * @param {Texture} texture - The texture.
  39518. */
  39519. generateMipmaps( texture ) {
  39520. this.textureUtils.generateMipmaps( texture );
  39521. }
  39522. /**
  39523. * Destroys the GPU data for the given texture object.
  39524. *
  39525. * @param {Texture} texture - The texture.
  39526. */
  39527. destroyTexture( texture ) {
  39528. this.textureUtils.destroyTexture( texture );
  39529. }
  39530. /**
  39531. * Returns texture data as a typed array.
  39532. *
  39533. * @async
  39534. * @param {Texture} texture - The texture to copy.
  39535. * @param {Number} x - The x coordinate of the copy origin.
  39536. * @param {Number} y - The y coordinate of the copy origin.
  39537. * @param {Number} width - The width of the copy.
  39538. * @param {Number} height - The height of the copy.
  39539. * @param {Number} faceIndex - The face index.
  39540. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  39541. */
  39542. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  39543. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  39544. }
  39545. /**
  39546. * This method does nothing since WebGL 2 has no concept of samplers.
  39547. *
  39548. * @param {Texture} texture - The texture to create the sampler for.
  39549. */
  39550. createSampler( /*texture*/ ) {
  39551. //console.warn( 'Abstract class.' );
  39552. }
  39553. /**
  39554. * This method does nothing since WebGL 2 has no concept of samplers.
  39555. *
  39556. * @param {Texture} texture - The texture to destroy the sampler for.
  39557. */
  39558. destroySampler( /*texture*/ ) {}
  39559. // node builder
  39560. /**
  39561. * Returns a node builder for the given render object.
  39562. *
  39563. * @param {RenderObject} object - The render object.
  39564. * @param {Renderer} renderer - The renderer.
  39565. * @return {GLSLNodeBuilder} The node builder.
  39566. */
  39567. createNodeBuilder( object, renderer ) {
  39568. return new GLSLNodeBuilder( object, renderer );
  39569. }
  39570. // program
  39571. /**
  39572. * Creates a shader program from the given programmable stage.
  39573. *
  39574. * @param {ProgrammableStage} program - The programmable stage.
  39575. */
  39576. createProgram( program ) {
  39577. const gl = this.gl;
  39578. const { stage, code } = program;
  39579. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  39580. gl.shaderSource( shader, code );
  39581. gl.compileShader( shader );
  39582. this.set( program, {
  39583. shaderGPU: shader
  39584. } );
  39585. }
  39586. /**
  39587. * Destroys the shader program of the given programmable stage.
  39588. *
  39589. * @param {ProgrammableStage} program - The programmable stage.
  39590. */
  39591. destroyProgram( program ) {
  39592. this.delete( program );
  39593. }
  39594. /**
  39595. * Creates a render pipeline for the given render object.
  39596. *
  39597. * @param {RenderObject} renderObject - The render object.
  39598. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  39599. */
  39600. createRenderPipeline( renderObject, promises ) {
  39601. const gl = this.gl;
  39602. const pipeline = renderObject.pipeline;
  39603. // Program
  39604. const { fragmentProgram, vertexProgram } = pipeline;
  39605. const programGPU = gl.createProgram();
  39606. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  39607. const vertexShader = this.get( vertexProgram ).shaderGPU;
  39608. gl.attachShader( programGPU, fragmentShader );
  39609. gl.attachShader( programGPU, vertexShader );
  39610. gl.linkProgram( programGPU );
  39611. this.set( pipeline, {
  39612. programGPU,
  39613. fragmentShader,
  39614. vertexShader
  39615. } );
  39616. if ( promises !== null && this.parallel ) {
  39617. const p = new Promise( ( resolve /*, reject*/ ) => {
  39618. const parallel = this.parallel;
  39619. const checkStatus = () => {
  39620. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  39621. this._completeCompile( renderObject, pipeline );
  39622. resolve();
  39623. } else {
  39624. requestAnimationFrame( checkStatus );
  39625. }
  39626. };
  39627. checkStatus();
  39628. } );
  39629. promises.push( p );
  39630. return;
  39631. }
  39632. this._completeCompile( renderObject, pipeline );
  39633. }
  39634. /**
  39635. * Formats the source code of error messages.
  39636. *
  39637. * @private
  39638. * @param {String} string - The code.
  39639. * @param {Number} errorLine - The error line.
  39640. * @return {String} The formatted code.
  39641. */
  39642. _handleSource( string, errorLine ) {
  39643. const lines = string.split( '\n' );
  39644. const lines2 = [];
  39645. const from = Math.max( errorLine - 6, 0 );
  39646. const to = Math.min( errorLine + 6, lines.length );
  39647. for ( let i = from; i < to; i ++ ) {
  39648. const line = i + 1;
  39649. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  39650. }
  39651. return lines2.join( '\n' );
  39652. }
  39653. /**
  39654. * Gets the shader compilation errors from the info log.
  39655. *
  39656. * @private
  39657. * @param {WebGL2RenderingContext} gl - The rendering context.
  39658. * @param {WebGLShader} shader - The WebGL shader object.
  39659. * @param {String} type - The shader type.
  39660. * @return {String} The shader errors.
  39661. */
  39662. _getShaderErrors( gl, shader, type ) {
  39663. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  39664. const errors = gl.getShaderInfoLog( shader ).trim();
  39665. if ( status && errors === '' ) return '';
  39666. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  39667. if ( errorMatches ) {
  39668. const errorLine = parseInt( errorMatches[ 1 ] );
  39669. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  39670. } else {
  39671. return errors;
  39672. }
  39673. }
  39674. /**
  39675. * Logs shader compilation errors.
  39676. *
  39677. * @private
  39678. * @param {WebGLProgram} programGPU - The WebGL program.
  39679. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  39680. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  39681. */
  39682. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  39683. if ( this.renderer.debug.checkShaderErrors ) {
  39684. const gl = this.gl;
  39685. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  39686. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  39687. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  39688. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  39689. } else {
  39690. // default error reporting
  39691. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  39692. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  39693. console.error(
  39694. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  39695. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  39696. 'Program Info Log: ' + programLog + '\n' +
  39697. vertexErrors + '\n' +
  39698. fragmentErrors
  39699. );
  39700. }
  39701. } else if ( programLog !== '' ) {
  39702. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  39703. }
  39704. }
  39705. }
  39706. /**
  39707. * Completes the shader program setup for the given render object.
  39708. *
  39709. * @private
  39710. * @param {RenderObject} renderObject - The render object.
  39711. * @param {RenderPipeline} pipeline - The render pipeline.
  39712. */
  39713. _completeCompile( renderObject, pipeline ) {
  39714. const { state, gl } = this;
  39715. const pipelineData = this.get( pipeline );
  39716. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  39717. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  39718. this._logProgramError( programGPU, fragmentShader, vertexShader );
  39719. }
  39720. state.useProgram( programGPU );
  39721. // Bindings
  39722. const bindings = renderObject.getBindings();
  39723. this._setupBindings( bindings, programGPU );
  39724. //
  39725. this.set( pipeline, {
  39726. programGPU
  39727. } );
  39728. }
  39729. /**
  39730. * Creates a compute pipeline for the given compute node.
  39731. *
  39732. * @param {ComputePipeline} computePipeline - The compute pipeline.
  39733. * @param {Array<BindGroup>} bindings - The bindings.
  39734. */
  39735. createComputePipeline( computePipeline, bindings ) {
  39736. const { state, gl } = this;
  39737. // Program
  39738. const fragmentProgram = {
  39739. stage: 'fragment',
  39740. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  39741. };
  39742. this.createProgram( fragmentProgram );
  39743. const { computeProgram } = computePipeline;
  39744. const programGPU = gl.createProgram();
  39745. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  39746. const vertexShader = this.get( computeProgram ).shaderGPU;
  39747. const transforms = computeProgram.transforms;
  39748. const transformVaryingNames = [];
  39749. const transformAttributeNodes = [];
  39750. for ( let i = 0; i < transforms.length; i ++ ) {
  39751. const transform = transforms[ i ];
  39752. transformVaryingNames.push( transform.varyingName );
  39753. transformAttributeNodes.push( transform.attributeNode );
  39754. }
  39755. gl.attachShader( programGPU, fragmentShader );
  39756. gl.attachShader( programGPU, vertexShader );
  39757. gl.transformFeedbackVaryings(
  39758. programGPU,
  39759. transformVaryingNames,
  39760. gl.SEPARATE_ATTRIBS
  39761. );
  39762. gl.linkProgram( programGPU );
  39763. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  39764. this._logProgramError( programGPU, fragmentShader, vertexShader );
  39765. }
  39766. state.useProgram( programGPU );
  39767. // Bindings
  39768. this._setupBindings( bindings, programGPU );
  39769. const attributeNodes = computeProgram.attributes;
  39770. const attributes = [];
  39771. const transformBuffers = [];
  39772. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  39773. const attribute = attributeNodes[ i ].node.attribute;
  39774. attributes.push( attribute );
  39775. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  39776. }
  39777. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  39778. const attribute = transformAttributeNodes[ i ].attribute;
  39779. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  39780. const attributeData = this.get( attribute );
  39781. transformBuffers.push( attributeData );
  39782. }
  39783. //
  39784. this.set( computePipeline, {
  39785. programGPU,
  39786. transformBuffers,
  39787. attributes
  39788. } );
  39789. }
  39790. /**
  39791. * Creates bindings from the given bind group definition.
  39792. *
  39793. * @param {BindGroup} bindGroup - The bind group.
  39794. * @param {Array<BindGroup>} bindings - Array of bind groups.
  39795. * @param {Number} cacheIndex - The cache index.
  39796. * @param {Number} version - The version.
  39797. */
  39798. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  39799. if ( this._knownBindings.has( bindings ) === false ) {
  39800. this._knownBindings.add( bindings );
  39801. let uniformBuffers = 0;
  39802. let textures = 0;
  39803. for ( const bindGroup of bindings ) {
  39804. this.set( bindGroup, {
  39805. textures: textures,
  39806. uniformBuffers: uniformBuffers
  39807. } );
  39808. for ( const binding of bindGroup.bindings ) {
  39809. if ( binding.isUniformBuffer ) uniformBuffers ++;
  39810. if ( binding.isSampledTexture ) textures ++;
  39811. }
  39812. }
  39813. }
  39814. this.updateBindings( bindGroup, bindings );
  39815. }
  39816. /**
  39817. * Updates the given bind group definition.
  39818. *
  39819. * @param {BindGroup} bindGroup - The bind group.
  39820. * @param {Array<BindGroup>} bindings - Array of bind groups.
  39821. * @param {Number} cacheIndex - The cache index.
  39822. * @param {Number} version - The version.
  39823. */
  39824. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  39825. const { gl } = this;
  39826. const bindGroupData = this.get( bindGroup );
  39827. let i = bindGroupData.uniformBuffers;
  39828. let t = bindGroupData.textures;
  39829. for ( const binding of bindGroup.bindings ) {
  39830. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  39831. const data = binding.buffer;
  39832. const bufferGPU = gl.createBuffer();
  39833. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  39834. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  39835. this.set( binding, {
  39836. index: i ++,
  39837. bufferGPU
  39838. } );
  39839. } else if ( binding.isSampledTexture ) {
  39840. const { textureGPU, glTextureType } = this.get( binding.texture );
  39841. this.set( binding, {
  39842. index: t ++,
  39843. textureGPU,
  39844. glTextureType
  39845. } );
  39846. }
  39847. }
  39848. }
  39849. /**
  39850. * Updates a buffer binding.
  39851. *
  39852. * @param {Buffer} binding - The buffer binding to update.
  39853. */
  39854. updateBinding( binding ) {
  39855. const gl = this.gl;
  39856. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  39857. const bindingData = this.get( binding );
  39858. const bufferGPU = bindingData.bufferGPU;
  39859. const data = binding.buffer;
  39860. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  39861. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  39862. }
  39863. }
  39864. // attributes
  39865. /**
  39866. * Creates the GPU buffer of an indexed shader attribute.
  39867. *
  39868. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  39869. */
  39870. createIndexAttribute( attribute ) {
  39871. const gl = this.gl;
  39872. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  39873. }
  39874. /**
  39875. * Creates the GPU buffer of a shader attribute.
  39876. *
  39877. * @param {BufferAttribute} attribute - The buffer attribute.
  39878. */
  39879. createAttribute( attribute ) {
  39880. if ( this.has( attribute ) ) return;
  39881. const gl = this.gl;
  39882. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  39883. }
  39884. /**
  39885. * Creates the GPU buffer of a storage attribute.
  39886. *
  39887. * @param {BufferAttribute} attribute - The buffer attribute.
  39888. */
  39889. createStorageAttribute( attribute ) {
  39890. if ( this.has( attribute ) ) return;
  39891. const gl = this.gl;
  39892. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  39893. }
  39894. /**
  39895. * Updates the GPU buffer of a shader attribute.
  39896. *
  39897. * @param {BufferAttribute} attribute - The buffer attribute to update.
  39898. */
  39899. updateAttribute( attribute ) {
  39900. this.attributeUtils.updateAttribute( attribute );
  39901. }
  39902. /**
  39903. * Destroys the GPU buffer of a shader attribute.
  39904. *
  39905. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  39906. */
  39907. destroyAttribute( attribute ) {
  39908. this.attributeUtils.destroyAttribute( attribute );
  39909. }
  39910. /**
  39911. * Checks if the given feature is supported by the backend.
  39912. *
  39913. * @param {String} name - The feature's name.
  39914. * @return {Boolean} Whether the feature is supported or not.
  39915. */
  39916. hasFeature( name ) {
  39917. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  39918. const extensions = this.extensions;
  39919. for ( let i = 0; i < keysMatching.length; i ++ ) {
  39920. if ( extensions.has( keysMatching[ i ] ) ) return true;
  39921. }
  39922. return false;
  39923. }
  39924. /**
  39925. * Returns the maximum anisotropy texture filtering value.
  39926. *
  39927. * @return {Number} The maximum anisotropy texture filtering value.
  39928. */
  39929. getMaxAnisotropy() {
  39930. return this.capabilities.getMaxAnisotropy();
  39931. }
  39932. /**
  39933. * Copies data of the given source texture to the given destination texture.
  39934. *
  39935. * @param {Texture} srcTexture - The source texture.
  39936. * @param {Texture} dstTexture - The destination texture.
  39937. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  39938. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  39939. * @param {Number} [level=0] - The mip level to copy.
  39940. */
  39941. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  39942. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  39943. }
  39944. /**
  39945. * Copies the current bound framebuffer to the given texture.
  39946. *
  39947. * @param {Texture} texture - The destination texture.
  39948. * @param {RenderContext} renderContext - The render context.
  39949. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  39950. */
  39951. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  39952. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  39953. }
  39954. /**
  39955. * Configures the active framebuffer from the given render context.
  39956. *
  39957. * @private
  39958. * @param {RenderContext} descriptor - The render context.
  39959. */
  39960. _setFramebuffer( descriptor ) {
  39961. const { gl, state } = this;
  39962. let currentFrameBuffer = null;
  39963. if ( descriptor.textures !== null ) {
  39964. const renderTarget = descriptor.renderTarget;
  39965. const renderTargetContextData = this.get( renderTarget );
  39966. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  39967. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  39968. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  39969. const isRenderTargetArray = renderTarget.isRenderTargetArray === true;
  39970. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  39971. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  39972. const cacheKey = getCacheKey( descriptor );
  39973. let fb;
  39974. if ( isCube ) {
  39975. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  39976. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  39977. } else {
  39978. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  39979. fb = renderTargetContextData.framebuffers[ cacheKey ];
  39980. }
  39981. if ( fb === undefined ) {
  39982. fb = gl.createFramebuffer();
  39983. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  39984. const textures = descriptor.textures;
  39985. if ( isCube ) {
  39986. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  39987. const { textureGPU } = this.get( textures[ 0 ] );
  39988. const cubeFace = this.renderer._activeCubeFace;
  39989. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  39990. } else {
  39991. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  39992. for ( let i = 0; i < textures.length; i ++ ) {
  39993. const texture = textures[ i ];
  39994. const textureData = this.get( texture );
  39995. textureData.renderTarget = descriptor.renderTarget;
  39996. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  39997. const attachment = gl.COLOR_ATTACHMENT0 + i;
  39998. if ( isRenderTarget3D || isRenderTargetArray ) {
  39999. const layer = this.renderer._activeCubeFace;
  40000. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, layer );
  40001. } else {
  40002. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  40003. }
  40004. }
  40005. state.drawBuffers( descriptor, fb );
  40006. }
  40007. if ( descriptor.depthTexture !== null ) {
  40008. const textureData = this.get( descriptor.depthTexture );
  40009. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  40010. textureData.renderTarget = descriptor.renderTarget;
  40011. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  40012. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  40013. }
  40014. }
  40015. if ( samples > 0 ) {
  40016. if ( msaaFb === undefined ) {
  40017. const invalidationArray = [];
  40018. msaaFb = gl.createFramebuffer();
  40019. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  40020. const msaaRenderbuffers = [];
  40021. const textures = descriptor.textures;
  40022. for ( let i = 0; i < textures.length; i ++ ) {
  40023. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  40024. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  40025. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  40026. if ( depthBuffer ) {
  40027. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  40028. invalidationArray.push( depthStyle );
  40029. }
  40030. const texture = descriptor.textures[ i ];
  40031. const textureData = this.get( texture );
  40032. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  40033. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  40034. }
  40035. renderTargetContextData.msaaFrameBuffer = msaaFb;
  40036. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  40037. if ( depthRenderbuffer === undefined ) {
  40038. depthRenderbuffer = gl.createRenderbuffer();
  40039. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor );
  40040. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  40041. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  40042. invalidationArray.push( depthStyle );
  40043. }
  40044. renderTargetContextData.invalidationArray = invalidationArray;
  40045. }
  40046. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  40047. } else {
  40048. currentFrameBuffer = fb;
  40049. }
  40050. }
  40051. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  40052. }
  40053. /**
  40054. * Computes the VAO key for the given index and attributes.
  40055. *
  40056. * @private
  40057. * @param {BufferAttribute?} index - The index. `null` for non-indexed geometries.
  40058. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  40059. * @return {String} The VAO key.
  40060. */
  40061. _getVaoKey( index, attributes ) {
  40062. let key = '';
  40063. if ( index !== null ) {
  40064. const indexData = this.get( index );
  40065. key += ':' + indexData.id;
  40066. }
  40067. for ( let i = 0; i < attributes.length; i ++ ) {
  40068. const attributeData = this.get( attributes[ i ] );
  40069. key += ':' + attributeData.id;
  40070. }
  40071. return key;
  40072. }
  40073. /**
  40074. * Creates a VAO from the index and attributes.
  40075. *
  40076. * @private
  40077. * @param {BufferAttribute?} index - The index. `null` for non-indexed geometries.
  40078. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  40079. * @return {Object} The VAO data.
  40080. */
  40081. _createVao( index, attributes ) {
  40082. const { gl } = this;
  40083. const vaoGPU = gl.createVertexArray();
  40084. let key = '';
  40085. let staticVao = true;
  40086. gl.bindVertexArray( vaoGPU );
  40087. if ( index !== null ) {
  40088. const indexData = this.get( index );
  40089. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  40090. key += ':' + indexData.id;
  40091. }
  40092. for ( let i = 0; i < attributes.length; i ++ ) {
  40093. const attribute = attributes[ i ];
  40094. const attributeData = this.get( attribute );
  40095. key += ':' + attributeData.id;
  40096. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  40097. gl.enableVertexAttribArray( i );
  40098. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  40099. let stride, offset;
  40100. if ( attribute.isInterleavedBufferAttribute === true ) {
  40101. stride = attribute.data.stride * attributeData.bytesPerElement;
  40102. offset = attribute.offset * attributeData.bytesPerElement;
  40103. } else {
  40104. stride = 0;
  40105. offset = 0;
  40106. }
  40107. if ( attributeData.isInteger ) {
  40108. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  40109. } else {
  40110. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  40111. }
  40112. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  40113. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  40114. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  40115. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  40116. }
  40117. }
  40118. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  40119. this.vaoCache[ key ] = vaoGPU;
  40120. return { vaoGPU, staticVao };
  40121. }
  40122. /**
  40123. * Creates a transform feedback from the given transform buffers.
  40124. *
  40125. * @private
  40126. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  40127. * @return {WebGLTransformFeedback} The transform feedback.
  40128. */
  40129. _getTransformFeedback( transformBuffers ) {
  40130. let key = '';
  40131. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  40132. key += ':' + transformBuffers[ i ].id;
  40133. }
  40134. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  40135. if ( transformFeedbackGPU !== undefined ) {
  40136. return transformFeedbackGPU;
  40137. }
  40138. const { gl } = this;
  40139. transformFeedbackGPU = gl.createTransformFeedback();
  40140. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  40141. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  40142. const attributeData = transformBuffers[ i ];
  40143. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  40144. }
  40145. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  40146. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  40147. return transformFeedbackGPU;
  40148. }
  40149. /**
  40150. * Setups the given bindings.
  40151. *
  40152. * @private
  40153. * @param {Array<BindGroup>} bindings - The bindings.
  40154. * @param {WebGLProgram} programGPU - The WebGL program.
  40155. */
  40156. _setupBindings( bindings, programGPU ) {
  40157. const gl = this.gl;
  40158. for ( const bindGroup of bindings ) {
  40159. for ( const binding of bindGroup.bindings ) {
  40160. const bindingData = this.get( binding );
  40161. const index = bindingData.index;
  40162. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  40163. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  40164. gl.uniformBlockBinding( programGPU, location, index );
  40165. } else if ( binding.isSampledTexture ) {
  40166. const location = gl.getUniformLocation( programGPU, binding.name );
  40167. gl.uniform1i( location, index );
  40168. }
  40169. }
  40170. }
  40171. }
  40172. /**
  40173. * Binds the given uniforms.
  40174. *
  40175. * @private
  40176. * @param {Array<BindGroup>} bindings - The bindings.
  40177. */
  40178. _bindUniforms( bindings ) {
  40179. const { gl, state } = this;
  40180. for ( const bindGroup of bindings ) {
  40181. for ( const binding of bindGroup.bindings ) {
  40182. const bindingData = this.get( binding );
  40183. const index = bindingData.index;
  40184. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  40185. // TODO USE bindBufferRange to group multiple uniform buffers
  40186. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  40187. } else if ( binding.isSampledTexture ) {
  40188. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  40189. }
  40190. }
  40191. }
  40192. }
  40193. /**
  40194. * Frees internal resources.
  40195. */
  40196. dispose() {
  40197. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  40198. }
  40199. }
  40200. const GPUPrimitiveTopology = {
  40201. PointList: 'point-list',
  40202. LineList: 'line-list',
  40203. LineStrip: 'line-strip',
  40204. TriangleList: 'triangle-list',
  40205. TriangleStrip: 'triangle-strip',
  40206. };
  40207. const GPUCompareFunction = {
  40208. Never: 'never',
  40209. Less: 'less',
  40210. Equal: 'equal',
  40211. LessEqual: 'less-equal',
  40212. Greater: 'greater',
  40213. NotEqual: 'not-equal',
  40214. GreaterEqual: 'greater-equal',
  40215. Always: 'always'
  40216. };
  40217. const GPUStoreOp = {
  40218. Store: 'store',
  40219. Discard: 'discard'
  40220. };
  40221. const GPULoadOp = {
  40222. Load: 'load',
  40223. Clear: 'clear'
  40224. };
  40225. const GPUFrontFace = {
  40226. CCW: 'ccw',
  40227. CW: 'cw'
  40228. };
  40229. const GPUCullMode = {
  40230. None: 'none',
  40231. Front: 'front',
  40232. Back: 'back'
  40233. };
  40234. const GPUIndexFormat = {
  40235. Uint16: 'uint16',
  40236. Uint32: 'uint32'
  40237. };
  40238. const GPUTextureFormat = {
  40239. // 8-bit formats
  40240. R8Unorm: 'r8unorm',
  40241. R8Snorm: 'r8snorm',
  40242. R8Uint: 'r8uint',
  40243. R8Sint: 'r8sint',
  40244. // 16-bit formats
  40245. R16Uint: 'r16uint',
  40246. R16Sint: 'r16sint',
  40247. R16Float: 'r16float',
  40248. RG8Unorm: 'rg8unorm',
  40249. RG8Snorm: 'rg8snorm',
  40250. RG8Uint: 'rg8uint',
  40251. RG8Sint: 'rg8sint',
  40252. // 32-bit formats
  40253. R32Uint: 'r32uint',
  40254. R32Sint: 'r32sint',
  40255. R32Float: 'r32float',
  40256. RG16Uint: 'rg16uint',
  40257. RG16Sint: 'rg16sint',
  40258. RG16Float: 'rg16float',
  40259. RGBA8Unorm: 'rgba8unorm',
  40260. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  40261. RGBA8Snorm: 'rgba8snorm',
  40262. RGBA8Uint: 'rgba8uint',
  40263. RGBA8Sint: 'rgba8sint',
  40264. BGRA8Unorm: 'bgra8unorm',
  40265. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  40266. // Packed 32-bit formats
  40267. RGB9E5UFloat: 'rgb9e5ufloat',
  40268. RGB10A2Unorm: 'rgb10a2unorm',
  40269. RG11B10uFloat: 'rgb10a2unorm',
  40270. // 64-bit formats
  40271. RG32Uint: 'rg32uint',
  40272. RG32Sint: 'rg32sint',
  40273. RG32Float: 'rg32float',
  40274. RGBA16Uint: 'rgba16uint',
  40275. RGBA16Sint: 'rgba16sint',
  40276. RGBA16Float: 'rgba16float',
  40277. // 128-bit formats
  40278. RGBA32Uint: 'rgba32uint',
  40279. RGBA32Sint: 'rgba32sint',
  40280. RGBA32Float: 'rgba32float',
  40281. // Depth and stencil formats
  40282. Stencil8: 'stencil8',
  40283. Depth16Unorm: 'depth16unorm',
  40284. Depth24Plus: 'depth24plus',
  40285. Depth24PlusStencil8: 'depth24plus-stencil8',
  40286. Depth32Float: 'depth32float',
  40287. // 'depth32float-stencil8' extension
  40288. Depth32FloatStencil8: 'depth32float-stencil8',
  40289. // BC compressed formats usable if 'texture-compression-bc' is both
  40290. // supported by the device/user agent and enabled in requestDevice.
  40291. BC1RGBAUnorm: 'bc1-rgba-unorm',
  40292. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  40293. BC2RGBAUnorm: 'bc2-rgba-unorm',
  40294. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  40295. BC3RGBAUnorm: 'bc3-rgba-unorm',
  40296. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  40297. BC4RUnorm: 'bc4-r-unorm',
  40298. BC4RSnorm: 'bc4-r-snorm',
  40299. BC5RGUnorm: 'bc5-rg-unorm',
  40300. BC5RGSnorm: 'bc5-rg-snorm',
  40301. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  40302. BC6HRGBFloat: 'bc6h-rgb-float',
  40303. BC7RGBAUnorm: 'bc7-rgba-unorm',
  40304. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  40305. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  40306. // supported by the device/user agent and enabled in requestDevice.
  40307. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  40308. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  40309. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  40310. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  40311. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  40312. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  40313. EACR11Unorm: 'eac-r11unorm',
  40314. EACR11Snorm: 'eac-r11snorm',
  40315. EACRG11Unorm: 'eac-rg11unorm',
  40316. EACRG11Snorm: 'eac-rg11snorm',
  40317. // ASTC compressed formats usable if 'texture-compression-astc' is both
  40318. // supported by the device/user agent and enabled in requestDevice.
  40319. ASTC4x4Unorm: 'astc-4x4-unorm',
  40320. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  40321. ASTC5x4Unorm: 'astc-5x4-unorm',
  40322. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  40323. ASTC5x5Unorm: 'astc-5x5-unorm',
  40324. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  40325. ASTC6x5Unorm: 'astc-6x5-unorm',
  40326. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  40327. ASTC6x6Unorm: 'astc-6x6-unorm',
  40328. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  40329. ASTC8x5Unorm: 'astc-8x5-unorm',
  40330. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  40331. ASTC8x6Unorm: 'astc-8x6-unorm',
  40332. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  40333. ASTC8x8Unorm: 'astc-8x8-unorm',
  40334. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  40335. ASTC10x5Unorm: 'astc-10x5-unorm',
  40336. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  40337. ASTC10x6Unorm: 'astc-10x6-unorm',
  40338. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  40339. ASTC10x8Unorm: 'astc-10x8-unorm',
  40340. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  40341. ASTC10x10Unorm: 'astc-10x10-unorm',
  40342. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  40343. ASTC12x10Unorm: 'astc-12x10-unorm',
  40344. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  40345. ASTC12x12Unorm: 'astc-12x12-unorm',
  40346. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  40347. };
  40348. const GPUAddressMode = {
  40349. ClampToEdge: 'clamp-to-edge',
  40350. Repeat: 'repeat',
  40351. MirrorRepeat: 'mirror-repeat'
  40352. };
  40353. const GPUFilterMode = {
  40354. Linear: 'linear',
  40355. Nearest: 'nearest'
  40356. };
  40357. const GPUBlendFactor = {
  40358. Zero: 'zero',
  40359. One: 'one',
  40360. Src: 'src',
  40361. OneMinusSrc: 'one-minus-src',
  40362. SrcAlpha: 'src-alpha',
  40363. OneMinusSrcAlpha: 'one-minus-src-alpha',
  40364. Dst: 'dst',
  40365. OneMinusDstColor: 'one-minus-dst',
  40366. DstAlpha: 'dst-alpha',
  40367. OneMinusDstAlpha: 'one-minus-dst-alpha',
  40368. SrcAlphaSaturated: 'src-alpha-saturated',
  40369. Constant: 'constant',
  40370. OneMinusConstant: 'one-minus-constant'
  40371. };
  40372. const GPUBlendOperation = {
  40373. Add: 'add',
  40374. Subtract: 'subtract',
  40375. ReverseSubtract: 'reverse-subtract',
  40376. Min: 'min',
  40377. Max: 'max'
  40378. };
  40379. const GPUColorWriteFlags = {
  40380. None: 0,
  40381. Red: 0x1,
  40382. Green: 0x2,
  40383. Blue: 0x4,
  40384. Alpha: 0x8,
  40385. All: 0xF
  40386. };
  40387. const GPUStencilOperation = {
  40388. Keep: 'keep',
  40389. Zero: 'zero',
  40390. Replace: 'replace',
  40391. Invert: 'invert',
  40392. IncrementClamp: 'increment-clamp',
  40393. DecrementClamp: 'decrement-clamp',
  40394. IncrementWrap: 'increment-wrap',
  40395. DecrementWrap: 'decrement-wrap'
  40396. };
  40397. const GPUBufferBindingType = {
  40398. Uniform: 'uniform',
  40399. Storage: 'storage',
  40400. ReadOnlyStorage: 'read-only-storage'
  40401. };
  40402. const GPUStorageTextureAccess = {
  40403. WriteOnly: 'write-only',
  40404. ReadOnly: 'read-only',
  40405. ReadWrite: 'read-write',
  40406. };
  40407. const GPUTextureSampleType = {
  40408. Float: 'float',
  40409. UnfilterableFloat: 'unfilterable-float',
  40410. Depth: 'depth',
  40411. SInt: 'sint',
  40412. UInt: 'uint'
  40413. };
  40414. const GPUTextureDimension = {
  40415. OneD: '1d',
  40416. TwoD: '2d',
  40417. ThreeD: '3d'
  40418. };
  40419. const GPUTextureViewDimension = {
  40420. OneD: '1d',
  40421. TwoD: '2d',
  40422. TwoDArray: '2d-array',
  40423. Cube: 'cube',
  40424. CubeArray: 'cube-array',
  40425. ThreeD: '3d'
  40426. };
  40427. const GPUTextureAspect = {
  40428. All: 'all',
  40429. StencilOnly: 'stencil-only',
  40430. DepthOnly: 'depth-only'
  40431. };
  40432. const GPUInputStepMode = {
  40433. Vertex: 'vertex',
  40434. Instance: 'instance'
  40435. };
  40436. const GPUFeatureName = {
  40437. DepthClipControl: 'depth-clip-control',
  40438. Depth32FloatStencil8: 'depth32float-stencil8',
  40439. TextureCompressionBC: 'texture-compression-bc',
  40440. TextureCompressionETC2: 'texture-compression-etc2',
  40441. TextureCompressionASTC: 'texture-compression-astc',
  40442. TimestampQuery: 'timestamp-query',
  40443. IndirectFirstInstance: 'indirect-first-instance',
  40444. ShaderF16: 'shader-f16',
  40445. RG11B10UFloat: 'rg11b10ufloat-renderable',
  40446. BGRA8UNormStorage: 'bgra8unorm-storage',
  40447. Float32Filterable: 'float32-filterable',
  40448. ClipDistances: 'clip-distances',
  40449. DualSourceBlending: 'dual-source-blending',
  40450. Subgroups: 'subgroups'
  40451. };
  40452. /**
  40453. * Represents a sampler binding type.
  40454. *
  40455. * @private
  40456. * @augments Binding
  40457. */
  40458. class Sampler extends Binding {
  40459. /**
  40460. * Constructs a new sampler.
  40461. *
  40462. * @param {String} name - The samplers's name.
  40463. * @param {Texture?} texture - The texture this binding is referring to.
  40464. */
  40465. constructor( name, texture ) {
  40466. super( name );
  40467. /**
  40468. * The texture the sampler is referring to.
  40469. *
  40470. * @type {Texture?}
  40471. */
  40472. this.texture = texture;
  40473. /**
  40474. * The binding's version.
  40475. *
  40476. * @type {Number}
  40477. */
  40478. this.version = texture ? texture.version : 0;
  40479. /**
  40480. * This flag can be used for type testing.
  40481. *
  40482. * @type {Boolean}
  40483. * @readonly
  40484. * @default true
  40485. */
  40486. this.isSampler = true;
  40487. }
  40488. }
  40489. /**
  40490. * A special form of sampler binding type.
  40491. * It's texture value is managed by a node object.
  40492. *
  40493. * @private
  40494. * @augments Sampler
  40495. */
  40496. class NodeSampler extends Sampler {
  40497. /**
  40498. * Constructs a new node-based sampler.
  40499. *
  40500. * @param {String} name - The samplers's name.
  40501. * @param {TextureNode} textureNode - The texture node.
  40502. * @param {UniformGroupNode} groupNode - The uniform group node.
  40503. */
  40504. constructor( name, textureNode, groupNode ) {
  40505. super( name, textureNode ? textureNode.value : null );
  40506. /**
  40507. * The texture node.
  40508. *
  40509. * @type {TextureNode}
  40510. */
  40511. this.textureNode = textureNode;
  40512. /**
  40513. * The uniform group node.
  40514. *
  40515. * @type {UniformGroupNode}
  40516. */
  40517. this.groupNode = groupNode;
  40518. }
  40519. /**
  40520. * Updates the texture value of this sampler.
  40521. */
  40522. update() {
  40523. this.texture = this.textureNode.value;
  40524. }
  40525. }
  40526. /**
  40527. * Represents a storage buffer binding type.
  40528. *
  40529. * @private
  40530. * @augments Buffer
  40531. */
  40532. class StorageBuffer extends Buffer {
  40533. /**
  40534. * Constructs a new uniform buffer.
  40535. *
  40536. * @param {String} name - The buffer's name.
  40537. * @param {BufferAttribute} attribute - The buffer attribute.
  40538. */
  40539. constructor( name, attribute ) {
  40540. super( name, attribute ? attribute.array : null );
  40541. /**
  40542. * This flag can be used for type testing.
  40543. *
  40544. * @type {BufferAttribute}
  40545. */
  40546. this.attribute = attribute;
  40547. /**
  40548. * This flag can be used for type testing.
  40549. *
  40550. * @type {Boolean}
  40551. * @readonly
  40552. * @default true
  40553. */
  40554. this.isStorageBuffer = true;
  40555. }
  40556. }
  40557. let _id = 0;
  40558. /**
  40559. * A special form of storage buffer binding type.
  40560. * It's buffer value is managed by a node object.
  40561. *
  40562. * @private
  40563. * @augments StorageBuffer
  40564. */
  40565. class NodeStorageBuffer extends StorageBuffer {
  40566. /**
  40567. * Constructs a new node-based storage buffer.
  40568. *
  40569. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  40570. * @param {UniformGroupNode} groupNode - The uniform group node.
  40571. */
  40572. constructor( nodeUniform, groupNode ) {
  40573. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  40574. /**
  40575. * The node uniform.
  40576. *
  40577. * @type {StorageBufferNode}
  40578. */
  40579. this.nodeUniform = nodeUniform;
  40580. /**
  40581. * The access type.
  40582. *
  40583. * @type {String}
  40584. */
  40585. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  40586. /**
  40587. * The uniform group node.
  40588. *
  40589. * @type {UniformGroupNode}
  40590. */
  40591. this.groupNode = groupNode;
  40592. }
  40593. /**
  40594. * The storage buffer.
  40595. *
  40596. * @type {BufferAttribute}
  40597. */
  40598. get buffer() {
  40599. return this.nodeUniform.value;
  40600. }
  40601. }
  40602. /**
  40603. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  40604. *
  40605. * @private
  40606. */
  40607. class WebGPUTexturePassUtils extends DataMap {
  40608. /**
  40609. * Constructs a new utility object.
  40610. *
  40611. * @param {GPUDevice} device - The WebGPU device.
  40612. */
  40613. constructor( device ) {
  40614. super();
  40615. /**
  40616. * The WebGPU device.
  40617. *
  40618. * @type {GPUDevice}
  40619. */
  40620. this.device = device;
  40621. const mipmapVertexSource = `
  40622. struct VarysStruct {
  40623. @builtin( position ) Position: vec4<f32>,
  40624. @location( 0 ) vTex : vec2<f32>
  40625. };
  40626. @vertex
  40627. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  40628. var Varys : VarysStruct;
  40629. var pos = array< vec2<f32>, 4 >(
  40630. vec2<f32>( -1.0, 1.0 ),
  40631. vec2<f32>( 1.0, 1.0 ),
  40632. vec2<f32>( -1.0, -1.0 ),
  40633. vec2<f32>( 1.0, -1.0 )
  40634. );
  40635. var tex = array< vec2<f32>, 4 >(
  40636. vec2<f32>( 0.0, 0.0 ),
  40637. vec2<f32>( 1.0, 0.0 ),
  40638. vec2<f32>( 0.0, 1.0 ),
  40639. vec2<f32>( 1.0, 1.0 )
  40640. );
  40641. Varys.vTex = tex[ vertexIndex ];
  40642. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  40643. return Varys;
  40644. }
  40645. `;
  40646. const mipmapFragmentSource = `
  40647. @group( 0 ) @binding( 0 )
  40648. var imgSampler : sampler;
  40649. @group( 0 ) @binding( 1 )
  40650. var img : texture_2d<f32>;
  40651. @fragment
  40652. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  40653. return textureSample( img, imgSampler, vTex );
  40654. }
  40655. `;
  40656. const flipYFragmentSource = `
  40657. @group( 0 ) @binding( 0 )
  40658. var imgSampler : sampler;
  40659. @group( 0 ) @binding( 1 )
  40660. var img : texture_2d<f32>;
  40661. @fragment
  40662. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  40663. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  40664. }
  40665. `;
  40666. /**
  40667. * The mipmap GPU sampler.
  40668. *
  40669. * @type {GPUSampler}
  40670. */
  40671. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  40672. /**
  40673. * The flipY GPU sampler.
  40674. *
  40675. * @type {GPUSampler}
  40676. */
  40677. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  40678. /**
  40679. * A cache for GPU render pipelines used for copy/transfer passes.
  40680. * Every texture format requires a unique pipeline.
  40681. *
  40682. * @type {Object<String,GPURenderPipeline>}
  40683. */
  40684. this.transferPipelines = {};
  40685. /**
  40686. * A cache for GPU render pipelines used for flipY passes.
  40687. * Every texture format requires a unique pipeline.
  40688. *
  40689. * @type {Object<String,GPURenderPipeline>}
  40690. */
  40691. this.flipYPipelines = {};
  40692. /**
  40693. * The mipmap vertex shader module.
  40694. *
  40695. * @type {GPUShaderModule}
  40696. */
  40697. this.mipmapVertexShaderModule = device.createShaderModule( {
  40698. label: 'mipmapVertex',
  40699. code: mipmapVertexSource
  40700. } );
  40701. /**
  40702. * The mipmap fragment shader module.
  40703. *
  40704. * @type {GPUShaderModule}
  40705. */
  40706. this.mipmapFragmentShaderModule = device.createShaderModule( {
  40707. label: 'mipmapFragment',
  40708. code: mipmapFragmentSource
  40709. } );
  40710. /**
  40711. * The flipY fragment shader module.
  40712. *
  40713. * @type {GPUShaderModule}
  40714. */
  40715. this.flipYFragmentShaderModule = device.createShaderModule( {
  40716. label: 'flipYFragment',
  40717. code: flipYFragmentSource
  40718. } );
  40719. }
  40720. /**
  40721. * Returns a render pipeline for the internal copy render pass. The pass
  40722. * requires a unique render pipeline for each texture format.
  40723. *
  40724. * @param {String} format - The GPU texture format
  40725. * @return {GPURenderPipeline} The GPU render pipeline.
  40726. */
  40727. getTransferPipeline( format ) {
  40728. let pipeline = this.transferPipelines[ format ];
  40729. if ( pipeline === undefined ) {
  40730. pipeline = this.device.createRenderPipeline( {
  40731. label: `mipmap-${ format }`,
  40732. vertex: {
  40733. module: this.mipmapVertexShaderModule,
  40734. entryPoint: 'main'
  40735. },
  40736. fragment: {
  40737. module: this.mipmapFragmentShaderModule,
  40738. entryPoint: 'main',
  40739. targets: [ { format } ]
  40740. },
  40741. primitive: {
  40742. topology: GPUPrimitiveTopology.TriangleStrip,
  40743. stripIndexFormat: GPUIndexFormat.Uint32
  40744. },
  40745. layout: 'auto'
  40746. } );
  40747. this.transferPipelines[ format ] = pipeline;
  40748. }
  40749. return pipeline;
  40750. }
  40751. /**
  40752. * Returns a render pipeline for the flipY render pass. The pass
  40753. * requires a unique render pipeline for each texture format.
  40754. *
  40755. * @param {String} format - The GPU texture format
  40756. * @return {GPURenderPipeline} The GPU render pipeline.
  40757. */
  40758. getFlipYPipeline( format ) {
  40759. let pipeline = this.flipYPipelines[ format ];
  40760. if ( pipeline === undefined ) {
  40761. pipeline = this.device.createRenderPipeline( {
  40762. label: `flipY-${ format }`,
  40763. vertex: {
  40764. module: this.mipmapVertexShaderModule,
  40765. entryPoint: 'main'
  40766. },
  40767. fragment: {
  40768. module: this.flipYFragmentShaderModule,
  40769. entryPoint: 'main',
  40770. targets: [ { format } ]
  40771. },
  40772. primitive: {
  40773. topology: GPUPrimitiveTopology.TriangleStrip,
  40774. stripIndexFormat: GPUIndexFormat.Uint32
  40775. },
  40776. layout: 'auto'
  40777. } );
  40778. this.flipYPipelines[ format ] = pipeline;
  40779. }
  40780. return pipeline;
  40781. }
  40782. /**
  40783. * Flip the contents of the given GPU texture along its vertical axis.
  40784. *
  40785. * @param {GPUTexture} textureGPU - The GPU texture object.
  40786. * @param {Object} textureGPUDescriptor - The texture descriptor.
  40787. * @param {Number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  40788. */
  40789. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  40790. const format = textureGPUDescriptor.format;
  40791. const { width, height } = textureGPUDescriptor.size;
  40792. const transferPipeline = this.getTransferPipeline( format );
  40793. const flipYPipeline = this.getFlipYPipeline( format );
  40794. const tempTexture = this.device.createTexture( {
  40795. size: { width, height, depthOrArrayLayers: 1 },
  40796. format,
  40797. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  40798. } );
  40799. const srcView = textureGPU.createView( {
  40800. baseMipLevel: 0,
  40801. mipLevelCount: 1,
  40802. dimension: GPUTextureViewDimension.TwoD,
  40803. baseArrayLayer
  40804. } );
  40805. const dstView = tempTexture.createView( {
  40806. baseMipLevel: 0,
  40807. mipLevelCount: 1,
  40808. dimension: GPUTextureViewDimension.TwoD,
  40809. baseArrayLayer: 0
  40810. } );
  40811. const commandEncoder = this.device.createCommandEncoder( {} );
  40812. const pass = ( pipeline, sourceView, destinationView ) => {
  40813. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  40814. const bindGroup = this.device.createBindGroup( {
  40815. layout: bindGroupLayout,
  40816. entries: [ {
  40817. binding: 0,
  40818. resource: this.flipYSampler
  40819. }, {
  40820. binding: 1,
  40821. resource: sourceView
  40822. } ]
  40823. } );
  40824. const passEncoder = commandEncoder.beginRenderPass( {
  40825. colorAttachments: [ {
  40826. view: destinationView,
  40827. loadOp: GPULoadOp.Clear,
  40828. storeOp: GPUStoreOp.Store,
  40829. clearValue: [ 0, 0, 0, 0 ]
  40830. } ]
  40831. } );
  40832. passEncoder.setPipeline( pipeline );
  40833. passEncoder.setBindGroup( 0, bindGroup );
  40834. passEncoder.draw( 4, 1, 0, 0 );
  40835. passEncoder.end();
  40836. };
  40837. pass( transferPipeline, srcView, dstView );
  40838. pass( flipYPipeline, dstView, srcView );
  40839. this.device.queue.submit( [ commandEncoder.finish() ] );
  40840. tempTexture.destroy();
  40841. }
  40842. /**
  40843. * Generates mipmaps for the given GPU texture.
  40844. *
  40845. * @param {GPUTexture} textureGPU - The GPU texture object.
  40846. * @param {Object} textureGPUDescriptor - The texture descriptor.
  40847. * @param {Number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  40848. */
  40849. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  40850. const textureData = this.get( textureGPU );
  40851. if ( textureData.useCount === undefined ) {
  40852. textureData.useCount = 0;
  40853. textureData.layers = [];
  40854. }
  40855. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  40856. const commandEncoder = this.device.createCommandEncoder( {} );
  40857. this._mipmapRunBundles( commandEncoder, passes );
  40858. this.device.queue.submit( [ commandEncoder.finish() ] );
  40859. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  40860. textureData.useCount ++;
  40861. }
  40862. /**
  40863. * Since multiple copy render passes are required to generate mipmaps, the passes
  40864. * are managed as render bundles to improve performance.
  40865. *
  40866. * @param {GPUTexture} textureGPU - The GPU texture object.
  40867. * @param {Object} textureGPUDescriptor - The texture descriptor.
  40868. * @param {Number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  40869. * @return {Array} An array of render bundles.
  40870. */
  40871. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  40872. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  40873. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  40874. let srcView = textureGPU.createView( {
  40875. baseMipLevel: 0,
  40876. mipLevelCount: 1,
  40877. dimension: GPUTextureViewDimension.TwoD,
  40878. baseArrayLayer
  40879. } );
  40880. const passes = [];
  40881. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  40882. const bindGroup = this.device.createBindGroup( {
  40883. layout: bindGroupLayout,
  40884. entries: [ {
  40885. binding: 0,
  40886. resource: this.mipmapSampler
  40887. }, {
  40888. binding: 1,
  40889. resource: srcView
  40890. } ]
  40891. } );
  40892. const dstView = textureGPU.createView( {
  40893. baseMipLevel: i,
  40894. mipLevelCount: 1,
  40895. dimension: GPUTextureViewDimension.TwoD,
  40896. baseArrayLayer
  40897. } );
  40898. const passDescriptor = {
  40899. colorAttachments: [ {
  40900. view: dstView,
  40901. loadOp: GPULoadOp.Clear,
  40902. storeOp: GPUStoreOp.Store,
  40903. clearValue: [ 0, 0, 0, 0 ]
  40904. } ]
  40905. };
  40906. const passEncoder = this.device.createRenderBundleEncoder( {
  40907. colorFormats: [ textureGPUDescriptor.format ]
  40908. } );
  40909. passEncoder.setPipeline( pipeline );
  40910. passEncoder.setBindGroup( 0, bindGroup );
  40911. passEncoder.draw( 4, 1, 0, 0 );
  40912. passes.push( {
  40913. renderBundles: [ passEncoder.finish() ],
  40914. passDescriptor
  40915. } );
  40916. srcView = dstView;
  40917. }
  40918. return passes;
  40919. }
  40920. /**
  40921. * Executes the render bundles.
  40922. *
  40923. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  40924. * @param {Array} passes - An array of render bundles.
  40925. */
  40926. _mipmapRunBundles( commandEncoder, passes ) {
  40927. const levels = passes.length;
  40928. for ( let i = 0; i < levels; i ++ ) {
  40929. const pass = passes[ i ];
  40930. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  40931. passEncoder.executeBundles( pass.renderBundles );
  40932. passEncoder.end();
  40933. }
  40934. }
  40935. }
  40936. const _compareToWebGPU = {
  40937. [ NeverCompare ]: 'never',
  40938. [ LessCompare ]: 'less',
  40939. [ EqualCompare ]: 'equal',
  40940. [ LessEqualCompare ]: 'less-equal',
  40941. [ GreaterCompare ]: 'greater',
  40942. [ GreaterEqualCompare ]: 'greater-equal',
  40943. [ AlwaysCompare ]: 'always',
  40944. [ NotEqualCompare ]: 'not-equal'
  40945. };
  40946. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  40947. /**
  40948. * A WebGPU backend utility module for managing textures.
  40949. *
  40950. * @private
  40951. */
  40952. class WebGPUTextureUtils {
  40953. /**
  40954. * Constructs a new utility object.
  40955. *
  40956. * @param {WebGPUBackend} backend - The WebGPU backend.
  40957. */
  40958. constructor( backend ) {
  40959. /**
  40960. * A reference to the WebGPU backend.
  40961. *
  40962. * @type {WebGPUBackend}
  40963. */
  40964. this.backend = backend;
  40965. /**
  40966. * A reference to the pass utils.
  40967. *
  40968. * @type {WebGPUTexturePassUtils?}
  40969. * @default null
  40970. */
  40971. this._passUtils = null;
  40972. /**
  40973. * A dictionary for managing default textures. The key
  40974. * is the texture format, the value the texture object.
  40975. *
  40976. * @type {Object<String,Texture>}
  40977. */
  40978. this.defaultTexture = {};
  40979. /**
  40980. * A dictionary for managing default cube textures. The key
  40981. * is the texture format, the value the texture object.
  40982. *
  40983. * @type {Object<String,CubeTexture>}
  40984. */
  40985. this.defaultCubeTexture = {};
  40986. /**
  40987. * A default video frame.
  40988. *
  40989. * @type {VideoFrame?}
  40990. * @default null
  40991. */
  40992. this.defaultVideoFrame = null;
  40993. /**
  40994. * Represents the color attachment of the default framebuffer.
  40995. *
  40996. * @type {GPUTexture?}
  40997. * @default null
  40998. */
  40999. this.colorBuffer = null;
  41000. /**
  41001. * Represents the depth attachment of the default framebuffer.
  41002. *
  41003. * @type {DepthTexture}
  41004. */
  41005. this.depthTexture = new DepthTexture();
  41006. this.depthTexture.name = 'depthBuffer';
  41007. }
  41008. /**
  41009. * Creates a GPU sampler for the given texture.
  41010. *
  41011. * @param {Texture} texture - The texture to create the sampler for.
  41012. */
  41013. createSampler( texture ) {
  41014. const backend = this.backend;
  41015. const device = backend.device;
  41016. const textureGPU = backend.get( texture );
  41017. const samplerDescriptorGPU = {
  41018. addressModeU: this._convertAddressMode( texture.wrapS ),
  41019. addressModeV: this._convertAddressMode( texture.wrapT ),
  41020. addressModeW: this._convertAddressMode( texture.wrapR ),
  41021. magFilter: this._convertFilterMode( texture.magFilter ),
  41022. minFilter: this._convertFilterMode( texture.minFilter ),
  41023. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  41024. maxAnisotropy: 1
  41025. };
  41026. // anisotropy can only be used when all filter modes are set to linear.
  41027. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  41028. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  41029. }
  41030. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  41031. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  41032. }
  41033. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  41034. }
  41035. /**
  41036. * Creates a default texture for the given texture that can be used
  41037. * as a placeholder until the actual texture is ready for usage.
  41038. *
  41039. * @param {Texture} texture - The texture to create a default texture for.
  41040. */
  41041. createDefaultTexture( texture ) {
  41042. let textureGPU;
  41043. const format = getFormat( texture );
  41044. if ( texture.isCubeTexture ) {
  41045. textureGPU = this._getDefaultCubeTextureGPU( format );
  41046. } else if ( texture.isVideoTexture ) {
  41047. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  41048. } else {
  41049. textureGPU = this._getDefaultTextureGPU( format );
  41050. }
  41051. this.backend.get( texture ).texture = textureGPU;
  41052. }
  41053. /**
  41054. * Defines a texture on the GPU for the given texture object.
  41055. *
  41056. * @param {Texture} texture - The texture.
  41057. * @param {Object} [options={}] - Optional configuration parameter.
  41058. * @return {undefined}
  41059. */
  41060. createTexture( texture, options = {} ) {
  41061. const backend = this.backend;
  41062. const textureData = backend.get( texture );
  41063. if ( textureData.initialized ) {
  41064. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  41065. }
  41066. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  41067. if ( options.levels === undefined ) options.levels = 1;
  41068. if ( options.depth === undefined ) options.depth = 1;
  41069. const { width, height, depth, levels } = options;
  41070. if ( texture.isFramebufferTexture ) {
  41071. if ( options.renderTarget ) {
  41072. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  41073. } else {
  41074. options.format = this.backend.utils.getPreferredCanvasFormat();
  41075. }
  41076. }
  41077. const dimension = this._getDimension( texture );
  41078. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  41079. textureData.format = format;
  41080. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  41081. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  41082. if ( texture.isStorageTexture === true ) {
  41083. usage |= GPUTextureUsage.STORAGE_BINDING;
  41084. }
  41085. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  41086. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  41087. }
  41088. const textureDescriptorGPU = {
  41089. label: texture.name,
  41090. size: {
  41091. width: width,
  41092. height: height,
  41093. depthOrArrayLayers: depth,
  41094. },
  41095. mipLevelCount: levels,
  41096. sampleCount: primarySamples,
  41097. dimension: dimension,
  41098. format: format,
  41099. usage: usage
  41100. };
  41101. // texture creation
  41102. if ( texture.isVideoTexture ) {
  41103. const video = texture.source.data;
  41104. const videoFrame = new VideoFrame( video );
  41105. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  41106. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  41107. videoFrame.close();
  41108. textureData.externalTexture = video;
  41109. } else {
  41110. if ( format === undefined ) {
  41111. console.warn( 'WebGPURenderer: Texture format not supported.' );
  41112. return this.createDefaultTexture( texture );
  41113. }
  41114. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  41115. }
  41116. if ( isMSAA ) {
  41117. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  41118. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  41119. msaaTextureDescriptorGPU.sampleCount = samples;
  41120. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  41121. }
  41122. textureData.initialized = true;
  41123. textureData.textureDescriptorGPU = textureDescriptorGPU;
  41124. }
  41125. /**
  41126. * Destroys the GPU data for the given texture object.
  41127. *
  41128. * @param {Texture} texture - The texture.
  41129. */
  41130. destroyTexture( texture ) {
  41131. const backend = this.backend;
  41132. const textureData = backend.get( texture );
  41133. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  41134. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  41135. backend.delete( texture );
  41136. }
  41137. /**
  41138. * Destroys the GPU sampler for the given texture.
  41139. *
  41140. * @param {Texture} texture - The texture to destroy the sampler for.
  41141. */
  41142. destroySampler( texture ) {
  41143. const backend = this.backend;
  41144. const textureData = backend.get( texture );
  41145. delete textureData.sampler;
  41146. }
  41147. /**
  41148. * Generates mipmaps for the given texture.
  41149. *
  41150. * @param {Texture} texture - The texture.
  41151. */
  41152. generateMipmaps( texture ) {
  41153. const textureData = this.backend.get( texture );
  41154. if ( texture.isCubeTexture ) {
  41155. for ( let i = 0; i < 6; i ++ ) {
  41156. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  41157. }
  41158. } else {
  41159. const depth = texture.image.depth || 1;
  41160. for ( let i = 0; i < depth; i ++ ) {
  41161. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  41162. }
  41163. }
  41164. }
  41165. /**
  41166. * Returns the color buffer representing the color
  41167. * attachment of the default framebuffer.
  41168. *
  41169. * @return {GPUTexture} The color buffer.
  41170. */
  41171. getColorBuffer() {
  41172. if ( this.colorBuffer ) this.colorBuffer.destroy();
  41173. const backend = this.backend;
  41174. const { width, height } = backend.getDrawingBufferSize();
  41175. this.colorBuffer = backend.device.createTexture( {
  41176. label: 'colorBuffer',
  41177. size: {
  41178. width: width,
  41179. height: height,
  41180. depthOrArrayLayers: 1
  41181. },
  41182. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  41183. format: backend.utils.getPreferredCanvasFormat(),
  41184. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  41185. } );
  41186. return this.colorBuffer;
  41187. }
  41188. /**
  41189. * Returns the depth buffer representing the depth
  41190. * attachment of the default framebuffer.
  41191. *
  41192. * @param {Boolean} [depth=true] - Whether depth is enabled or not.
  41193. * @param {Boolean} [stencil=false] - Whether stencil is enabled or not.
  41194. * @return {GPUTexture} The depth buffer.
  41195. */
  41196. getDepthBuffer( depth = true, stencil = false ) {
  41197. const backend = this.backend;
  41198. const { width, height } = backend.getDrawingBufferSize();
  41199. const depthTexture = this.depthTexture;
  41200. const depthTextureGPU = backend.get( depthTexture ).texture;
  41201. let format, type;
  41202. if ( stencil ) {
  41203. format = DepthStencilFormat;
  41204. type = UnsignedInt248Type;
  41205. } else if ( depth ) {
  41206. format = DepthFormat;
  41207. type = UnsignedIntType;
  41208. }
  41209. if ( depthTextureGPU !== undefined ) {
  41210. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  41211. return depthTextureGPU;
  41212. }
  41213. this.destroyTexture( depthTexture );
  41214. }
  41215. depthTexture.name = 'depthBuffer';
  41216. depthTexture.format = format;
  41217. depthTexture.type = type;
  41218. depthTexture.image.width = width;
  41219. depthTexture.image.height = height;
  41220. this.createTexture( depthTexture, { width, height } );
  41221. return backend.get( depthTexture ).texture;
  41222. }
  41223. /**
  41224. * Uploads the updated texture data to the GPU.
  41225. *
  41226. * @param {Texture} texture - The texture.
  41227. * @param {Object} [options={}] - Optional configuration parameter.
  41228. */
  41229. updateTexture( texture, options ) {
  41230. const textureData = this.backend.get( texture );
  41231. const { textureDescriptorGPU } = textureData;
  41232. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  41233. return;
  41234. // transfer texture data
  41235. if ( texture.isDataTexture ) {
  41236. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  41237. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  41238. for ( let i = 0; i < options.image.depth; i ++ ) {
  41239. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  41240. }
  41241. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  41242. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  41243. } else if ( texture.isCubeTexture ) {
  41244. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  41245. } else if ( texture.isVideoTexture ) {
  41246. const video = texture.source.data;
  41247. textureData.externalTexture = video;
  41248. } else {
  41249. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  41250. }
  41251. //
  41252. textureData.version = texture.version;
  41253. if ( texture.onUpdate ) texture.onUpdate( texture );
  41254. }
  41255. /**
  41256. * Returns texture data as a typed array.
  41257. *
  41258. * @async
  41259. * @param {Texture} texture - The texture to copy.
  41260. * @param {Number} x - The x coordinate of the copy origin.
  41261. * @param {Number} y - The y coordinate of the copy origin.
  41262. * @param {Number} width - The width of the copy.
  41263. * @param {Number} height - The height of the copy.
  41264. * @param {Number} faceIndex - The face index.
  41265. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  41266. */
  41267. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  41268. const device = this.backend.device;
  41269. const textureData = this.backend.get( texture );
  41270. const textureGPU = textureData.texture;
  41271. const format = textureData.textureDescriptorGPU.format;
  41272. const bytesPerTexel = this._getBytesPerTexel( format );
  41273. let bytesPerRow = width * bytesPerTexel;
  41274. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  41275. const readBuffer = device.createBuffer(
  41276. {
  41277. size: width * height * bytesPerTexel,
  41278. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  41279. }
  41280. );
  41281. const encoder = device.createCommandEncoder();
  41282. encoder.copyTextureToBuffer(
  41283. {
  41284. texture: textureGPU,
  41285. origin: { x, y, z: faceIndex },
  41286. },
  41287. {
  41288. buffer: readBuffer,
  41289. bytesPerRow: bytesPerRow
  41290. },
  41291. {
  41292. width: width,
  41293. height: height
  41294. }
  41295. );
  41296. const typedArrayType = this._getTypedArrayType( format );
  41297. device.queue.submit( [ encoder.finish() ] );
  41298. await readBuffer.mapAsync( GPUMapMode.READ );
  41299. const buffer = readBuffer.getMappedRange();
  41300. return new typedArrayType( buffer );
  41301. }
  41302. /**
  41303. * Returns `true` if the given texture is an environment map.
  41304. *
  41305. * @private
  41306. * @param {Texture} texture - The texture.
  41307. * @return {Boolean} Whether the given texture is an environment map or not.
  41308. */
  41309. _isEnvironmentTexture( texture ) {
  41310. const mapping = texture.mapping;
  41311. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  41312. }
  41313. /**
  41314. * Returns the default GPU texture for the given format.
  41315. *
  41316. * @private
  41317. * @param {String} format - The GPU format.
  41318. * @return {GPUTexture} The GPU texture.
  41319. */
  41320. _getDefaultTextureGPU( format ) {
  41321. let defaultTexture = this.defaultTexture[ format ];
  41322. if ( defaultTexture === undefined ) {
  41323. const texture = new Texture();
  41324. texture.minFilter = NearestFilter;
  41325. texture.magFilter = NearestFilter;
  41326. this.createTexture( texture, { width: 1, height: 1, format } );
  41327. this.defaultTexture[ format ] = defaultTexture = texture;
  41328. }
  41329. return this.backend.get( defaultTexture ).texture;
  41330. }
  41331. /**
  41332. * Returns the default GPU cube texture for the given format.
  41333. *
  41334. * @private
  41335. * @param {String} format - The GPU format.
  41336. * @return {GPUTexture} The GPU texture.
  41337. */
  41338. _getDefaultCubeTextureGPU( format ) {
  41339. let defaultCubeTexture = this.defaultTexture[ format ];
  41340. if ( defaultCubeTexture === undefined ) {
  41341. const texture = new CubeTexture();
  41342. texture.minFilter = NearestFilter;
  41343. texture.magFilter = NearestFilter;
  41344. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  41345. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  41346. }
  41347. return this.backend.get( defaultCubeTexture ).texture;
  41348. }
  41349. /**
  41350. * Returns the default video frame used as default data in context of video textures.
  41351. *
  41352. * @private
  41353. * @return {VideoFrame} The video frame.
  41354. */
  41355. _getDefaultVideoFrame() {
  41356. let defaultVideoFrame = this.defaultVideoFrame;
  41357. if ( defaultVideoFrame === null ) {
  41358. const init = {
  41359. timestamp: 0,
  41360. codedWidth: 1,
  41361. codedHeight: 1,
  41362. format: 'RGBA',
  41363. };
  41364. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  41365. }
  41366. return defaultVideoFrame;
  41367. }
  41368. /**
  41369. * Uploads cube texture image data to the GPU memory.
  41370. *
  41371. * @private
  41372. * @param {Array} images - The cube image data.
  41373. * @param {GPUTexture} textureGPU - The GPU texture.
  41374. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  41375. * @param {Boolean} flipY - Whether to flip texture data along their vertical axis or not.
  41376. */
  41377. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  41378. for ( let i = 0; i < 6; i ++ ) {
  41379. const image = images[ i ];
  41380. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  41381. if ( image.isDataTexture ) {
  41382. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  41383. } else {
  41384. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  41385. }
  41386. }
  41387. }
  41388. /**
  41389. * Uploads texture image data to the GPU memory.
  41390. *
  41391. * @private
  41392. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  41393. * @param {GPUTexture} textureGPU - The GPU texture.
  41394. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  41395. * @param {Number} originDepth - The origin depth.
  41396. * @param {Boolean} flipY - Whether to flip texture data along their vertical axis or not.
  41397. */
  41398. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  41399. const device = this.backend.device;
  41400. device.queue.copyExternalImageToTexture(
  41401. {
  41402. source: image,
  41403. flipY: flipY
  41404. }, {
  41405. texture: textureGPU,
  41406. mipLevel: 0,
  41407. origin: { x: 0, y: 0, z: originDepth }
  41408. }, {
  41409. width: image.width,
  41410. height: image.height,
  41411. depthOrArrayLayers: 1
  41412. }
  41413. );
  41414. }
  41415. /**
  41416. * Returns the pass utils singleton.
  41417. *
  41418. * @private
  41419. * @return {WebGPUTexturePassUtils} The utils instance.
  41420. */
  41421. _getPassUtils() {
  41422. let passUtils = this._passUtils;
  41423. if ( passUtils === null ) {
  41424. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  41425. }
  41426. return passUtils;
  41427. }
  41428. /**
  41429. * Generates mipmaps for the given GPU texture.
  41430. *
  41431. * @private
  41432. * @param {GPUTexture} textureGPU - The GPU texture object.
  41433. * @param {Object} textureDescriptorGPU - The texture descriptor.
  41434. * @param {Number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  41435. */
  41436. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  41437. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  41438. }
  41439. /**
  41440. * Flip the contents of the given GPU texture along its vertical axis.
  41441. *
  41442. * @private
  41443. * @param {GPUTexture} textureGPU - The GPU texture object.
  41444. * @param {Object} textureDescriptorGPU - The texture descriptor.
  41445. * @param {Number} [originDepth=0] - The origin depth.
  41446. */
  41447. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  41448. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  41449. }
  41450. /**
  41451. * Uploads texture buffer data to the GPU memory.
  41452. *
  41453. * @private
  41454. * @param {Object} image - An object defining the image buffer data.
  41455. * @param {GPUTexture} textureGPU - The GPU texture.
  41456. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  41457. * @param {Number} originDepth - The origin depth.
  41458. * @param {Boolean} flipY - Whether to flip texture data along their vertical axis or not.
  41459. * @param {Number} [depth=0] - TODO.
  41460. */
  41461. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  41462. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  41463. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  41464. const device = this.backend.device;
  41465. const data = image.data;
  41466. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  41467. const bytesPerRow = image.width * bytesPerTexel;
  41468. device.queue.writeTexture(
  41469. {
  41470. texture: textureGPU,
  41471. mipLevel: 0,
  41472. origin: { x: 0, y: 0, z: originDepth }
  41473. },
  41474. data,
  41475. {
  41476. offset: image.width * image.height * bytesPerTexel * depth,
  41477. bytesPerRow
  41478. },
  41479. {
  41480. width: image.width,
  41481. height: image.height,
  41482. depthOrArrayLayers: 1
  41483. } );
  41484. if ( flipY === true ) {
  41485. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  41486. }
  41487. }
  41488. /**
  41489. * Uploads compressed texture data to the GPU memory.
  41490. *
  41491. * @private
  41492. * @param {Array<Object>} mipmaps - An array with mipmap data.
  41493. * @param {GPUTexture} textureGPU - The GPU texture.
  41494. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  41495. */
  41496. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  41497. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  41498. const device = this.backend.device;
  41499. const blockData = this._getBlockData( textureDescriptorGPU.format );
  41500. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  41501. for ( let i = 0; i < mipmaps.length; i ++ ) {
  41502. const mipmap = mipmaps[ i ];
  41503. const width = mipmap.width;
  41504. const height = mipmap.height;
  41505. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  41506. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  41507. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  41508. for ( let j = 0; j < depth; j ++ ) {
  41509. device.queue.writeTexture(
  41510. {
  41511. texture: textureGPU,
  41512. mipLevel: i,
  41513. origin: { x: 0, y: 0, z: j }
  41514. },
  41515. mipmap.data,
  41516. {
  41517. offset: j * bytesPerImage,
  41518. bytesPerRow,
  41519. rowsPerImage: Math.ceil( height / blockData.height )
  41520. },
  41521. {
  41522. width: Math.ceil( width / blockData.width ) * blockData.width,
  41523. height: Math.ceil( height / blockData.height ) * blockData.height,
  41524. depthOrArrayLayers: 1
  41525. }
  41526. );
  41527. }
  41528. }
  41529. }
  41530. /**
  41531. * This method is only relevant for compressed texture formats. It returns a block
  41532. * data descriptor for the given GPU compressed texture format.
  41533. *
  41534. * @private
  41535. * @param {String} format - The GPU compressed texture format.
  41536. * @return {Object} The block data descriptor.
  41537. */
  41538. _getBlockData( format ) {
  41539. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  41540. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  41541. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  41542. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  41543. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  41544. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  41545. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  41546. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  41547. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  41548. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  41549. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  41550. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  41551. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  41552. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  41553. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  41554. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  41555. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  41556. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  41557. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  41558. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  41559. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  41560. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  41561. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  41562. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  41563. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  41564. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  41565. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  41566. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  41567. }
  41568. /**
  41569. * Converts the three.js uv wrapping constants to GPU address mode constants.
  41570. *
  41571. * @private
  41572. * @param {Number} value - The three.js constant defining a uv wrapping mode.
  41573. * @return {String} The GPU address mode.
  41574. */
  41575. _convertAddressMode( value ) {
  41576. let addressMode = GPUAddressMode.ClampToEdge;
  41577. if ( value === RepeatWrapping ) {
  41578. addressMode = GPUAddressMode.Repeat;
  41579. } else if ( value === MirroredRepeatWrapping ) {
  41580. addressMode = GPUAddressMode.MirrorRepeat;
  41581. }
  41582. return addressMode;
  41583. }
  41584. /**
  41585. * Converts the three.js filter constants to GPU filter constants.
  41586. *
  41587. * @private
  41588. * @param {Number} value - The three.js constant defining a filter mode.
  41589. * @return {String} The GPU filter mode.
  41590. */
  41591. _convertFilterMode( value ) {
  41592. let filterMode = GPUFilterMode.Linear;
  41593. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  41594. filterMode = GPUFilterMode.Nearest;
  41595. }
  41596. return filterMode;
  41597. }
  41598. /**
  41599. * Returns the bytes-per-texel value for the given GPU texture format.
  41600. *
  41601. * @private
  41602. * @param {String} format - The GPU texture format.
  41603. * @return {Number} The bytes-per-texel.
  41604. */
  41605. _getBytesPerTexel( format ) {
  41606. // 8-bit formats
  41607. if ( format === GPUTextureFormat.R8Unorm ||
  41608. format === GPUTextureFormat.R8Snorm ||
  41609. format === GPUTextureFormat.R8Uint ||
  41610. format === GPUTextureFormat.R8Sint ) return 1;
  41611. // 16-bit formats
  41612. if ( format === GPUTextureFormat.R16Uint ||
  41613. format === GPUTextureFormat.R16Sint ||
  41614. format === GPUTextureFormat.R16Float ||
  41615. format === GPUTextureFormat.RG8Unorm ||
  41616. format === GPUTextureFormat.RG8Snorm ||
  41617. format === GPUTextureFormat.RG8Uint ||
  41618. format === GPUTextureFormat.RG8Sint ) return 2;
  41619. // 32-bit formats
  41620. if ( format === GPUTextureFormat.R32Uint ||
  41621. format === GPUTextureFormat.R32Sint ||
  41622. format === GPUTextureFormat.R32Float ||
  41623. format === GPUTextureFormat.RG16Uint ||
  41624. format === GPUTextureFormat.RG16Sint ||
  41625. format === GPUTextureFormat.RG16Float ||
  41626. format === GPUTextureFormat.RGBA8Unorm ||
  41627. format === GPUTextureFormat.RGBA8UnormSRGB ||
  41628. format === GPUTextureFormat.RGBA8Snorm ||
  41629. format === GPUTextureFormat.RGBA8Uint ||
  41630. format === GPUTextureFormat.RGBA8Sint ||
  41631. format === GPUTextureFormat.BGRA8Unorm ||
  41632. format === GPUTextureFormat.BGRA8UnormSRGB ||
  41633. // Packed 32-bit formats
  41634. format === GPUTextureFormat.RGB9E5UFloat ||
  41635. format === GPUTextureFormat.RGB10A2Unorm ||
  41636. format === GPUTextureFormat.RG11B10UFloat ||
  41637. format === GPUTextureFormat.Depth32Float ||
  41638. format === GPUTextureFormat.Depth24Plus ||
  41639. format === GPUTextureFormat.Depth24PlusStencil8 ||
  41640. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  41641. // 64-bit formats
  41642. if ( format === GPUTextureFormat.RG32Uint ||
  41643. format === GPUTextureFormat.RG32Sint ||
  41644. format === GPUTextureFormat.RG32Float ||
  41645. format === GPUTextureFormat.RGBA16Uint ||
  41646. format === GPUTextureFormat.RGBA16Sint ||
  41647. format === GPUTextureFormat.RGBA16Float ) return 8;
  41648. // 128-bit formats
  41649. if ( format === GPUTextureFormat.RGBA32Uint ||
  41650. format === GPUTextureFormat.RGBA32Sint ||
  41651. format === GPUTextureFormat.RGBA32Float ) return 16;
  41652. }
  41653. /**
  41654. * Returns the corresponding typed array type for the given GPU texture format.
  41655. *
  41656. * @private
  41657. * @param {String} format - The GPU texture format.
  41658. * @return {TypedArray.constructor} The typed array type.
  41659. */
  41660. _getTypedArrayType( format ) {
  41661. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  41662. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  41663. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  41664. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  41665. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  41666. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  41667. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  41668. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  41669. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  41670. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  41671. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  41672. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  41673. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  41674. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  41675. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  41676. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  41677. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  41678. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  41679. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  41680. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  41681. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  41682. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  41683. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  41684. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  41685. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  41686. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  41687. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  41688. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  41689. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  41690. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  41691. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  41692. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  41693. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  41694. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  41695. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  41696. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  41697. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  41698. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  41699. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  41700. }
  41701. /**
  41702. * Returns the GPU dimensions for the given texture.
  41703. *
  41704. * @private
  41705. * @param {Texture} texture - The texture.
  41706. * @return {String} The GPU dimension.
  41707. */
  41708. _getDimension( texture ) {
  41709. let dimension;
  41710. if ( texture.isData3DTexture ) {
  41711. dimension = GPUTextureDimension.ThreeD;
  41712. } else {
  41713. dimension = GPUTextureDimension.TwoD;
  41714. }
  41715. return dimension;
  41716. }
  41717. }
  41718. /**
  41719. * Returns the GPU format for the given texture.
  41720. *
  41721. * @param {Texture} texture - The texture.
  41722. * @param {GPUDevice?} [device=null] - The GPU device which is used for feature detection.
  41723. * It is not necessary to apply the device for most formats.
  41724. * @return {String} The GPU format.
  41725. */
  41726. function getFormat( texture, device = null ) {
  41727. const format = texture.format;
  41728. const type = texture.type;
  41729. const colorSpace = texture.colorSpace;
  41730. let formatGPU;
  41731. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  41732. switch ( format ) {
  41733. case RGBA_S3TC_DXT1_Format:
  41734. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  41735. break;
  41736. case RGBA_S3TC_DXT3_Format:
  41737. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  41738. break;
  41739. case RGBA_S3TC_DXT5_Format:
  41740. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  41741. break;
  41742. case RGB_ETC2_Format:
  41743. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  41744. break;
  41745. case RGBA_ETC2_EAC_Format:
  41746. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  41747. break;
  41748. case RGBA_ASTC_4x4_Format:
  41749. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  41750. break;
  41751. case RGBA_ASTC_5x4_Format:
  41752. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  41753. break;
  41754. case RGBA_ASTC_5x5_Format:
  41755. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  41756. break;
  41757. case RGBA_ASTC_6x5_Format:
  41758. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  41759. break;
  41760. case RGBA_ASTC_6x6_Format:
  41761. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  41762. break;
  41763. case RGBA_ASTC_8x5_Format:
  41764. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  41765. break;
  41766. case RGBA_ASTC_8x6_Format:
  41767. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  41768. break;
  41769. case RGBA_ASTC_8x8_Format:
  41770. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  41771. break;
  41772. case RGBA_ASTC_10x5_Format:
  41773. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  41774. break;
  41775. case RGBA_ASTC_10x6_Format:
  41776. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  41777. break;
  41778. case RGBA_ASTC_10x8_Format:
  41779. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  41780. break;
  41781. case RGBA_ASTC_10x10_Format:
  41782. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  41783. break;
  41784. case RGBA_ASTC_12x10_Format:
  41785. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  41786. break;
  41787. case RGBA_ASTC_12x12_Format:
  41788. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  41789. break;
  41790. case RGBAFormat:
  41791. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  41792. break;
  41793. default:
  41794. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  41795. }
  41796. } else {
  41797. switch ( format ) {
  41798. case RGBAFormat:
  41799. switch ( type ) {
  41800. case ByteType:
  41801. formatGPU = GPUTextureFormat.RGBA8Snorm;
  41802. break;
  41803. case ShortType:
  41804. formatGPU = GPUTextureFormat.RGBA16Sint;
  41805. break;
  41806. case UnsignedShortType:
  41807. formatGPU = GPUTextureFormat.RGBA16Uint;
  41808. break;
  41809. case UnsignedIntType:
  41810. formatGPU = GPUTextureFormat.RGBA32Uint;
  41811. break;
  41812. case IntType:
  41813. formatGPU = GPUTextureFormat.RGBA32Sint;
  41814. break;
  41815. case UnsignedByteType:
  41816. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  41817. break;
  41818. case HalfFloatType:
  41819. formatGPU = GPUTextureFormat.RGBA16Float;
  41820. break;
  41821. case FloatType:
  41822. formatGPU = GPUTextureFormat.RGBA32Float;
  41823. break;
  41824. default:
  41825. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  41826. }
  41827. break;
  41828. case RGBFormat:
  41829. switch ( type ) {
  41830. case UnsignedInt5999Type:
  41831. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  41832. break;
  41833. default:
  41834. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  41835. }
  41836. break;
  41837. case RedFormat:
  41838. switch ( type ) {
  41839. case ByteType:
  41840. formatGPU = GPUTextureFormat.R8Snorm;
  41841. break;
  41842. case ShortType:
  41843. formatGPU = GPUTextureFormat.R16Sint;
  41844. break;
  41845. case UnsignedShortType:
  41846. formatGPU = GPUTextureFormat.R16Uint;
  41847. break;
  41848. case UnsignedIntType:
  41849. formatGPU = GPUTextureFormat.R32Uint;
  41850. break;
  41851. case IntType:
  41852. formatGPU = GPUTextureFormat.R32Sint;
  41853. break;
  41854. case UnsignedByteType:
  41855. formatGPU = GPUTextureFormat.R8Unorm;
  41856. break;
  41857. case HalfFloatType:
  41858. formatGPU = GPUTextureFormat.R16Float;
  41859. break;
  41860. case FloatType:
  41861. formatGPU = GPUTextureFormat.R32Float;
  41862. break;
  41863. default:
  41864. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  41865. }
  41866. break;
  41867. case RGFormat:
  41868. switch ( type ) {
  41869. case ByteType:
  41870. formatGPU = GPUTextureFormat.RG8Snorm;
  41871. break;
  41872. case ShortType:
  41873. formatGPU = GPUTextureFormat.RG16Sint;
  41874. break;
  41875. case UnsignedShortType:
  41876. formatGPU = GPUTextureFormat.RG16Uint;
  41877. break;
  41878. case UnsignedIntType:
  41879. formatGPU = GPUTextureFormat.RG32Uint;
  41880. break;
  41881. case IntType:
  41882. formatGPU = GPUTextureFormat.RG32Sint;
  41883. break;
  41884. case UnsignedByteType:
  41885. formatGPU = GPUTextureFormat.RG8Unorm;
  41886. break;
  41887. case HalfFloatType:
  41888. formatGPU = GPUTextureFormat.RG16Float;
  41889. break;
  41890. case FloatType:
  41891. formatGPU = GPUTextureFormat.RG32Float;
  41892. break;
  41893. default:
  41894. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  41895. }
  41896. break;
  41897. case DepthFormat:
  41898. switch ( type ) {
  41899. case UnsignedShortType:
  41900. formatGPU = GPUTextureFormat.Depth16Unorm;
  41901. break;
  41902. case UnsignedIntType:
  41903. formatGPU = GPUTextureFormat.Depth24Plus;
  41904. break;
  41905. case FloatType:
  41906. formatGPU = GPUTextureFormat.Depth32Float;
  41907. break;
  41908. default:
  41909. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  41910. }
  41911. break;
  41912. case DepthStencilFormat:
  41913. switch ( type ) {
  41914. case UnsignedInt248Type:
  41915. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  41916. break;
  41917. case FloatType:
  41918. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  41919. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  41920. }
  41921. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  41922. break;
  41923. default:
  41924. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  41925. }
  41926. break;
  41927. case RedIntegerFormat:
  41928. switch ( type ) {
  41929. case IntType:
  41930. formatGPU = GPUTextureFormat.R32Sint;
  41931. break;
  41932. case UnsignedIntType:
  41933. formatGPU = GPUTextureFormat.R32Uint;
  41934. break;
  41935. default:
  41936. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  41937. }
  41938. break;
  41939. case RGIntegerFormat:
  41940. switch ( type ) {
  41941. case IntType:
  41942. formatGPU = GPUTextureFormat.RG32Sint;
  41943. break;
  41944. case UnsignedIntType:
  41945. formatGPU = GPUTextureFormat.RG32Uint;
  41946. break;
  41947. default:
  41948. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  41949. }
  41950. break;
  41951. case RGBAIntegerFormat:
  41952. switch ( type ) {
  41953. case IntType:
  41954. formatGPU = GPUTextureFormat.RGBA32Sint;
  41955. break;
  41956. case UnsignedIntType:
  41957. formatGPU = GPUTextureFormat.RGBA32Uint;
  41958. break;
  41959. default:
  41960. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  41961. }
  41962. break;
  41963. default:
  41964. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  41965. }
  41966. }
  41967. return formatGPU;
  41968. }
  41969. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  41970. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  41971. const wgslTypeLib$1 = {
  41972. 'f32': 'float',
  41973. 'i32': 'int',
  41974. 'u32': 'uint',
  41975. 'bool': 'bool',
  41976. 'vec2<f32>': 'vec2',
  41977. 'vec2<i32>': 'ivec2',
  41978. 'vec2<u32>': 'uvec2',
  41979. 'vec2<bool>': 'bvec2',
  41980. 'vec2f': 'vec2',
  41981. 'vec2i': 'ivec2',
  41982. 'vec2u': 'uvec2',
  41983. 'vec2b': 'bvec2',
  41984. 'vec3<f32>': 'vec3',
  41985. 'vec3<i32>': 'ivec3',
  41986. 'vec3<u32>': 'uvec3',
  41987. 'vec3<bool>': 'bvec3',
  41988. 'vec3f': 'vec3',
  41989. 'vec3i': 'ivec3',
  41990. 'vec3u': 'uvec3',
  41991. 'vec3b': 'bvec3',
  41992. 'vec4<f32>': 'vec4',
  41993. 'vec4<i32>': 'ivec4',
  41994. 'vec4<u32>': 'uvec4',
  41995. 'vec4<bool>': 'bvec4',
  41996. 'vec4f': 'vec4',
  41997. 'vec4i': 'ivec4',
  41998. 'vec4u': 'uvec4',
  41999. 'vec4b': 'bvec4',
  42000. 'mat2x2<f32>': 'mat2',
  42001. 'mat2x2f': 'mat2',
  42002. 'mat3x3<f32>': 'mat3',
  42003. 'mat3x3f': 'mat3',
  42004. 'mat4x4<f32>': 'mat4',
  42005. 'mat4x4f': 'mat4',
  42006. 'sampler': 'sampler',
  42007. 'texture_1d': 'texture',
  42008. 'texture_2d': 'texture',
  42009. 'texture_2d_array': 'texture',
  42010. 'texture_multisampled_2d': 'cubeTexture',
  42011. 'texture_depth_2d': 'depthTexture',
  42012. 'texture_depth_multisampled_2d': 'depthTexture',
  42013. 'texture_3d': 'texture3D',
  42014. 'texture_cube': 'cubeTexture',
  42015. 'texture_cube_array': 'cubeTexture',
  42016. 'texture_storage_1d': 'storageTexture',
  42017. 'texture_storage_2d': 'storageTexture',
  42018. 'texture_storage_2d_array': 'storageTexture',
  42019. 'texture_storage_3d': 'storageTexture'
  42020. };
  42021. const parse = ( source ) => {
  42022. source = source.trim();
  42023. const declaration = source.match( declarationRegexp );
  42024. if ( declaration !== null && declaration.length === 4 ) {
  42025. const inputsCode = declaration[ 2 ];
  42026. const propsMatches = [];
  42027. let match = null;
  42028. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  42029. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  42030. }
  42031. // Process matches to correctly pair names and types
  42032. const inputs = [];
  42033. for ( let i = 0; i < propsMatches.length; i ++ ) {
  42034. const { name, type } = propsMatches[ i ];
  42035. let resolvedType = type;
  42036. if ( resolvedType.startsWith( 'ptr' ) ) {
  42037. resolvedType = 'pointer';
  42038. } else {
  42039. if ( resolvedType.startsWith( 'texture' ) ) {
  42040. resolvedType = type.split( '<' )[ 0 ];
  42041. }
  42042. resolvedType = wgslTypeLib$1[ resolvedType ];
  42043. }
  42044. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  42045. }
  42046. const blockCode = source.substring( declaration[ 0 ].length );
  42047. const outputType = declaration[ 3 ] || 'void';
  42048. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  42049. const type = wgslTypeLib$1[ outputType ] || outputType;
  42050. return {
  42051. type,
  42052. inputs,
  42053. name,
  42054. inputsCode,
  42055. blockCode,
  42056. outputType
  42057. };
  42058. } else {
  42059. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  42060. }
  42061. };
  42062. /**
  42063. * This class represents a WSL node function.
  42064. *
  42065. * @augments NodeFunction
  42066. */
  42067. class WGSLNodeFunction extends NodeFunction {
  42068. /**
  42069. * Constructs a new WGSL node function.
  42070. *
  42071. * @param {String} source - The WGSL source.
  42072. */
  42073. constructor( source ) {
  42074. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  42075. super( type, inputs, name );
  42076. this.inputsCode = inputsCode;
  42077. this.blockCode = blockCode;
  42078. this.outputType = outputType;
  42079. }
  42080. /**
  42081. * This method returns the WGSL code of the node function.
  42082. *
  42083. * @param {String} [name=this.name] - The function's name.
  42084. * @return {String} The shader code.
  42085. */
  42086. getCode( name = this.name ) {
  42087. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  42088. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  42089. }
  42090. }
  42091. /**
  42092. * A WGSL node parser.
  42093. *
  42094. * @augments NodeParser
  42095. */
  42096. class WGSLNodeParser extends NodeParser {
  42097. /**
  42098. * The method parses the given WGSL code an returns a node function.
  42099. *
  42100. * @param {String} source - The WGSL code.
  42101. * @return {WGSLNodeFunction} A node function.
  42102. */
  42103. parseFunction( source ) {
  42104. return new WGSLNodeFunction( source );
  42105. }
  42106. }
  42107. // GPUShaderStage is not defined in browsers not supporting WebGPU
  42108. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  42109. const accessNames = {
  42110. [ NodeAccess.READ_ONLY ]: 'read',
  42111. [ NodeAccess.WRITE_ONLY ]: 'write',
  42112. [ NodeAccess.READ_WRITE ]: 'read_write'
  42113. };
  42114. const wrapNames = {
  42115. [ RepeatWrapping ]: 'repeat',
  42116. [ ClampToEdgeWrapping ]: 'clamp',
  42117. [ MirroredRepeatWrapping ]: 'mirror'
  42118. };
  42119. const gpuShaderStageLib = {
  42120. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  42121. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  42122. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  42123. };
  42124. const supports = {
  42125. instance: true,
  42126. swizzleAssign: false,
  42127. storageBuffer: true
  42128. };
  42129. const wgslFnOpLib = {
  42130. '^^': 'tsl_xor'
  42131. };
  42132. const wgslTypeLib = {
  42133. float: 'f32',
  42134. int: 'i32',
  42135. uint: 'u32',
  42136. bool: 'bool',
  42137. color: 'vec3<f32>',
  42138. vec2: 'vec2<f32>',
  42139. ivec2: 'vec2<i32>',
  42140. uvec2: 'vec2<u32>',
  42141. bvec2: 'vec2<bool>',
  42142. vec3: 'vec3<f32>',
  42143. ivec3: 'vec3<i32>',
  42144. uvec3: 'vec3<u32>',
  42145. bvec3: 'vec3<bool>',
  42146. vec4: 'vec4<f32>',
  42147. ivec4: 'vec4<i32>',
  42148. uvec4: 'vec4<u32>',
  42149. bvec4: 'vec4<bool>',
  42150. mat2: 'mat2x2<f32>',
  42151. mat3: 'mat3x3<f32>',
  42152. mat4: 'mat4x4<f32>'
  42153. };
  42154. const wgslCodeCache = {};
  42155. const wgslPolyfill = {
  42156. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  42157. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  42158. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  42159. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  42160. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  42161. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  42162. 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 ); }' ),
  42163. 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 ); }' ),
  42164. 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 ); }' ),
  42165. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  42166. 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 ); }' ),
  42167. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  42168. biquadraticTexture: new CodeNode( /* wgsl */`
  42169. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  42170. let res = vec2f( iRes );
  42171. let uvScaled = coord * res;
  42172. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  42173. // https://www.shadertoy.com/view/WtyXRy
  42174. let uv = uvWrapping - 0.5;
  42175. let iuv = floor( uv );
  42176. let f = fract( uv );
  42177. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  42178. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  42179. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  42180. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  42181. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  42182. }
  42183. ` )
  42184. };
  42185. const wgslMethods = {
  42186. dFdx: 'dpdx',
  42187. dFdy: '- dpdy',
  42188. mod_float: 'tsl_mod_float',
  42189. mod_vec2: 'tsl_mod_vec2',
  42190. mod_vec3: 'tsl_mod_vec3',
  42191. mod_vec4: 'tsl_mod_vec4',
  42192. equals_bool: 'tsl_equals_bool',
  42193. equals_bvec2: 'tsl_equals_bvec2',
  42194. equals_bvec3: 'tsl_equals_bvec3',
  42195. equals_bvec4: 'tsl_equals_bvec4',
  42196. inversesqrt: 'inverseSqrt',
  42197. bitcast: 'bitcast<f32>'
  42198. };
  42199. // WebGPU issue: does not support pow() with negative base on Windows
  42200. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  42201. 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 ); }' );
  42202. 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 ] );
  42203. 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 ] );
  42204. 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 ] );
  42205. wgslMethods.pow_float = 'tsl_pow_float';
  42206. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  42207. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  42208. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  42209. }
  42210. //
  42211. let diagnostics = '';
  42212. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  42213. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  42214. }
  42215. /**
  42216. * A node builder targeting WGSL.
  42217. *
  42218. * This module generates WGSL shader code from node materials and also
  42219. * generates the respective bindings and vertex buffer definitions. These
  42220. * data are later used by the renderer to create render and compute pipelines
  42221. * for render objects.
  42222. *
  42223. * @augments NodeBuilder
  42224. */
  42225. class WGSLNodeBuilder extends NodeBuilder {
  42226. /**
  42227. * Constructs a new WGSL node builder renderer.
  42228. *
  42229. * @param {Object3D} object - The 3D object.
  42230. * @param {Renderer} renderer - The renderer.
  42231. */
  42232. constructor( object, renderer ) {
  42233. super( object, renderer, new WGSLNodeParser() );
  42234. /**
  42235. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  42236. * another dictionary which manages UBOs per group ('render','frame','object').
  42237. *
  42238. * @type {Object<String,Object<String,NodeUniformsGroup>>}
  42239. */
  42240. this.uniformGroups = {};
  42241. /**
  42242. * A dictionary that holds for each shader stage a Map of builtins.
  42243. *
  42244. * @type {Object<String,Map<String,Object>>}
  42245. */
  42246. this.builtins = {};
  42247. /**
  42248. * A dictionary that holds for each shader stage a Set of directives.
  42249. *
  42250. * @type {Object<String,Set<String>>}
  42251. */
  42252. this.directives = {};
  42253. /**
  42254. * A map for managing scope arrays. Only relevant for when using
  42255. * {@link module:WorkgroupInfoNode} in context of compute shaders.
  42256. *
  42257. * @type {Map<String,Object>}
  42258. */
  42259. this.scopedArrays = new Map();
  42260. }
  42261. /**
  42262. * Checks if the given texture requires a manual conversion to the working color space.
  42263. *
  42264. * @param {Texture} texture - The texture to check.
  42265. * @return {Boolean} Whether the given texture requires a conversion to working color space or not.
  42266. */
  42267. needsToWorkingColorSpace( texture ) {
  42268. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  42269. }
  42270. /**
  42271. * Generates the WGSL snippet for sampled textures.
  42272. *
  42273. * @private
  42274. * @param {Texture} texture - The texture.
  42275. * @param {String} textureProperty - The name of the texture uniform in the shader.
  42276. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  42277. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  42278. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  42279. * @return {String} The WGSL snippet.
  42280. */
  42281. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42282. if ( shaderStage === 'fragment' ) {
  42283. if ( depthSnippet ) {
  42284. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  42285. } else {
  42286. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  42287. }
  42288. } else if ( this.isFilteredTexture( texture ) ) {
  42289. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  42290. } else {
  42291. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0' );
  42292. }
  42293. }
  42294. /**
  42295. * Generates the WGSL snippet when sampling video textures.
  42296. *
  42297. * @private
  42298. * @param {String} textureProperty - The name of the video texture uniform in the shader.
  42299. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  42300. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  42301. * @return {String} The WGSL snippet.
  42302. */
  42303. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  42304. if ( shaderStage === 'fragment' ) {
  42305. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  42306. } else {
  42307. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  42308. }
  42309. }
  42310. /**
  42311. * Generates the WGSL snippet when sampling textures with explicit mip level.
  42312. *
  42313. * @private
  42314. * @param {Texture} texture - The texture.
  42315. * @param {String} textureProperty - The name of the texture uniform in the shader.
  42316. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  42317. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  42318. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  42319. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  42320. * @return {String} The WGSL snippet.
  42321. */
  42322. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42323. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false ) {
  42324. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  42325. } else if ( this.isFilteredTexture( texture ) ) {
  42326. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  42327. } else {
  42328. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  42329. }
  42330. }
  42331. /**
  42332. * Generates a wrap function used in context of textures.
  42333. *
  42334. * @param {Texture} texture - The texture to generate the function for.
  42335. * @return {String} The name of the generated function.
  42336. */
  42337. generateWrapFunction( texture ) {
  42338. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${texture.isData3DTexture ? '3d' : '2d'}T`;
  42339. let nodeCode = wgslCodeCache[ functionName ];
  42340. if ( nodeCode === undefined ) {
  42341. const includes = [];
  42342. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  42343. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  42344. let code = `fn ${functionName}( coord : ${coordType} ) -> ${coordType} {\n\n\treturn ${coordType}(\n`;
  42345. const addWrapSnippet = ( wrap, axis ) => {
  42346. if ( wrap === RepeatWrapping ) {
  42347. includes.push( wgslPolyfill.repeatWrapping_float );
  42348. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  42349. } else if ( wrap === ClampToEdgeWrapping ) {
  42350. includes.push( wgslPolyfill.clampWrapping_float );
  42351. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  42352. } else if ( wrap === MirroredRepeatWrapping ) {
  42353. includes.push( wgslPolyfill.mirrorWrapping_float );
  42354. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  42355. } else {
  42356. code += `\t\tcoord.${ axis }`;
  42357. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  42358. }
  42359. };
  42360. addWrapSnippet( texture.wrapS, 'x' );
  42361. code += ',\n';
  42362. addWrapSnippet( texture.wrapT, 'y' );
  42363. if ( texture.isData3DTexture ) {
  42364. code += ',\n';
  42365. addWrapSnippet( texture.wrapR, 'z' );
  42366. }
  42367. code += '\n\t);\n\n}\n';
  42368. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  42369. }
  42370. nodeCode.build( this );
  42371. return functionName;
  42372. }
  42373. /**
  42374. * Generates a WGSL variable that holds the texture dimension of the given texture.
  42375. * It also returns information about the the number of layers (elements) of an arrayed
  42376. * texture as well as the cube face count of cube textures.
  42377. *
  42378. * @param {Texture} texture - The texture to generate the function for.
  42379. * @param {String} textureProperty - The name of the video texture uniform in the shader.
  42380. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  42381. * @return {String} The name of the dimension variable.
  42382. */
  42383. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  42384. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  42385. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  42386. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  42387. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  42388. let textureDimensionsParams;
  42389. let dimensionType;
  42390. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  42391. const isMultisampled = primarySamples > 1;
  42392. if ( texture.isData3DTexture ) {
  42393. dimensionType = 'vec3<u32>';
  42394. } else {
  42395. // Regular 2D textures, depth textures, etc.
  42396. dimensionType = 'vec2<u32>';
  42397. }
  42398. // Build parameters string based on texture type and multisampling
  42399. if ( isMultisampled || texture.isVideoTexture || texture.isStorageTexture ) {
  42400. textureDimensionsParams = textureProperty;
  42401. } else {
  42402. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  42403. }
  42404. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  42405. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  42406. if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  42407. textureData.arrayLayerCount = new VarNode(
  42408. new ExpressionNode(
  42409. `textureNumLayers(${textureProperty})`,
  42410. 'u32'
  42411. )
  42412. );
  42413. }
  42414. // For cube textures, we know it's always 6 faces
  42415. if ( texture.isTextureCube ) {
  42416. textureData.cubeFaceCount = new VarNode(
  42417. new ExpressionNode( '6u', 'u32' )
  42418. );
  42419. }
  42420. }
  42421. return textureDimensionNode.build( this );
  42422. }
  42423. /**
  42424. * Generates the WGSL snippet for a manual filtered texture.
  42425. *
  42426. * @param {Texture} texture - The texture.
  42427. * @param {String} textureProperty - The name of the texture uniform in the shader.
  42428. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  42429. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  42430. * @return {String} The WGSL snippet.
  42431. */
  42432. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  42433. this._include( 'biquadraticTexture' );
  42434. const wrapFunction = this.generateWrapFunction( texture );
  42435. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  42436. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  42437. }
  42438. /**
  42439. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  42440. * Since it's a lookup, no sampling or filtering is applied.
  42441. *
  42442. * @param {Texture} texture - The texture.
  42443. * @param {String} textureProperty - The name of the texture uniform in the shader.
  42444. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  42445. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  42446. * @param {String} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  42447. * @return {String} The WGSL snippet.
  42448. */
  42449. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  42450. const wrapFunction = this.generateWrapFunction( texture );
  42451. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  42452. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  42453. const coordSnippet = `${vecType}<u32>(${wrapFunction}(${uvSnippet}) * ${vecType}<f32>(${textureDimension}))`;
  42454. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  42455. }
  42456. /**
  42457. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  42458. *
  42459. * @param {Texture} texture - The texture.
  42460. * @param {String} textureProperty - The name of the texture uniform in the shader.
  42461. * @param {String} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  42462. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  42463. * @param {String} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  42464. * @return {String} The WGSL snippet.
  42465. */
  42466. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  42467. if ( texture.isVideoTexture === true || texture.isStorageTexture === true ) {
  42468. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  42469. } else if ( depthSnippet ) {
  42470. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  42471. } else {
  42472. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  42473. }
  42474. }
  42475. /**
  42476. * Generates the WGSL snippet that writes a single texel to a texture.
  42477. *
  42478. * @param {Texture} texture - The texture.
  42479. * @param {String} textureProperty - The name of the texture uniform in the shader.
  42480. * @param {String} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  42481. * @param {String} valueSnippet - A WGSL snippet that represent the new texel value.
  42482. * @return {String} The WGSL snippet.
  42483. */
  42484. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  42485. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  42486. }
  42487. /**
  42488. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  42489. *
  42490. * @param {Texture} texture - The texture.
  42491. * @return {Boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  42492. */
  42493. isSampleCompare( texture ) {
  42494. return texture.isDepthTexture === true && texture.compareFunction !== null;
  42495. }
  42496. /**
  42497. * Returns `true` if the given texture is unfilterable.
  42498. *
  42499. * @param {Texture} texture - The texture.
  42500. * @return {Boolean} Whether the given texture is unfilterable or not.
  42501. */
  42502. isUnfilterable( texture ) {
  42503. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  42504. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  42505. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  42506. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  42507. }
  42508. /**
  42509. * Generates the WGSL snippet for sampling/loading the given texture.
  42510. *
  42511. * @param {Texture} texture - The texture.
  42512. * @param {String} textureProperty - The name of the texture uniform in the shader.
  42513. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  42514. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  42515. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  42516. * @return {String} The WGSL snippet.
  42517. */
  42518. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42519. let snippet = null;
  42520. if ( texture.isVideoTexture === true ) {
  42521. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  42522. } else if ( this.isUnfilterable( texture ) ) {
  42523. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  42524. } else {
  42525. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  42526. }
  42527. return snippet;
  42528. }
  42529. /**
  42530. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  42531. *
  42532. * @param {Texture} texture - The texture.
  42533. * @param {String} textureProperty - The name of the texture uniform in the shader.
  42534. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  42535. * @param {Array<String>} gradSnippet - An array holding both gradient WGSL snippets.
  42536. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  42537. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  42538. * @return {String} The WGSL snippet.
  42539. */
  42540. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42541. if ( shaderStage === 'fragment' ) {
  42542. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  42543. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  42544. } else {
  42545. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  42546. }
  42547. }
  42548. /**
  42549. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  42550. * against a reference value.
  42551. *
  42552. * @param {Texture} texture - The texture.
  42553. * @param {String} textureProperty - The name of the texture uniform in the shader.
  42554. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  42555. * @param {String} compareSnippet - A WGSL snippet that represents the reference value.
  42556. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  42557. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  42558. * @return {String} The WGSL snippet.
  42559. */
  42560. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42561. if ( shaderStage === 'fragment' ) {
  42562. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  42563. } else {
  42564. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  42565. }
  42566. }
  42567. /**
  42568. * Generates the WGSL snippet when sampling textures with explicit mip level.
  42569. *
  42570. * @param {Texture} texture - The texture.
  42571. * @param {String} textureProperty - The name of the texture uniform in the shader.
  42572. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  42573. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  42574. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  42575. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  42576. * @return {String} The WGSL snippet.
  42577. */
  42578. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42579. let snippet = null;
  42580. if ( texture.isVideoTexture === true ) {
  42581. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  42582. } else {
  42583. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  42584. }
  42585. return snippet;
  42586. }
  42587. /**
  42588. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  42589. *
  42590. * @param {Texture} texture - The texture.
  42591. * @param {String} textureProperty - The name of the texture uniform in the shader.
  42592. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  42593. * @param {String} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  42594. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  42595. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  42596. * @return {String} The WGSL snippet.
  42597. */
  42598. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42599. if ( shaderStage === 'fragment' ) {
  42600. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  42601. } else {
  42602. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  42603. }
  42604. }
  42605. /**
  42606. * Returns a WGSL snippet that represents the property name of the given node.
  42607. *
  42608. * @param {Node} node - The node.
  42609. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  42610. * @return {String} The property name.
  42611. */
  42612. getPropertyName( node, shaderStage = this.shaderStage ) {
  42613. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  42614. if ( shaderStage === 'vertex' ) {
  42615. return `varyings.${ node.name }`;
  42616. }
  42617. } else if ( node.isNodeUniform === true ) {
  42618. const name = node.name;
  42619. const type = node.type;
  42620. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  42621. return name;
  42622. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  42623. return `NodeBuffer_${ node.id }.${name}`;
  42624. } else {
  42625. return node.groupNode.name + '.' + name;
  42626. }
  42627. }
  42628. return super.getPropertyName( node );
  42629. }
  42630. /**
  42631. * Returns the output struct name.
  42632. *
  42633. * @return {String} The name of the output struct.
  42634. */
  42635. getOutputStructName() {
  42636. return 'output';
  42637. }
  42638. /**
  42639. * Returns uniforms group count for the given shader stage.
  42640. *
  42641. * @private
  42642. * @param {String} shaderStage - The shader stage.
  42643. * @return {Number} The uniforms group count for the given shader stage.
  42644. */
  42645. _getUniformGroupCount( shaderStage ) {
  42646. return Object.keys( this.uniforms[ shaderStage ] ).length;
  42647. }
  42648. /**
  42649. * Returns the native shader operator name for a given generic name.
  42650. *
  42651. * @param {String} op - The operator name to resolve.
  42652. * @return {String} The resolved operator name.
  42653. */
  42654. getFunctionOperator( op ) {
  42655. const fnOp = wgslFnOpLib[ op ];
  42656. if ( fnOp !== undefined ) {
  42657. this._include( fnOp );
  42658. return fnOp;
  42659. }
  42660. return null;
  42661. }
  42662. /**
  42663. * Returns the node access for the given node and shader stage.
  42664. *
  42665. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  42666. * @param {String} shaderStage - The shader stage.
  42667. * @return {String} The node access.
  42668. */
  42669. getNodeAccess( node, shaderStage ) {
  42670. if ( shaderStage !== 'compute' )
  42671. return NodeAccess.READ_ONLY;
  42672. return node.access;
  42673. }
  42674. /**
  42675. * Returns A WGSL snippet representing the storage access.
  42676. *
  42677. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  42678. * @param {String} shaderStage - The shader stage.
  42679. * @return {String} The WGSL snippet representing the storage access.
  42680. */
  42681. getStorageAccess( node, shaderStage ) {
  42682. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  42683. }
  42684. /**
  42685. * This method is one of the more important ones since it's responsible
  42686. * for generating a matching binding instance for the given uniform node.
  42687. *
  42688. * These bindings are later used in the renderer to create bind groups
  42689. * and layouts.
  42690. *
  42691. * @param {UniformNode} node - The uniform node.
  42692. * @param {String} type - The node data type.
  42693. * @param {String} shaderStage - The shader stage.
  42694. * @param {String?} [name=null] - An optional uniform name.
  42695. * @return {NodeUniform} The node uniform object.
  42696. */
  42697. getUniformFromNode( node, type, shaderStage, name = null ) {
  42698. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  42699. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  42700. if ( nodeData.uniformGPU === undefined ) {
  42701. let uniformGPU;
  42702. const group = node.groupNode;
  42703. const groupName = group.name;
  42704. const bindings = this.getBindGroupArray( groupName, shaderStage );
  42705. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  42706. let texture = null;
  42707. const access = this.getNodeAccess( node, shaderStage );
  42708. if ( type === 'texture' || type === 'storageTexture' ) {
  42709. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  42710. } else if ( type === 'cubeTexture' ) {
  42711. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  42712. } else if ( type === 'texture3D' ) {
  42713. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  42714. }
  42715. texture.store = node.isStorageTextureNode === true;
  42716. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42717. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  42718. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  42719. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42720. bindings.push( sampler, texture );
  42721. uniformGPU = [ sampler, texture ];
  42722. } else {
  42723. bindings.push( texture );
  42724. uniformGPU = [ texture ];
  42725. }
  42726. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  42727. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  42728. const buffer = new bufferClass( node, group );
  42729. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42730. bindings.push( buffer );
  42731. uniformGPU = buffer;
  42732. } else {
  42733. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  42734. let uniformsGroup = uniformsStage[ groupName ];
  42735. if ( uniformsGroup === undefined ) {
  42736. uniformsGroup = new NodeUniformsGroup( groupName, group );
  42737. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42738. uniformsStage[ groupName ] = uniformsGroup;
  42739. bindings.push( uniformsGroup );
  42740. }
  42741. uniformGPU = this.getNodeUniform( uniformNode, type );
  42742. uniformsGroup.addUniform( uniformGPU );
  42743. }
  42744. nodeData.uniformGPU = uniformGPU;
  42745. }
  42746. return uniformNode;
  42747. }
  42748. /**
  42749. * This method should be used whenever builtins are required in nodes.
  42750. * The internal builtins data structure will make sure builtins are
  42751. * defined in the WGSL source.
  42752. *
  42753. * @param {String} name - The builtin name.
  42754. * @param {String} property - The property name.
  42755. * @param {String} type - The node data type.
  42756. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  42757. * @return {String} The property name.
  42758. */
  42759. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  42760. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  42761. if ( map.has( name ) === false ) {
  42762. map.set( name, {
  42763. name,
  42764. property,
  42765. type
  42766. } );
  42767. }
  42768. return property;
  42769. }
  42770. /**
  42771. * Returns `true` if the given builtin is defined in the given shader stage.
  42772. *
  42773. * @param {String} name - The builtin name.
  42774. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  42775. * @return {String} Whether the given builtin is defined in the given shader stage or not.
  42776. */
  42777. hasBuiltin( name, shaderStage = this.shaderStage ) {
  42778. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  42779. }
  42780. /**
  42781. * Returns the vertex index builtin.
  42782. *
  42783. * @return {String} The vertex index.
  42784. */
  42785. getVertexIndex() {
  42786. if ( this.shaderStage === 'vertex' ) {
  42787. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  42788. }
  42789. return 'vertexIndex';
  42790. }
  42791. /**
  42792. * Builds the given shader node.
  42793. *
  42794. * @param {ShaderNodeInternal} shaderNode - The shader node.
  42795. * @return {String} The WGSL function code.
  42796. */
  42797. buildFunctionCode( shaderNode ) {
  42798. const layout = shaderNode.layout;
  42799. const flowData = this.flowShaderNode( shaderNode );
  42800. const parameters = [];
  42801. for ( const input of layout.inputs ) {
  42802. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  42803. }
  42804. //
  42805. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  42806. ${ flowData.vars }
  42807. ${ flowData.code }
  42808. `;
  42809. if ( flowData.result ) {
  42810. code += `\treturn ${ flowData.result };\n`;
  42811. }
  42812. code += '\n}\n';
  42813. //
  42814. return code;
  42815. }
  42816. /**
  42817. * Returns the instance index builtin.
  42818. *
  42819. * @return {String} The instance index.
  42820. */
  42821. getInstanceIndex() {
  42822. if ( this.shaderStage === 'vertex' ) {
  42823. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  42824. }
  42825. return 'instanceIndex';
  42826. }
  42827. /**
  42828. * Returns the invocation local index builtin.
  42829. *
  42830. * @return {String} The invocation local index.
  42831. */
  42832. getInvocationLocalIndex() {
  42833. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  42834. }
  42835. /**
  42836. * Returns the subgroup size builtin.
  42837. *
  42838. * @return {String} The subgroup size.
  42839. */
  42840. getSubgroupSize() {
  42841. this.enableSubGroups();
  42842. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  42843. }
  42844. /**
  42845. * Returns the invocation subgroup index builtin.
  42846. *
  42847. * @return {String} The invocation subgroup index.
  42848. */
  42849. getInvocationSubgroupIndex() {
  42850. this.enableSubGroups();
  42851. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  42852. }
  42853. /**
  42854. * Returns the subgroup index builtin.
  42855. *
  42856. * @return {String} The subgroup index.
  42857. */
  42858. getSubgroupIndex() {
  42859. this.enableSubGroups();
  42860. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  42861. }
  42862. /**
  42863. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  42864. *
  42865. * @return {null} Null.
  42866. */
  42867. getDrawIndex() {
  42868. return null;
  42869. }
  42870. /**
  42871. * Returns the front facing builtin.
  42872. *
  42873. * @return {String} The front facing builtin.
  42874. */
  42875. getFrontFacing() {
  42876. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  42877. }
  42878. /**
  42879. * Returns the frag coord builtin.
  42880. *
  42881. * @return {String} The frag coord builtin.
  42882. */
  42883. getFragCoord() {
  42884. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  42885. }
  42886. /**
  42887. * Returns the frag depth builtin.
  42888. *
  42889. * @return {String} The frag depth builtin.
  42890. */
  42891. getFragDepth() {
  42892. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  42893. }
  42894. /**
  42895. * Returns the clip distances builtin.
  42896. *
  42897. * @return {String} The clip distances builtin.
  42898. */
  42899. getClipDistance() {
  42900. return 'varyings.hw_clip_distances';
  42901. }
  42902. /**
  42903. * Whether to flip texture data along its vertical axis or not.
  42904. *
  42905. * @return {Boolean} Returns always `false` in context of WGSL.
  42906. */
  42907. isFlipY() {
  42908. return false;
  42909. }
  42910. /**
  42911. * Enables the given directive for the given shader stage.
  42912. *
  42913. * @param {String} name - The directive name.
  42914. * @param {String} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  42915. */
  42916. enableDirective( name, shaderStage = this.shaderStage ) {
  42917. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  42918. stage.add( name );
  42919. }
  42920. /**
  42921. * Returns the directives of the given shader stage as a WGSL string.
  42922. *
  42923. * @param {String} shaderStage - The shader stage.
  42924. * @return {String} A WGSL snippet that enables the directives of the given stage.
  42925. */
  42926. getDirectives( shaderStage ) {
  42927. const snippets = [];
  42928. const directives = this.directives[ shaderStage ];
  42929. if ( directives !== undefined ) {
  42930. for ( const directive of directives ) {
  42931. snippets.push( `enable ${directive};` );
  42932. }
  42933. }
  42934. return snippets.join( '\n' );
  42935. }
  42936. /**
  42937. * Enables the 'subgroups' directive.
  42938. */
  42939. enableSubGroups() {
  42940. this.enableDirective( 'subgroups' );
  42941. }
  42942. /**
  42943. * Enables the 'subgroups-f16' directive.
  42944. */
  42945. enableSubgroupsF16() {
  42946. this.enableDirective( 'subgroups-f16' );
  42947. }
  42948. /**
  42949. * Enables the 'clip_distances' directive.
  42950. */
  42951. enableClipDistances() {
  42952. this.enableDirective( 'clip_distances' );
  42953. }
  42954. /**
  42955. * Enables the 'f16' directive.
  42956. */
  42957. enableShaderF16() {
  42958. this.enableDirective( 'f16' );
  42959. }
  42960. /**
  42961. * Enables the 'dual_source_blending' directive.
  42962. */
  42963. enableDualSourceBlending() {
  42964. this.enableDirective( 'dual_source_blending' );
  42965. }
  42966. /**
  42967. * Enables hardware clipping.
  42968. *
  42969. * @param {String} planeCount - The clipping plane count.
  42970. */
  42971. enableHardwareClipping( planeCount ) {
  42972. this.enableClipDistances();
  42973. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  42974. }
  42975. /**
  42976. * Returns the builtins of the given shader stage as a WGSL string.
  42977. *
  42978. * @param {String} shaderStage - The shader stage.
  42979. * @return {String} A WGSL snippet that represents the builtins of the given stage.
  42980. */
  42981. getBuiltins( shaderStage ) {
  42982. const snippets = [];
  42983. const builtins = this.builtins[ shaderStage ];
  42984. if ( builtins !== undefined ) {
  42985. for ( const { name, property, type } of builtins.values() ) {
  42986. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  42987. }
  42988. }
  42989. return snippets.join( ',\n\t' );
  42990. }
  42991. /**
  42992. * This method should be used when a new scoped buffer is used in context of
  42993. * compute shaders. It adds the array to the internal data structure which is
  42994. * later used to generate the respective WGSL.
  42995. *
  42996. * @param {String} name - The array name.
  42997. * @param {String} scope - The scope.
  42998. * @param {String} bufferType - The buffer type.
  42999. * @param {String} bufferCount - The buffer count.
  43000. * @return {String} The array name.
  43001. */
  43002. getScopedArray( name, scope, bufferType, bufferCount ) {
  43003. if ( this.scopedArrays.has( name ) === false ) {
  43004. this.scopedArrays.set( name, {
  43005. name,
  43006. scope,
  43007. bufferType,
  43008. bufferCount
  43009. } );
  43010. }
  43011. return name;
  43012. }
  43013. /**
  43014. * Returns the scoped arrays of the given shader stage as a WGSL string.
  43015. *
  43016. * @param {String} shaderStage - The shader stage.
  43017. * @return {String|undefined} The WGSL snippet that defines the scoped arrays.
  43018. * Returns `undefined` when used in the vertex or fragment stage.
  43019. */
  43020. getScopedArrays( shaderStage ) {
  43021. if ( shaderStage !== 'compute' ) {
  43022. return;
  43023. }
  43024. const snippets = [];
  43025. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  43026. const type = this.getType( bufferType );
  43027. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  43028. }
  43029. return snippets.join( '\n' );
  43030. }
  43031. /**
  43032. * Returns the shader attributes of the given shader stage as a WGSL string.
  43033. *
  43034. * @param {String} shaderStage - The shader stage.
  43035. * @return {String} The WGSL snippet that defines the shader attributes.
  43036. */
  43037. getAttributes( shaderStage ) {
  43038. const snippets = [];
  43039. if ( shaderStage === 'compute' ) {
  43040. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  43041. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  43042. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  43043. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  43044. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  43045. this.enableDirective( 'subgroups', shaderStage );
  43046. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  43047. }
  43048. }
  43049. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  43050. const builtins = this.getBuiltins( 'attribute' );
  43051. if ( builtins ) snippets.push( builtins );
  43052. const attributes = this.getAttributesArray();
  43053. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  43054. const attribute = attributes[ index ];
  43055. const name = attribute.name;
  43056. const type = this.getType( attribute.type );
  43057. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  43058. }
  43059. }
  43060. return snippets.join( ',\n\t' );
  43061. }
  43062. /**
  43063. * Returns the members of the given struct type node as a WGSL string.
  43064. *
  43065. * @param {StructTypeNode} struct - The struct type node.
  43066. * @return {String} The WGSL snippet that defines the struct members.
  43067. */
  43068. getStructMembers( struct ) {
  43069. const snippets = [];
  43070. const members = struct.getMemberTypes();
  43071. for ( let i = 0; i < members.length; i ++ ) {
  43072. const member = members[ i ];
  43073. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  43074. }
  43075. const builtins = this.getBuiltins( 'output' );
  43076. if ( builtins ) snippets.push( '\t' + builtins );
  43077. return snippets.join( ',\n' );
  43078. }
  43079. /**
  43080. * Returns the structs of the given shader stage as a WGSL string.
  43081. *
  43082. * @param {String} shaderStage - The shader stage.
  43083. * @return {String} The WGSL snippet that defines the structs.
  43084. */
  43085. getStructs( shaderStage ) {
  43086. const snippets = [];
  43087. const structs = this.structs[ shaderStage ];
  43088. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  43089. const struct = structs[ index ];
  43090. const name = struct.name;
  43091. let snippet = `\struct ${ name } {\n`;
  43092. snippet += this.getStructMembers( struct );
  43093. snippet += '\n}';
  43094. snippets.push( snippet );
  43095. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  43096. }
  43097. return snippets.join( '\n\n' );
  43098. }
  43099. /**
  43100. * Returns a WGSL string representing a variable.
  43101. *
  43102. * @param {String} type - The variable's type.
  43103. * @param {String} name - The variable's name.
  43104. * @return {String} The WGSL snippet that defines a variable.
  43105. */
  43106. getVar( type, name ) {
  43107. return `var ${ name } : ${ this.getType( type ) }`;
  43108. }
  43109. /**
  43110. * Returns the variables of the given shader stage as a WGSL string.
  43111. *
  43112. * @param {String} shaderStage - The shader stage.
  43113. * @return {String} The WGSL snippet that defines the variables.
  43114. */
  43115. getVars( shaderStage ) {
  43116. const snippets = [];
  43117. const vars = this.vars[ shaderStage ];
  43118. if ( vars !== undefined ) {
  43119. for ( const variable of vars ) {
  43120. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  43121. }
  43122. }
  43123. return `\n${ snippets.join( '\n' ) }\n`;
  43124. }
  43125. /**
  43126. * Returns the varyings of the given shader stage as a WGSL string.
  43127. *
  43128. * @param {String} shaderStage - The shader stage.
  43129. * @return {String} The WGSL snippet that defines the varyings.
  43130. */
  43131. getVaryings( shaderStage ) {
  43132. const snippets = [];
  43133. if ( shaderStage === 'vertex' ) {
  43134. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  43135. }
  43136. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  43137. const varyings = this.varyings;
  43138. const vars = this.vars[ shaderStage ];
  43139. for ( let index = 0; index < varyings.length; index ++ ) {
  43140. const varying = varyings[ index ];
  43141. if ( varying.needsInterpolation ) {
  43142. let attributesSnippet = `@location( ${index} )`;
  43143. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  43144. attributesSnippet += ' @interpolate( flat )';
  43145. }
  43146. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  43147. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  43148. vars.push( varying );
  43149. }
  43150. }
  43151. }
  43152. const builtins = this.getBuiltins( shaderStage );
  43153. if ( builtins ) snippets.push( builtins );
  43154. const code = snippets.join( ',\n\t' );
  43155. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  43156. }
  43157. /**
  43158. * Returns the uniforms of the given shader stage as a WGSL string.
  43159. *
  43160. * @param {String} shaderStage - The shader stage.
  43161. * @return {String} The WGSL snippet that defines the uniforms.
  43162. */
  43163. getUniforms( shaderStage ) {
  43164. const uniforms = this.uniforms[ shaderStage ];
  43165. const bindingSnippets = [];
  43166. const bufferSnippets = [];
  43167. const structSnippets = [];
  43168. const uniformGroups = {};
  43169. for ( const uniform of uniforms ) {
  43170. const groupName = uniform.groupNode.name;
  43171. const uniformIndexes = this.bindingsIndexes[ groupName ];
  43172. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  43173. const texture = uniform.node.value;
  43174. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  43175. if ( this.isSampleCompare( texture ) ) {
  43176. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  43177. } else {
  43178. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  43179. }
  43180. }
  43181. let textureType;
  43182. let multisampled = '';
  43183. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  43184. if ( primarySamples > 1 ) {
  43185. multisampled = '_multisampled';
  43186. }
  43187. if ( texture.isCubeTexture === true ) {
  43188. textureType = 'texture_cube<f32>';
  43189. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  43190. textureType = 'texture_2d_array<f32>';
  43191. } else if ( texture.isDepthTexture === true ) {
  43192. textureType = `texture_depth${multisampled}_2d`;
  43193. } else if ( texture.isVideoTexture === true ) {
  43194. textureType = 'texture_external';
  43195. } else if ( texture.isData3DTexture === true ) {
  43196. textureType = 'texture_3d<f32>';
  43197. } else if ( uniform.node.isStorageTextureNode === true ) {
  43198. const format = getFormat( texture );
  43199. const access = this.getStorageAccess( uniform.node, shaderStage );
  43200. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  43201. } else {
  43202. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  43203. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  43204. }
  43205. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  43206. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  43207. const bufferNode = uniform.node;
  43208. const bufferType = this.getType( bufferNode.bufferType );
  43209. const bufferCount = bufferNode.bufferCount;
  43210. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  43211. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${bufferType}>` : `${bufferType}`;
  43212. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >\n`;
  43213. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  43214. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  43215. } else {
  43216. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  43217. const groupName = uniform.groupNode.name;
  43218. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  43219. index: uniformIndexes.binding ++,
  43220. id: uniformIndexes.group,
  43221. snippets: []
  43222. } );
  43223. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  43224. }
  43225. }
  43226. for ( const name in uniformGroups ) {
  43227. const group = uniformGroups[ name ];
  43228. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  43229. }
  43230. let code = bindingSnippets.join( '\n' );
  43231. code += bufferSnippets.join( '\n' );
  43232. code += structSnippets.join( '\n' );
  43233. return code;
  43234. }
  43235. /**
  43236. * Controls the code build of the shader stages.
  43237. */
  43238. buildCode() {
  43239. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  43240. this.sortBindingGroups();
  43241. for ( const shaderStage in shadersData ) {
  43242. const stageData = shadersData[ shaderStage ];
  43243. stageData.uniforms = this.getUniforms( shaderStage );
  43244. stageData.attributes = this.getAttributes( shaderStage );
  43245. stageData.varyings = this.getVaryings( shaderStage );
  43246. stageData.structs = this.getStructs( shaderStage );
  43247. stageData.vars = this.getVars( shaderStage );
  43248. stageData.codes = this.getCodes( shaderStage );
  43249. stageData.directives = this.getDirectives( shaderStage );
  43250. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  43251. //
  43252. let flow = '// code\n\n';
  43253. flow += this.flowCode[ shaderStage ];
  43254. const flowNodes = this.flowNodes[ shaderStage ];
  43255. const mainNode = flowNodes[ flowNodes.length - 1 ];
  43256. const outputNode = mainNode.outputNode;
  43257. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  43258. for ( const node of flowNodes ) {
  43259. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  43260. const slotName = node.name;
  43261. if ( slotName ) {
  43262. if ( flow.length > 0 ) flow += '\n';
  43263. flow += `\t// flow -> ${ slotName }\n\t`;
  43264. }
  43265. flow += `${ flowSlotData.code }\n\t`;
  43266. if ( node === mainNode && shaderStage !== 'compute' ) {
  43267. flow += '// result\n\n\t';
  43268. if ( shaderStage === 'vertex' ) {
  43269. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  43270. } else if ( shaderStage === 'fragment' ) {
  43271. if ( isOutputStruct ) {
  43272. stageData.returnType = outputNode.nodeType;
  43273. flow += `return ${ flowSlotData.result };`;
  43274. } else {
  43275. let structSnippet = '\t@location(0) color: vec4<f32>';
  43276. const builtins = this.getBuiltins( 'output' );
  43277. if ( builtins ) structSnippet += ',\n\t' + builtins;
  43278. stageData.returnType = 'OutputStruct';
  43279. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  43280. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  43281. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  43282. }
  43283. }
  43284. }
  43285. }
  43286. stageData.flow = flow;
  43287. }
  43288. if ( this.material !== null ) {
  43289. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  43290. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  43291. } else {
  43292. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  43293. }
  43294. }
  43295. /**
  43296. * Returns the native shader method name for a given generic name.
  43297. *
  43298. * @param {String} method - The method name to resolve.
  43299. * @param {String} [output=null] - An optional output.
  43300. * @return {String} The resolved WGSL method name.
  43301. */
  43302. getMethod( method, output = null ) {
  43303. let wgslMethod;
  43304. if ( output !== null ) {
  43305. wgslMethod = this._getWGSLMethod( method + '_' + output );
  43306. }
  43307. if ( wgslMethod === undefined ) {
  43308. wgslMethod = this._getWGSLMethod( method );
  43309. }
  43310. return wgslMethod || method;
  43311. }
  43312. /**
  43313. * Returns the WGSL type of the given node data type.
  43314. *
  43315. * @param {String} type - The node data type.
  43316. * @return {String} The WGSL type.
  43317. */
  43318. getType( type ) {
  43319. return wgslTypeLib[ type ] || type;
  43320. }
  43321. /**
  43322. * Whether the requested feature is available or not.
  43323. *
  43324. * @param {String} name - The requested feature.
  43325. * @return {Boolean} Whether the requested feature is supported or not.
  43326. */
  43327. isAvailable( name ) {
  43328. let result = supports[ name ];
  43329. if ( result === undefined ) {
  43330. if ( name === 'float32Filterable' ) {
  43331. result = this.renderer.hasFeature( 'float32-filterable' );
  43332. } else if ( name === 'clipDistance' ) {
  43333. result = this.renderer.hasFeature( 'clip-distances' );
  43334. }
  43335. supports[ name ] = result;
  43336. }
  43337. return result;
  43338. }
  43339. /**
  43340. * Returns the native shader method name for a given generic name.
  43341. *
  43342. * @private
  43343. * @param {String} method - The method name to resolve.
  43344. * @return {String} The resolved WGSL method name.
  43345. */
  43346. _getWGSLMethod( method ) {
  43347. if ( wgslPolyfill[ method ] !== undefined ) {
  43348. this._include( method );
  43349. }
  43350. return wgslMethods[ method ];
  43351. }
  43352. /**
  43353. * Includes the given method name into the current
  43354. * function node.
  43355. *
  43356. * @private
  43357. * @param {String} name - The method name to include.
  43358. * @return {CodeNode} The respective code node.
  43359. */
  43360. _include( name ) {
  43361. const codeNode = wgslPolyfill[ name ];
  43362. codeNode.build( this );
  43363. if ( this.currentFunctionNode !== null ) {
  43364. this.currentFunctionNode.includes.push( codeNode );
  43365. }
  43366. return codeNode;
  43367. }
  43368. /**
  43369. * Returns a WGSL vertex shader based on the given shader data.
  43370. *
  43371. * @private
  43372. * @param {Object} shaderData - The shader data.
  43373. * @return {String} The vertex shader.
  43374. */
  43375. _getWGSLVertexCode( shaderData ) {
  43376. return `${ this.getSignature() }
  43377. // directives
  43378. ${shaderData.directives}
  43379. // uniforms
  43380. ${shaderData.uniforms}
  43381. // varyings
  43382. ${shaderData.varyings}
  43383. var<private> varyings : VaryingsStruct;
  43384. // codes
  43385. ${shaderData.codes}
  43386. @vertex
  43387. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  43388. // vars
  43389. ${shaderData.vars}
  43390. // flow
  43391. ${shaderData.flow}
  43392. return varyings;
  43393. }
  43394. `;
  43395. }
  43396. /**
  43397. * Returns a WGSL fragment shader based on the given shader data.
  43398. *
  43399. * @private
  43400. * @param {Object} shaderData - The shader data.
  43401. * @return {String} The vertex shader.
  43402. */
  43403. _getWGSLFragmentCode( shaderData ) {
  43404. return `${ this.getSignature() }
  43405. // global
  43406. ${ diagnostics }
  43407. // uniforms
  43408. ${shaderData.uniforms}
  43409. // structs
  43410. ${shaderData.structs}
  43411. // codes
  43412. ${shaderData.codes}
  43413. @fragment
  43414. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  43415. // vars
  43416. ${shaderData.vars}
  43417. // flow
  43418. ${shaderData.flow}
  43419. }
  43420. `;
  43421. }
  43422. /**
  43423. * Returns a WGSL compute shader based on the given shader data.
  43424. *
  43425. * @private
  43426. * @param {Object} shaderData - The shader data.
  43427. * @param {String} workgroupSize - The workgroup size.
  43428. * @return {String} The vertex shader.
  43429. */
  43430. _getWGSLComputeCode( shaderData, workgroupSize ) {
  43431. return `${ this.getSignature() }
  43432. // directives
  43433. ${shaderData.directives}
  43434. // system
  43435. var<private> instanceIndex : u32;
  43436. // locals
  43437. ${shaderData.scopedArrays}
  43438. // uniforms
  43439. ${shaderData.uniforms}
  43440. // codes
  43441. ${shaderData.codes}
  43442. @compute @workgroup_size( ${workgroupSize} )
  43443. fn main( ${shaderData.attributes} ) {
  43444. // system
  43445. instanceIndex = id.x + id.y * numWorkgroups.x * u32(${workgroupSize}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  43446. // vars
  43447. ${shaderData.vars}
  43448. // flow
  43449. ${shaderData.flow}
  43450. }
  43451. `;
  43452. }
  43453. /**
  43454. * Returns a WGSL struct based on the given name and variables.
  43455. *
  43456. * @private
  43457. * @param {String} name - The struct name.
  43458. * @param {String} vars - The struct variables.
  43459. * @return {String} The WGSL snippet representing a struct.
  43460. */
  43461. _getWGSLStruct( name, vars ) {
  43462. return `
  43463. struct ${name} {
  43464. ${vars}
  43465. };`;
  43466. }
  43467. /**
  43468. * Returns a WGSL struct binding.
  43469. *
  43470. * @private
  43471. * @param {String} name - The struct name.
  43472. * @param {String} vars - The struct variables.
  43473. * @param {String} access - The access.
  43474. * @param {Number} [binding=0] - The binding index.
  43475. * @param {Number} [group=0] - The group index.
  43476. * @return {String} The WGSL snippet representing a struct binding.
  43477. */
  43478. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  43479. const structName = name + 'Struct';
  43480. const structSnippet = this._getWGSLStruct( structName, vars );
  43481. return `${structSnippet}
  43482. @binding( ${binding} ) @group( ${group} )
  43483. var<${access}> ${name} : ${structName};`;
  43484. }
  43485. }
  43486. /**
  43487. * A WebGPU backend utility module with common helpers.
  43488. *
  43489. * @private
  43490. */
  43491. class WebGPUUtils {
  43492. /**
  43493. * Constructs a new utility object.
  43494. *
  43495. * @param {WebGPUBackend} backend - The WebGPU backend.
  43496. */
  43497. constructor( backend ) {
  43498. /**
  43499. * A reference to the WebGPU backend.
  43500. *
  43501. * @type {WebGPUBackend}
  43502. */
  43503. this.backend = backend;
  43504. }
  43505. /**
  43506. * Returns the depth/stencil GPU format for the given render context.
  43507. *
  43508. * @param {RenderContext} renderContext - The render context.
  43509. * @return {String} The depth/stencil GPU texture format.
  43510. */
  43511. getCurrentDepthStencilFormat( renderContext ) {
  43512. let format;
  43513. if ( renderContext.depthTexture !== null ) {
  43514. format = this.getTextureFormatGPU( renderContext.depthTexture );
  43515. } else if ( renderContext.depth && renderContext.stencil ) {
  43516. format = GPUTextureFormat.Depth24PlusStencil8;
  43517. } else if ( renderContext.depth ) {
  43518. format = GPUTextureFormat.Depth24Plus;
  43519. }
  43520. return format;
  43521. }
  43522. /**
  43523. * Returns the GPU format for the given texture.
  43524. *
  43525. * @param {Texture} texture - The texture.
  43526. * @return {String} The GPU texture format.
  43527. */
  43528. getTextureFormatGPU( texture ) {
  43529. return this.backend.get( texture ).format;
  43530. }
  43531. /**
  43532. * Returns an object that defines the multi-sampling state of the given texture.
  43533. *
  43534. * @param {Texture} texture - The texture.
  43535. * @return {Object} The multi-sampling state.
  43536. */
  43537. getTextureSampleData( texture ) {
  43538. let samples;
  43539. if ( texture.isFramebufferTexture ) {
  43540. samples = 1;
  43541. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  43542. const renderer = this.backend.renderer;
  43543. const renderTarget = renderer.getRenderTarget();
  43544. samples = renderTarget ? renderTarget.samples : renderer.samples;
  43545. } else if ( texture.renderTarget ) {
  43546. samples = texture.renderTarget.samples;
  43547. }
  43548. samples = samples || 1;
  43549. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  43550. const primarySamples = isMSAA ? 1 : samples;
  43551. return { samples, primarySamples, isMSAA };
  43552. }
  43553. /**
  43554. * Returns the default color attachment's GPU format of the current render context.
  43555. *
  43556. * @param {RenderContext} renderContext - The render context.
  43557. * @return {String} The GPU texture format of the default color attachment.
  43558. */
  43559. getCurrentColorFormat( renderContext ) {
  43560. let format;
  43561. if ( renderContext.textures !== null ) {
  43562. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  43563. } else {
  43564. format = this.getPreferredCanvasFormat(); // default context format
  43565. }
  43566. return format;
  43567. }
  43568. /**
  43569. * Returns the output color space of the current render context.
  43570. *
  43571. * @param {RenderContext} renderContext - The render context.
  43572. * @return {String} The output color space.
  43573. */
  43574. getCurrentColorSpace( renderContext ) {
  43575. if ( renderContext.textures !== null ) {
  43576. return renderContext.textures[ 0 ].colorSpace;
  43577. }
  43578. return this.backend.renderer.outputColorSpace;
  43579. }
  43580. /**
  43581. * Returns GPU primitive topology for the given object and material.
  43582. *
  43583. * @param {Object3D} object - The 3D object.
  43584. * @param {Material} material - The material.
  43585. * @return {String} The GPU primitive topology.
  43586. */
  43587. getPrimitiveTopology( object, material ) {
  43588. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  43589. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  43590. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  43591. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  43592. }
  43593. /**
  43594. * Returns a modified sample count from the given sample count value.
  43595. *
  43596. * That is required since WebGPU does not support arbitrary sample counts.
  43597. *
  43598. * @param {Number} sampleCount - The input sample count.
  43599. * @return {Number} The (potentially updated) output sample count.
  43600. */
  43601. getSampleCount( sampleCount ) {
  43602. let count = 1;
  43603. if ( sampleCount > 1 ) {
  43604. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  43605. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  43606. if ( count === 2 ) {
  43607. count = 4;
  43608. }
  43609. }
  43610. return count;
  43611. }
  43612. /**
  43613. * Returns the sample count of the given render context.
  43614. *
  43615. * @param {RenderContext} renderContext - The render context.
  43616. * @return {Number} The sample count.
  43617. */
  43618. getSampleCountRenderContext( renderContext ) {
  43619. if ( renderContext.textures !== null ) {
  43620. return this.getSampleCount( renderContext.sampleCount );
  43621. }
  43622. return this.getSampleCount( this.backend.renderer.samples );
  43623. }
  43624. /**
  43625. * Returns the preferred canvas format.
  43626. *
  43627. * There is a separate method for this so it's possible to
  43628. * honor edge cases for specific devices.
  43629. *
  43630. * @return {String} The GPU texture format of the canvas.
  43631. */
  43632. getPreferredCanvasFormat() {
  43633. // TODO: Remove this check when Quest 34.5 is out
  43634. // https://github.com/mrdoob/three.js/pull/29221/files#r1731833949
  43635. if ( navigator.userAgent.includes( 'Quest' ) ) {
  43636. return GPUTextureFormat.BGRA8Unorm;
  43637. } else {
  43638. return navigator.gpu.getPreferredCanvasFormat();
  43639. }
  43640. }
  43641. }
  43642. const typedArraysToVertexFormatPrefix = new Map( [
  43643. [ Int8Array, [ 'sint8', 'snorm8' ]],
  43644. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  43645. [ Int16Array, [ 'sint16', 'snorm16' ]],
  43646. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  43647. [ Int32Array, [ 'sint32', 'snorm32' ]],
  43648. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  43649. [ Float32Array, [ 'float32', ]],
  43650. ] );
  43651. const typedAttributeToVertexFormatPrefix = new Map( [
  43652. [ Float16BufferAttribute, [ 'float16', ]],
  43653. ] );
  43654. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  43655. [ Int32Array, 'sint32' ],
  43656. [ Int16Array, 'sint32' ], // patch for INT16
  43657. [ Uint32Array, 'uint32' ],
  43658. [ Uint16Array, 'uint32' ], // patch for UINT16
  43659. [ Float32Array, 'float32' ]
  43660. ] );
  43661. /**
  43662. * A WebGPU backend utility module for managing shader attributes.
  43663. *
  43664. * @private
  43665. */
  43666. class WebGPUAttributeUtils {
  43667. /**
  43668. * Constructs a new utility object.
  43669. *
  43670. * @param {WebGPUBackend} backend - The WebGPU backend.
  43671. */
  43672. constructor( backend ) {
  43673. /**
  43674. * A reference to the WebGPU backend.
  43675. *
  43676. * @type {WebGPUBackend}
  43677. */
  43678. this.backend = backend;
  43679. }
  43680. /**
  43681. * Creates the GPU buffer for the given buffer attribute.
  43682. *
  43683. * @param {BufferAttribute} attribute - The buffer attribute.
  43684. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  43685. */
  43686. createAttribute( attribute, usage ) {
  43687. const bufferAttribute = this._getBufferAttribute( attribute );
  43688. const backend = this.backend;
  43689. const bufferData = backend.get( bufferAttribute );
  43690. let buffer = bufferData.buffer;
  43691. if ( buffer === undefined ) {
  43692. const device = backend.device;
  43693. let array = bufferAttribute.array;
  43694. // patch for INT16 and UINT16
  43695. if ( attribute.normalized === false ) {
  43696. if ( array.constructor === Int16Array ) {
  43697. array = new Int32Array( array );
  43698. } else if ( array.constructor === Uint16Array ) {
  43699. array = new Uint32Array( array );
  43700. if ( usage & GPUBufferUsage.INDEX ) {
  43701. for ( let i = 0; i < array.length; i ++ ) {
  43702. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  43703. }
  43704. }
  43705. }
  43706. }
  43707. bufferAttribute.array = array;
  43708. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  43709. array = new array.constructor( bufferAttribute.count * 4 );
  43710. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  43711. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  43712. }
  43713. // Update BufferAttribute
  43714. bufferAttribute.itemSize = 4;
  43715. bufferAttribute.array = array;
  43716. }
  43717. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  43718. buffer = device.createBuffer( {
  43719. label: bufferAttribute.name,
  43720. size: size,
  43721. usage: usage,
  43722. mappedAtCreation: true
  43723. } );
  43724. new array.constructor( buffer.getMappedRange() ).set( array );
  43725. buffer.unmap();
  43726. bufferData.buffer = buffer;
  43727. }
  43728. }
  43729. /**
  43730. * Updates the GPU buffer of the given buffer attribute.
  43731. *
  43732. * @param {BufferAttribute} attribute - The buffer attribute.
  43733. */
  43734. updateAttribute( attribute ) {
  43735. const bufferAttribute = this._getBufferAttribute( attribute );
  43736. const backend = this.backend;
  43737. const device = backend.device;
  43738. const buffer = backend.get( bufferAttribute ).buffer;
  43739. const array = bufferAttribute.array;
  43740. const isTypedArray = this._isTypedArray( array );
  43741. const updateRanges = bufferAttribute.updateRanges;
  43742. if ( updateRanges.length === 0 ) {
  43743. // Not using update ranges
  43744. device.queue.writeBuffer(
  43745. buffer,
  43746. 0,
  43747. array,
  43748. 0
  43749. );
  43750. } else {
  43751. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  43752. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  43753. const range = updateRanges[ i ];
  43754. const dataOffset = range.start * byteOffsetFactor;
  43755. const size = range.count * byteOffsetFactor;
  43756. device.queue.writeBuffer(
  43757. buffer,
  43758. 0,
  43759. array,
  43760. dataOffset,
  43761. size
  43762. );
  43763. }
  43764. bufferAttribute.clearUpdateRanges();
  43765. }
  43766. }
  43767. /**
  43768. * This method creates the vertex buffer layout data which are
  43769. * require when creating a render pipeline for the given render object.
  43770. *
  43771. * @param {RenderObject} renderObject - The render object.
  43772. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  43773. */
  43774. createShaderVertexBuffers( renderObject ) {
  43775. const attributes = renderObject.getAttributes();
  43776. const vertexBuffers = new Map();
  43777. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  43778. const geometryAttribute = attributes[ slot ];
  43779. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  43780. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  43781. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  43782. if ( vertexBufferLayout === undefined ) {
  43783. let arrayStride, stepMode;
  43784. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  43785. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  43786. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  43787. } else {
  43788. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  43789. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  43790. }
  43791. // patch for INT16 and UINT16
  43792. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  43793. arrayStride = 4;
  43794. }
  43795. vertexBufferLayout = {
  43796. arrayStride,
  43797. attributes: [],
  43798. stepMode
  43799. };
  43800. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  43801. }
  43802. const format = this._getVertexFormat( geometryAttribute );
  43803. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  43804. vertexBufferLayout.attributes.push( {
  43805. shaderLocation: slot,
  43806. offset,
  43807. format
  43808. } );
  43809. }
  43810. return Array.from( vertexBuffers.values() );
  43811. }
  43812. /**
  43813. * Destroys the GPU buffer of the given buffer attribute.
  43814. *
  43815. * @param {BufferAttribute} attribute - The buffer attribute.
  43816. */
  43817. destroyAttribute( attribute ) {
  43818. const backend = this.backend;
  43819. const data = backend.get( this._getBufferAttribute( attribute ) );
  43820. data.buffer.destroy();
  43821. backend.delete( attribute );
  43822. }
  43823. /**
  43824. * This method performs a readback operation by moving buffer data from
  43825. * a storage buffer attribute from the GPU to the CPU.
  43826. *
  43827. * @async
  43828. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  43829. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  43830. */
  43831. async getArrayBufferAsync( attribute ) {
  43832. const backend = this.backend;
  43833. const device = backend.device;
  43834. const data = backend.get( this._getBufferAttribute( attribute ) );
  43835. const bufferGPU = data.buffer;
  43836. const size = bufferGPU.size;
  43837. const readBufferGPU = device.createBuffer( {
  43838. label: `${ attribute.name }_readback`,
  43839. size,
  43840. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  43841. } );
  43842. const cmdEncoder = device.createCommandEncoder( {
  43843. label: `readback_encoder_${ attribute.name }`
  43844. } );
  43845. cmdEncoder.copyBufferToBuffer(
  43846. bufferGPU,
  43847. 0,
  43848. readBufferGPU,
  43849. 0,
  43850. size
  43851. );
  43852. const gpuCommands = cmdEncoder.finish();
  43853. device.queue.submit( [ gpuCommands ] );
  43854. await readBufferGPU.mapAsync( GPUMapMode.READ );
  43855. const arrayBuffer = readBufferGPU.getMappedRange();
  43856. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  43857. readBufferGPU.unmap();
  43858. return dstBuffer.buffer;
  43859. }
  43860. /**
  43861. * Returns the vertex format of the given buffer attribute.
  43862. *
  43863. * @private
  43864. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  43865. * @return {String} The vertex format (e.g. 'float32x3').
  43866. */
  43867. _getVertexFormat( geometryAttribute ) {
  43868. const { itemSize, normalized } = geometryAttribute;
  43869. const ArrayType = geometryAttribute.array.constructor;
  43870. const AttributeType = geometryAttribute.constructor;
  43871. let format;
  43872. if ( itemSize === 1 ) {
  43873. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  43874. } else {
  43875. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  43876. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  43877. if ( prefix ) {
  43878. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  43879. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  43880. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  43881. if ( paddedItemSize % 1 ) {
  43882. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  43883. }
  43884. format = `${prefix}x${paddedItemSize}`;
  43885. }
  43886. }
  43887. if ( ! format ) {
  43888. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  43889. }
  43890. return format;
  43891. }
  43892. /**
  43893. * Returns `true` if the given array is a typed array.
  43894. *
  43895. * @private
  43896. * @param {Any} array - The array.
  43897. * @return {Boolean} Whether the given array is a typed array or not.
  43898. */
  43899. _isTypedArray( array ) {
  43900. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  43901. }
  43902. /**
  43903. * Utility method for handling interleaved buffer attributes correctly.
  43904. * To process them, their `InterleavedBuffer` is returned.
  43905. *
  43906. * @private
  43907. * @param {BufferAttribute} attribute - The attribute.
  43908. * @return {BufferAttribute|InterleavedBuffer}
  43909. */
  43910. _getBufferAttribute( attribute ) {
  43911. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  43912. return attribute;
  43913. }
  43914. }
  43915. /**
  43916. * A WebGPU backend utility module for managing bindings.
  43917. *
  43918. * When reading the documentation it's helpful to keep in mind that
  43919. * all class definitions starting with 'GPU*' are modules from the
  43920. * WebGPU API. So for example `BindGroup` is a class from the engine
  43921. * whereas `GPUBindGroup` is a class from WebGPU.
  43922. *
  43923. * @private
  43924. */
  43925. class WebGPUBindingUtils {
  43926. /**
  43927. * Constructs a new utility object.
  43928. *
  43929. * @param {WebGPUBackend} backend - The WebGPU backend.
  43930. */
  43931. constructor( backend ) {
  43932. /**
  43933. * A reference to the WebGPU backend.
  43934. *
  43935. * @type {WebGPUBackend}
  43936. */
  43937. this.backend = backend;
  43938. /**
  43939. * A cache for managing bind group layouts.
  43940. *
  43941. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  43942. */
  43943. this.bindGroupLayoutCache = new WeakMap();
  43944. }
  43945. /**
  43946. * Creates a GPU bind group layout for the given bind group.
  43947. *
  43948. * @param {BindGroup} bindGroup - The bind group.
  43949. * @return {GPUBindGroupLayout} The GPU bind group layout.
  43950. */
  43951. createBindingsLayout( bindGroup ) {
  43952. const backend = this.backend;
  43953. const device = backend.device;
  43954. const entries = [];
  43955. let index = 0;
  43956. for ( const binding of bindGroup.bindings ) {
  43957. const bindingGPU = {
  43958. binding: index ++,
  43959. visibility: binding.visibility
  43960. };
  43961. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  43962. const buffer = {}; // GPUBufferBindingLayout
  43963. if ( binding.isStorageBuffer ) {
  43964. if ( binding.visibility & 4 ) {
  43965. // compute
  43966. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  43967. buffer.type = GPUBufferBindingType.Storage;
  43968. } else {
  43969. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  43970. }
  43971. } else {
  43972. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  43973. }
  43974. }
  43975. bindingGPU.buffer = buffer;
  43976. } else if ( binding.isSampler ) {
  43977. const sampler = {}; // GPUSamplerBindingLayout
  43978. if ( binding.texture.isDepthTexture ) {
  43979. if ( binding.texture.compareFunction !== null ) {
  43980. sampler.type = 'comparison';
  43981. }
  43982. }
  43983. bindingGPU.sampler = sampler;
  43984. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  43985. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  43986. } else if ( binding.isSampledTexture && binding.store ) {
  43987. const storageTexture = {}; // GPUStorageTextureBindingLayout
  43988. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  43989. const access = binding.access;
  43990. if ( access === NodeAccess.READ_WRITE ) {
  43991. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  43992. } else if ( access === NodeAccess.WRITE_ONLY ) {
  43993. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  43994. } else {
  43995. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  43996. }
  43997. bindingGPU.storageTexture = storageTexture;
  43998. } else if ( binding.isSampledTexture ) {
  43999. const texture = {}; // GPUTextureBindingLayout
  44000. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  44001. if ( primarySamples > 1 ) {
  44002. texture.multisampled = true;
  44003. if ( ! binding.texture.isDepthTexture ) {
  44004. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  44005. }
  44006. }
  44007. if ( binding.texture.isDepthTexture ) {
  44008. texture.sampleType = GPUTextureSampleType.Depth;
  44009. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  44010. const type = binding.texture.type;
  44011. if ( type === IntType ) {
  44012. texture.sampleType = GPUTextureSampleType.SInt;
  44013. } else if ( type === UnsignedIntType ) {
  44014. texture.sampleType = GPUTextureSampleType.UInt;
  44015. } else if ( type === FloatType ) {
  44016. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  44017. texture.sampleType = GPUTextureSampleType.Float;
  44018. } else {
  44019. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  44020. }
  44021. }
  44022. }
  44023. if ( binding.isSampledCubeTexture ) {
  44024. texture.viewDimension = GPUTextureViewDimension.Cube;
  44025. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  44026. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  44027. } else if ( binding.isSampledTexture3D ) {
  44028. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  44029. }
  44030. bindingGPU.texture = texture;
  44031. } else {
  44032. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  44033. }
  44034. entries.push( bindingGPU );
  44035. }
  44036. return device.createBindGroupLayout( { entries } );
  44037. }
  44038. /**
  44039. * Creates bindings from the given bind group definition.
  44040. *
  44041. * @param {BindGroup} bindGroup - The bind group.
  44042. * @param {Array<BindGroup>} bindings - Array of bind groups.
  44043. * @param {Number} cacheIndex - The cache index.
  44044. * @param {Number} version - The version.
  44045. */
  44046. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  44047. const { backend, bindGroupLayoutCache } = this;
  44048. const bindingsData = backend.get( bindGroup );
  44049. // setup (static) binding layout and (dynamic) binding group
  44050. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  44051. if ( bindLayoutGPU === undefined ) {
  44052. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  44053. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  44054. }
  44055. let bindGroupGPU;
  44056. if ( cacheIndex > 0 ) {
  44057. if ( bindingsData.groups === undefined ) {
  44058. bindingsData.groups = [];
  44059. bindingsData.versions = [];
  44060. }
  44061. if ( bindingsData.versions[ cacheIndex ] === version ) {
  44062. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  44063. }
  44064. }
  44065. if ( bindGroupGPU === undefined ) {
  44066. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  44067. if ( cacheIndex > 0 ) {
  44068. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  44069. bindingsData.versions[ cacheIndex ] = version;
  44070. }
  44071. }
  44072. bindingsData.group = bindGroupGPU;
  44073. bindingsData.layout = bindLayoutGPU;
  44074. }
  44075. /**
  44076. * Updates a buffer binding.
  44077. *
  44078. * @param {Buffer} binding - The buffer binding to update.
  44079. */
  44080. updateBinding( binding ) {
  44081. const backend = this.backend;
  44082. const device = backend.device;
  44083. const buffer = binding.buffer;
  44084. const bufferGPU = backend.get( binding ).buffer;
  44085. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  44086. }
  44087. /**
  44088. * Creates a GPU bind group for the given bind group and GPU layout.
  44089. *
  44090. * @param {BindGroup} bindGroup - The bind group.
  44091. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  44092. * @return {GPUBindGroup} The GPU bind group.
  44093. */
  44094. createBindGroup( bindGroup, layoutGPU ) {
  44095. const backend = this.backend;
  44096. const device = backend.device;
  44097. let bindingPoint = 0;
  44098. const entriesGPU = [];
  44099. for ( const binding of bindGroup.bindings ) {
  44100. if ( binding.isUniformBuffer ) {
  44101. const bindingData = backend.get( binding );
  44102. if ( bindingData.buffer === undefined ) {
  44103. const byteLength = binding.byteLength;
  44104. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  44105. const bufferGPU = device.createBuffer( {
  44106. label: 'bindingBuffer_' + binding.name,
  44107. size: byteLength,
  44108. usage: usage
  44109. } );
  44110. bindingData.buffer = bufferGPU;
  44111. }
  44112. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  44113. } else if ( binding.isStorageBuffer ) {
  44114. const bindingData = backend.get( binding );
  44115. if ( bindingData.buffer === undefined ) {
  44116. const attribute = binding.attribute;
  44117. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  44118. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  44119. bindingData.buffer = backend.get( attribute ).buffer;
  44120. }
  44121. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  44122. } else if ( binding.isSampler ) {
  44123. const textureGPU = backend.get( binding.texture );
  44124. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  44125. } else if ( binding.isSampledTexture ) {
  44126. const textureData = backend.get( binding.texture );
  44127. let resourceGPU;
  44128. if ( textureData.externalTexture !== undefined ) {
  44129. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  44130. } else {
  44131. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  44132. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  44133. resourceGPU = textureData[ propertyName ];
  44134. if ( resourceGPU === undefined ) {
  44135. const aspectGPU = GPUTextureAspect.All;
  44136. let dimensionViewGPU;
  44137. if ( binding.isSampledCubeTexture ) {
  44138. dimensionViewGPU = GPUTextureViewDimension.Cube;
  44139. } else if ( binding.isSampledTexture3D ) {
  44140. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  44141. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  44142. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  44143. } else {
  44144. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  44145. }
  44146. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  44147. }
  44148. }
  44149. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  44150. }
  44151. bindingPoint ++;
  44152. }
  44153. return device.createBindGroup( {
  44154. label: 'bindGroup_' + bindGroup.name,
  44155. layout: layoutGPU,
  44156. entries: entriesGPU
  44157. } );
  44158. }
  44159. }
  44160. /**
  44161. * A WebGPU backend utility module for managing pipelines.
  44162. *
  44163. * @private
  44164. */
  44165. class WebGPUPipelineUtils {
  44166. /**
  44167. * Constructs a new utility object.
  44168. *
  44169. * @param {WebGPUBackend} backend - The WebGPU backend.
  44170. */
  44171. constructor( backend ) {
  44172. /**
  44173. * A reference to the WebGPU backend.
  44174. *
  44175. * @type {WebGPUBackend}
  44176. */
  44177. this.backend = backend;
  44178. }
  44179. /**
  44180. * Returns the sample count derived from the given render context.
  44181. *
  44182. * @private
  44183. * @param {RenderContext} renderContext - The render context.
  44184. * @return {Number} The sample count.
  44185. */
  44186. _getSampleCount( renderContext ) {
  44187. return this.backend.utils.getSampleCountRenderContext( renderContext );
  44188. }
  44189. /**
  44190. * Creates a render pipeline for the given render object.
  44191. *
  44192. * @param {RenderObject} renderObject - The render object.
  44193. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  44194. */
  44195. createRenderPipeline( renderObject, promises ) {
  44196. const { object, material, geometry, pipeline } = renderObject;
  44197. const { vertexProgram, fragmentProgram } = pipeline;
  44198. const backend = this.backend;
  44199. const device = backend.device;
  44200. const utils = backend.utils;
  44201. const pipelineData = backend.get( pipeline );
  44202. // bind group layouts
  44203. const bindGroupLayouts = [];
  44204. for ( const bindGroup of renderObject.getBindings() ) {
  44205. const bindingsData = backend.get( bindGroup );
  44206. bindGroupLayouts.push( bindingsData.layout );
  44207. }
  44208. // vertex buffers
  44209. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  44210. // blending
  44211. let blending;
  44212. if ( material.transparent === true && material.blending !== NoBlending ) {
  44213. blending = this._getBlending( material );
  44214. }
  44215. // stencil
  44216. let stencilFront = {};
  44217. if ( material.stencilWrite === true ) {
  44218. stencilFront = {
  44219. compare: this._getStencilCompare( material ),
  44220. failOp: this._getStencilOperation( material.stencilFail ),
  44221. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  44222. passOp: this._getStencilOperation( material.stencilZPass )
  44223. };
  44224. }
  44225. const colorWriteMask = this._getColorWriteMask( material );
  44226. const targets = [];
  44227. if ( renderObject.context.textures !== null ) {
  44228. const textures = renderObject.context.textures;
  44229. for ( let i = 0; i < textures.length; i ++ ) {
  44230. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  44231. targets.push( {
  44232. format: colorFormat,
  44233. blend: blending,
  44234. writeMask: colorWriteMask
  44235. } );
  44236. }
  44237. } else {
  44238. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  44239. targets.push( {
  44240. format: colorFormat,
  44241. blend: blending,
  44242. writeMask: colorWriteMask
  44243. } );
  44244. }
  44245. const vertexModule = backend.get( vertexProgram ).module;
  44246. const fragmentModule = backend.get( fragmentProgram ).module;
  44247. const primitiveState = this._getPrimitiveState( object, geometry, material );
  44248. const depthCompare = this._getDepthCompare( material );
  44249. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  44250. const sampleCount = this._getSampleCount( renderObject.context );
  44251. const pipelineDescriptor = {
  44252. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  44253. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  44254. fragment: Object.assign( {}, fragmentModule, { targets } ),
  44255. primitive: primitiveState,
  44256. multisample: {
  44257. count: sampleCount,
  44258. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  44259. },
  44260. layout: device.createPipelineLayout( {
  44261. bindGroupLayouts
  44262. } )
  44263. };
  44264. const depthStencil = {};
  44265. const renderDepth = renderObject.context.depth;
  44266. const renderStencil = renderObject.context.stencil;
  44267. if ( renderDepth === true || renderStencil === true ) {
  44268. if ( renderDepth === true ) {
  44269. depthStencil.format = depthStencilFormat;
  44270. depthStencil.depthWriteEnabled = material.depthWrite;
  44271. depthStencil.depthCompare = depthCompare;
  44272. }
  44273. if ( renderStencil === true ) {
  44274. depthStencil.stencilFront = stencilFront;
  44275. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  44276. depthStencil.stencilReadMask = material.stencilFuncMask;
  44277. depthStencil.stencilWriteMask = material.stencilWriteMask;
  44278. }
  44279. pipelineDescriptor.depthStencil = depthStencil;
  44280. }
  44281. if ( promises === null ) {
  44282. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  44283. } else {
  44284. const p = new Promise( ( resolve /*, reject*/ ) => {
  44285. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  44286. pipelineData.pipeline = pipeline;
  44287. resolve();
  44288. } );
  44289. } );
  44290. promises.push( p );
  44291. }
  44292. }
  44293. /**
  44294. * Creates GPU render bundle encoder for the given render context.
  44295. *
  44296. * @param {RenderContext} renderContext - The render context.
  44297. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  44298. */
  44299. createBundleEncoder( renderContext ) {
  44300. const backend = this.backend;
  44301. const { utils, device } = backend;
  44302. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  44303. const colorFormat = utils.getCurrentColorFormat( renderContext );
  44304. const sampleCount = this._getSampleCount( renderContext );
  44305. const descriptor = {
  44306. label: 'renderBundleEncoder',
  44307. colorFormats: [ colorFormat ],
  44308. depthStencilFormat,
  44309. sampleCount
  44310. };
  44311. return device.createRenderBundleEncoder( descriptor );
  44312. }
  44313. /**
  44314. * Creates a compute pipeline for the given compute node.
  44315. *
  44316. * @param {ComputePipeline} pipeline - The compute pipeline.
  44317. * @param {Array<BindGroup>} bindings - The bindings.
  44318. */
  44319. createComputePipeline( pipeline, bindings ) {
  44320. const backend = this.backend;
  44321. const device = backend.device;
  44322. const computeProgram = backend.get( pipeline.computeProgram ).module;
  44323. const pipelineGPU = backend.get( pipeline );
  44324. // bind group layouts
  44325. const bindGroupLayouts = [];
  44326. for ( const bindingsGroup of bindings ) {
  44327. const bindingsData = backend.get( bindingsGroup );
  44328. bindGroupLayouts.push( bindingsData.layout );
  44329. }
  44330. pipelineGPU.pipeline = device.createComputePipeline( {
  44331. compute: computeProgram,
  44332. layout: device.createPipelineLayout( {
  44333. bindGroupLayouts
  44334. } )
  44335. } );
  44336. }
  44337. /**
  44338. * Returns the blending state as a descriptor object required
  44339. * for the pipeline creation.
  44340. *
  44341. * @private
  44342. * @param {Material} material - The material.
  44343. * @return {Object} The blending state.
  44344. */
  44345. _getBlending( material ) {
  44346. let color, alpha;
  44347. const blending = material.blending;
  44348. const blendSrc = material.blendSrc;
  44349. const blendDst = material.blendDst;
  44350. const blendEquation = material.blendEquation;
  44351. if ( blending === CustomBlending ) {
  44352. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  44353. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  44354. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  44355. color = {
  44356. srcFactor: this._getBlendFactor( blendSrc ),
  44357. dstFactor: this._getBlendFactor( blendDst ),
  44358. operation: this._getBlendOperation( blendEquation )
  44359. };
  44360. alpha = {
  44361. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  44362. dstFactor: this._getBlendFactor( blendDstAlpha ),
  44363. operation: this._getBlendOperation( blendEquationAlpha )
  44364. };
  44365. } else {
  44366. const premultipliedAlpha = material.premultipliedAlpha;
  44367. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  44368. color = {
  44369. srcFactor: srcRGB,
  44370. dstFactor: dstRGB,
  44371. operation: GPUBlendOperation.Add
  44372. };
  44373. alpha = {
  44374. srcFactor: srcAlpha,
  44375. dstFactor: dstAlpha,
  44376. operation: GPUBlendOperation.Add
  44377. };
  44378. };
  44379. if ( premultipliedAlpha ) {
  44380. switch ( blending ) {
  44381. case NormalBlending:
  44382. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  44383. break;
  44384. case AdditiveBlending:
  44385. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  44386. break;
  44387. case SubtractiveBlending:
  44388. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  44389. break;
  44390. case MultiplyBlending:
  44391. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  44392. break;
  44393. }
  44394. } else {
  44395. switch ( blending ) {
  44396. case NormalBlending:
  44397. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  44398. break;
  44399. case AdditiveBlending:
  44400. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  44401. break;
  44402. case SubtractiveBlending:
  44403. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  44404. break;
  44405. case MultiplyBlending:
  44406. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  44407. break;
  44408. }
  44409. }
  44410. }
  44411. if ( color !== undefined && alpha !== undefined ) {
  44412. return { color, alpha };
  44413. } else {
  44414. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  44415. }
  44416. }
  44417. /**
  44418. * Returns the GPU blend factor which is required for the pipeline creation.
  44419. *
  44420. * @private
  44421. * @param {Number} blend - The blend factor as a three.js constant.
  44422. * @return {String} The GPU blend factor.
  44423. */
  44424. _getBlendFactor( blend ) {
  44425. let blendFactor;
  44426. switch ( blend ) {
  44427. case ZeroFactor:
  44428. blendFactor = GPUBlendFactor.Zero;
  44429. break;
  44430. case OneFactor:
  44431. blendFactor = GPUBlendFactor.One;
  44432. break;
  44433. case SrcColorFactor:
  44434. blendFactor = GPUBlendFactor.Src;
  44435. break;
  44436. case OneMinusSrcColorFactor:
  44437. blendFactor = GPUBlendFactor.OneMinusSrc;
  44438. break;
  44439. case SrcAlphaFactor:
  44440. blendFactor = GPUBlendFactor.SrcAlpha;
  44441. break;
  44442. case OneMinusSrcAlphaFactor:
  44443. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  44444. break;
  44445. case DstColorFactor:
  44446. blendFactor = GPUBlendFactor.Dst;
  44447. break;
  44448. case OneMinusDstColorFactor:
  44449. blendFactor = GPUBlendFactor.OneMinusDstColor;
  44450. break;
  44451. case DstAlphaFactor:
  44452. blendFactor = GPUBlendFactor.DstAlpha;
  44453. break;
  44454. case OneMinusDstAlphaFactor:
  44455. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  44456. break;
  44457. case SrcAlphaSaturateFactor:
  44458. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  44459. break;
  44460. case BlendColorFactor:
  44461. blendFactor = GPUBlendFactor.Constant;
  44462. break;
  44463. case OneMinusBlendColorFactor:
  44464. blendFactor = GPUBlendFactor.OneMinusConstant;
  44465. break;
  44466. default:
  44467. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  44468. }
  44469. return blendFactor;
  44470. }
  44471. /**
  44472. * Returns the GPU stencil compare function which is required for the pipeline creation.
  44473. *
  44474. * @private
  44475. * @param {Material} material - The material.
  44476. * @return {String} The GPU stencil compare function.
  44477. */
  44478. _getStencilCompare( material ) {
  44479. let stencilCompare;
  44480. const stencilFunc = material.stencilFunc;
  44481. switch ( stencilFunc ) {
  44482. case NeverStencilFunc:
  44483. stencilCompare = GPUCompareFunction.Never;
  44484. break;
  44485. case AlwaysStencilFunc:
  44486. stencilCompare = GPUCompareFunction.Always;
  44487. break;
  44488. case LessStencilFunc:
  44489. stencilCompare = GPUCompareFunction.Less;
  44490. break;
  44491. case LessEqualStencilFunc:
  44492. stencilCompare = GPUCompareFunction.LessEqual;
  44493. break;
  44494. case EqualStencilFunc:
  44495. stencilCompare = GPUCompareFunction.Equal;
  44496. break;
  44497. case GreaterEqualStencilFunc:
  44498. stencilCompare = GPUCompareFunction.GreaterEqual;
  44499. break;
  44500. case GreaterStencilFunc:
  44501. stencilCompare = GPUCompareFunction.Greater;
  44502. break;
  44503. case NotEqualStencilFunc:
  44504. stencilCompare = GPUCompareFunction.NotEqual;
  44505. break;
  44506. default:
  44507. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  44508. }
  44509. return stencilCompare;
  44510. }
  44511. /**
  44512. * Returns the GPU stencil operation which is required for the pipeline creation.
  44513. *
  44514. * @private
  44515. * @param {Number} op - A three.js constant defining the stencil operation.
  44516. * @return {String} The GPU stencil operation.
  44517. */
  44518. _getStencilOperation( op ) {
  44519. let stencilOperation;
  44520. switch ( op ) {
  44521. case KeepStencilOp:
  44522. stencilOperation = GPUStencilOperation.Keep;
  44523. break;
  44524. case ZeroStencilOp:
  44525. stencilOperation = GPUStencilOperation.Zero;
  44526. break;
  44527. case ReplaceStencilOp:
  44528. stencilOperation = GPUStencilOperation.Replace;
  44529. break;
  44530. case InvertStencilOp:
  44531. stencilOperation = GPUStencilOperation.Invert;
  44532. break;
  44533. case IncrementStencilOp:
  44534. stencilOperation = GPUStencilOperation.IncrementClamp;
  44535. break;
  44536. case DecrementStencilOp:
  44537. stencilOperation = GPUStencilOperation.DecrementClamp;
  44538. break;
  44539. case IncrementWrapStencilOp:
  44540. stencilOperation = GPUStencilOperation.IncrementWrap;
  44541. break;
  44542. case DecrementWrapStencilOp:
  44543. stencilOperation = GPUStencilOperation.DecrementWrap;
  44544. break;
  44545. default:
  44546. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  44547. }
  44548. return stencilOperation;
  44549. }
  44550. /**
  44551. * Returns the GPU blend operation which is required for the pipeline creation.
  44552. *
  44553. * @private
  44554. * @param {Number} blendEquation - A three.js constant defining the blend equation.
  44555. * @return {String} The GPU blend operation.
  44556. */
  44557. _getBlendOperation( blendEquation ) {
  44558. let blendOperation;
  44559. switch ( blendEquation ) {
  44560. case AddEquation:
  44561. blendOperation = GPUBlendOperation.Add;
  44562. break;
  44563. case SubtractEquation:
  44564. blendOperation = GPUBlendOperation.Subtract;
  44565. break;
  44566. case ReverseSubtractEquation:
  44567. blendOperation = GPUBlendOperation.ReverseSubtract;
  44568. break;
  44569. case MinEquation:
  44570. blendOperation = GPUBlendOperation.Min;
  44571. break;
  44572. case MaxEquation:
  44573. blendOperation = GPUBlendOperation.Max;
  44574. break;
  44575. default:
  44576. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  44577. }
  44578. return blendOperation;
  44579. }
  44580. /**
  44581. * Returns the primitive state as a descriptor object required
  44582. * for the pipeline creation.
  44583. *
  44584. * @private
  44585. * @param {Object3D} object - The 3D object.
  44586. * @param {BufferGeometry} geometry - The geometry.
  44587. * @param {Material} material - The material.
  44588. * @return {Object} The primitive state.
  44589. */
  44590. _getPrimitiveState( object, geometry, material ) {
  44591. const descriptor = {};
  44592. const utils = this.backend.utils;
  44593. descriptor.topology = utils.getPrimitiveTopology( object, material );
  44594. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  44595. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  44596. }
  44597. switch ( material.side ) {
  44598. case FrontSide:
  44599. descriptor.frontFace = GPUFrontFace.CCW;
  44600. descriptor.cullMode = GPUCullMode.Back;
  44601. break;
  44602. case BackSide:
  44603. descriptor.frontFace = GPUFrontFace.CCW;
  44604. descriptor.cullMode = GPUCullMode.Front;
  44605. break;
  44606. case DoubleSide:
  44607. descriptor.frontFace = GPUFrontFace.CCW;
  44608. descriptor.cullMode = GPUCullMode.None;
  44609. break;
  44610. default:
  44611. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  44612. break;
  44613. }
  44614. return descriptor;
  44615. }
  44616. /**
  44617. * Returns the GPU color write mask which is required for the pipeline creation.
  44618. *
  44619. * @private
  44620. * @param {Material} material - The material.
  44621. * @return {String} The GPU color write mask.
  44622. */
  44623. _getColorWriteMask( material ) {
  44624. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  44625. }
  44626. /**
  44627. * Returns the GPU depth compare function which is required for the pipeline creation.
  44628. *
  44629. * @private
  44630. * @param {Material} material - The material.
  44631. * @return {String} The GPU depth compare function.
  44632. */
  44633. _getDepthCompare( material ) {
  44634. let depthCompare;
  44635. if ( material.depthTest === false ) {
  44636. depthCompare = GPUCompareFunction.Always;
  44637. } else {
  44638. const depthFunc = material.depthFunc;
  44639. switch ( depthFunc ) {
  44640. case NeverDepth:
  44641. depthCompare = GPUCompareFunction.Never;
  44642. break;
  44643. case AlwaysDepth:
  44644. depthCompare = GPUCompareFunction.Always;
  44645. break;
  44646. case LessDepth:
  44647. depthCompare = GPUCompareFunction.Less;
  44648. break;
  44649. case LessEqualDepth:
  44650. depthCompare = GPUCompareFunction.LessEqual;
  44651. break;
  44652. case EqualDepth:
  44653. depthCompare = GPUCompareFunction.Equal;
  44654. break;
  44655. case GreaterEqualDepth:
  44656. depthCompare = GPUCompareFunction.GreaterEqual;
  44657. break;
  44658. case GreaterDepth:
  44659. depthCompare = GPUCompareFunction.Greater;
  44660. break;
  44661. case NotEqualDepth:
  44662. depthCompare = GPUCompareFunction.NotEqual;
  44663. break;
  44664. default:
  44665. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  44666. }
  44667. }
  44668. return depthCompare;
  44669. }
  44670. }
  44671. /*// debugger tools
  44672. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  44673. //*/
  44674. /**
  44675. * A backend implementation targeting WebGPU.
  44676. *
  44677. * @private
  44678. * @augments Backend
  44679. */
  44680. class WebGPUBackend extends Backend {
  44681. /**
  44682. * Constructs a new WebGPU backend.
  44683. *
  44684. * @param {Object} parameters - The configuration parameter.
  44685. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  44686. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  44687. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  44688. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  44689. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  44690. * @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.
  44691. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  44692. * @param {Boolean} [parameters.trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  44693. * @param {String} [parameters.powerPreference=undefined] - The power preference.
  44694. * @param {Object} [parameters.requiredLimits=undefined] - Specifies the limits that are required by the device request. The request will fail if the adapter cannot provide these limits.
  44695. * @param {GPUDevice} [parameters.device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  44696. */
  44697. constructor( parameters = {} ) {
  44698. super( parameters );
  44699. /**
  44700. * This flag can be used for type testing.
  44701. *
  44702. * @type {Boolean}
  44703. * @readonly
  44704. * @default true
  44705. */
  44706. this.isWebGPUBackend = true;
  44707. // some parameters require default values other than "undefined"
  44708. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  44709. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  44710. /**
  44711. * Whether to track timestamps with a Timestamp Query API or not.
  44712. *
  44713. * @type {Boolean}
  44714. * @default false
  44715. */
  44716. this.trackTimestamp = ( parameters.trackTimestamp === true );
  44717. /**
  44718. * A reference to the device.
  44719. *
  44720. * @type {GPUDevice?}
  44721. * @default null
  44722. */
  44723. this.device = null;
  44724. /**
  44725. * A reference to the context.
  44726. *
  44727. * @type {GPUCanvasContext?}
  44728. * @default null
  44729. */
  44730. this.context = null;
  44731. /**
  44732. * A reference to the color attachment of the default framebuffer.
  44733. *
  44734. * @type {GPUTexture?}
  44735. * @default null
  44736. */
  44737. this.colorBuffer = null;
  44738. /**
  44739. * A reference to the default render pass descriptor.
  44740. *
  44741. * @type {Object?}
  44742. * @default null
  44743. */
  44744. this.defaultRenderPassdescriptor = null;
  44745. /**
  44746. * A reference to a backend module holding common utility functions.
  44747. *
  44748. * @type {WebGPUUtils}
  44749. */
  44750. this.utils = new WebGPUUtils( this );
  44751. /**
  44752. * A reference to a backend module holding shader attribute-related
  44753. * utility functions.
  44754. *
  44755. * @type {WebGPUAttributeUtils}
  44756. */
  44757. this.attributeUtils = new WebGPUAttributeUtils( this );
  44758. /**
  44759. * A reference to a backend module holding shader binding-related
  44760. * utility functions.
  44761. *
  44762. * @type {WebGPUBindingUtils}
  44763. */
  44764. this.bindingUtils = new WebGPUBindingUtils( this );
  44765. /**
  44766. * A reference to a backend module holding shader pipeline-related
  44767. * utility functions.
  44768. *
  44769. * @type {WebGPUPipelineUtils}
  44770. */
  44771. this.pipelineUtils = new WebGPUPipelineUtils( this );
  44772. /**
  44773. * A reference to a backend module holding shader texture-related
  44774. * utility functions.
  44775. *
  44776. * @type {WebGPUTextureUtils}
  44777. */
  44778. this.textureUtils = new WebGPUTextureUtils( this );
  44779. /**
  44780. * A map that manages the resolve buffers for occlusion queries.
  44781. *
  44782. * @type {Map<Number,GPUBuffer>}
  44783. */
  44784. this.occludedResolveCache = new Map();
  44785. }
  44786. /**
  44787. * Initializes the backend so it is ready for usage.
  44788. *
  44789. * @async
  44790. * @param {Renderer} renderer - The renderer.
  44791. * @return {Promise} A Promise that resolves when the backend has been initialized.
  44792. */
  44793. async init( renderer ) {
  44794. await super.init( renderer );
  44795. //
  44796. const parameters = this.parameters;
  44797. // create the device if it is not passed with parameters
  44798. let device;
  44799. if ( parameters.device === undefined ) {
  44800. const adapterOptions = {
  44801. powerPreference: parameters.powerPreference
  44802. };
  44803. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  44804. if ( adapter === null ) {
  44805. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  44806. }
  44807. // feature support
  44808. const features = Object.values( GPUFeatureName );
  44809. const supportedFeatures = [];
  44810. for ( const name of features ) {
  44811. if ( adapter.features.has( name ) ) {
  44812. supportedFeatures.push( name );
  44813. }
  44814. }
  44815. const deviceDescriptor = {
  44816. requiredFeatures: supportedFeatures,
  44817. requiredLimits: parameters.requiredLimits
  44818. };
  44819. device = await adapter.requestDevice( deviceDescriptor );
  44820. } else {
  44821. device = parameters.device;
  44822. }
  44823. device.lost.then( ( info ) => {
  44824. const deviceLossInfo = {
  44825. api: 'WebGPU',
  44826. message: info.message || 'Unknown reason',
  44827. reason: info.reason || null,
  44828. originalEvent: info
  44829. };
  44830. renderer.onDeviceLost( deviceLossInfo );
  44831. } );
  44832. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  44833. this.device = device;
  44834. this.context = context;
  44835. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  44836. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  44837. this.context.configure( {
  44838. device: this.device,
  44839. format: this.utils.getPreferredCanvasFormat(),
  44840. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  44841. alphaMode: alphaMode
  44842. } );
  44843. this.updateSize();
  44844. }
  44845. /**
  44846. * The coordinate system of the backend.
  44847. *
  44848. * @type {Number}
  44849. * @readonly
  44850. */
  44851. get coordinateSystem() {
  44852. return WebGPUCoordinateSystem;
  44853. }
  44854. /**
  44855. * This method performs a readback operation by moving buffer data from
  44856. * a storage buffer attribute from the GPU to the CPU.
  44857. *
  44858. * @async
  44859. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  44860. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  44861. */
  44862. async getArrayBufferAsync( attribute ) {
  44863. return await this.attributeUtils.getArrayBufferAsync( attribute );
  44864. }
  44865. /**
  44866. * Returns the backend's rendering context.
  44867. *
  44868. * @return {GPUCanvasContext} The rendering context.
  44869. */
  44870. getContext() {
  44871. return this.context;
  44872. }
  44873. /**
  44874. * Returns the default render pass descriptor.
  44875. *
  44876. * In WebGPU, the default framebuffer must be configured
  44877. * like custom framebuffers so the backend needs a render
  44878. * pass descriptor even when rendering directly to screen.
  44879. *
  44880. * @private
  44881. * @return {Object} The render pass descriptor.
  44882. */
  44883. _getDefaultRenderPassDescriptor() {
  44884. let descriptor = this.defaultRenderPassdescriptor;
  44885. if ( descriptor === null ) {
  44886. const renderer = this.renderer;
  44887. descriptor = {
  44888. colorAttachments: [ {
  44889. view: null
  44890. } ],
  44891. };
  44892. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  44893. descriptor.depthStencilAttachment = {
  44894. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  44895. };
  44896. }
  44897. const colorAttachment = descriptor.colorAttachments[ 0 ];
  44898. if ( this.renderer.samples > 0 ) {
  44899. colorAttachment.view = this.colorBuffer.createView();
  44900. } else {
  44901. colorAttachment.resolveTarget = undefined;
  44902. }
  44903. this.defaultRenderPassdescriptor = descriptor;
  44904. }
  44905. const colorAttachment = descriptor.colorAttachments[ 0 ];
  44906. if ( this.renderer.samples > 0 ) {
  44907. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  44908. } else {
  44909. colorAttachment.view = this.context.getCurrentTexture().createView();
  44910. }
  44911. return descriptor;
  44912. }
  44913. /**
  44914. * Returns the render pass descriptor for the given render context.
  44915. *
  44916. * @private
  44917. * @param {RenderContext} renderContext - The render context.
  44918. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  44919. * @return {Object} The render pass descriptor.
  44920. */
  44921. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  44922. const renderTarget = renderContext.renderTarget;
  44923. const renderTargetData = this.get( renderTarget );
  44924. let descriptors = renderTargetData.descriptors;
  44925. if ( descriptors === undefined ||
  44926. renderTargetData.width !== renderTarget.width ||
  44927. renderTargetData.height !== renderTarget.height ||
  44928. renderTargetData.dimensions !== renderTarget.dimensions ||
  44929. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  44930. renderTargetData.activeCubeFace !== renderContext.activeCubeFace ||
  44931. renderTargetData.samples !== renderTarget.samples ||
  44932. renderTargetData.loadOp !== colorAttachmentsConfig.loadOp
  44933. ) {
  44934. descriptors = {};
  44935. renderTargetData.descriptors = descriptors;
  44936. // dispose
  44937. const onDispose = () => {
  44938. renderTarget.removeEventListener( 'dispose', onDispose );
  44939. this.delete( renderTarget );
  44940. };
  44941. renderTarget.addEventListener( 'dispose', onDispose );
  44942. }
  44943. const cacheKey = renderContext.getCacheKey();
  44944. let descriptor = descriptors[ cacheKey ];
  44945. if ( descriptor === undefined ) {
  44946. const textures = renderContext.textures;
  44947. const colorAttachments = [];
  44948. let sliceIndex;
  44949. for ( let i = 0; i < textures.length; i ++ ) {
  44950. const textureData = this.get( textures[ i ] );
  44951. const viewDescriptor = {
  44952. label: `colorAttachment_${ i }`,
  44953. baseMipLevel: renderContext.activeMipmapLevel,
  44954. mipLevelCount: 1,
  44955. baseArrayLayer: renderContext.activeCubeFace,
  44956. arrayLayerCount: 1,
  44957. dimension: GPUTextureViewDimension.TwoD
  44958. };
  44959. if ( renderTarget.isRenderTarget3D ) {
  44960. sliceIndex = renderContext.activeCubeFace;
  44961. viewDescriptor.baseArrayLayer = 0;
  44962. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  44963. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  44964. } else if ( renderTarget.isRenderTargetArray ) {
  44965. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  44966. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  44967. }
  44968. const textureView = textureData.texture.createView( viewDescriptor );
  44969. let view, resolveTarget;
  44970. if ( textureData.msaaTexture !== undefined ) {
  44971. view = textureData.msaaTexture.createView();
  44972. resolveTarget = textureView;
  44973. } else {
  44974. view = textureView;
  44975. resolveTarget = undefined;
  44976. }
  44977. colorAttachments.push( {
  44978. view,
  44979. depthSlice: sliceIndex,
  44980. resolveTarget,
  44981. loadOp: GPULoadOp.Load,
  44982. storeOp: GPUStoreOp.Store,
  44983. ...colorAttachmentsConfig
  44984. } );
  44985. }
  44986. descriptor = {
  44987. colorAttachments,
  44988. };
  44989. if ( renderContext.depth ) {
  44990. const depthTextureData = this.get( renderContext.depthTexture );
  44991. const depthStencilAttachment = {
  44992. view: depthTextureData.texture.createView()
  44993. };
  44994. descriptor.depthStencilAttachment = depthStencilAttachment;
  44995. }
  44996. descriptors[ cacheKey ] = descriptor;
  44997. renderTargetData.width = renderTarget.width;
  44998. renderTargetData.height = renderTarget.height;
  44999. renderTargetData.samples = renderTarget.samples;
  45000. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  45001. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  45002. renderTargetData.dimensions = renderTarget.dimensions;
  45003. renderTargetData.depthSlice = sliceIndex;
  45004. renderTargetData.loadOp = colorAttachments[ 0 ].loadOp;
  45005. }
  45006. return descriptor;
  45007. }
  45008. /**
  45009. * This method is executed at the beginning of a render call and prepares
  45010. * the WebGPU state for upcoming render calls
  45011. *
  45012. * @param {RenderContext} renderContext - The render context.
  45013. */
  45014. beginRender( renderContext ) {
  45015. const renderContextData = this.get( renderContext );
  45016. const device = this.device;
  45017. const occlusionQueryCount = renderContext.occlusionQueryCount;
  45018. let occlusionQuerySet;
  45019. if ( occlusionQueryCount > 0 ) {
  45020. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  45021. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  45022. // Get a reference to the array of objects with queries. The renderContextData property
  45023. // can be changed by another render pass before the buffer.mapAsyc() completes.
  45024. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  45025. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  45026. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  45027. //
  45028. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  45029. renderContextData.occlusionQuerySet = occlusionQuerySet;
  45030. renderContextData.occlusionQueryIndex = 0;
  45031. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  45032. renderContextData.lastOcclusionObject = null;
  45033. }
  45034. let descriptor;
  45035. if ( renderContext.textures === null ) {
  45036. descriptor = this._getDefaultRenderPassDescriptor();
  45037. } else {
  45038. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  45039. }
  45040. this.initTimestampQuery( renderContext, descriptor );
  45041. descriptor.occlusionQuerySet = occlusionQuerySet;
  45042. const depthStencilAttachment = descriptor.depthStencilAttachment;
  45043. if ( renderContext.textures !== null ) {
  45044. const colorAttachments = descriptor.colorAttachments;
  45045. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  45046. const colorAttachment = colorAttachments[ i ];
  45047. if ( renderContext.clearColor ) {
  45048. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  45049. colorAttachment.loadOp = GPULoadOp.Clear;
  45050. colorAttachment.storeOp = GPUStoreOp.Store;
  45051. } else {
  45052. colorAttachment.loadOp = GPULoadOp.Load;
  45053. colorAttachment.storeOp = GPUStoreOp.Store;
  45054. }
  45055. }
  45056. } else {
  45057. const colorAttachment = descriptor.colorAttachments[ 0 ];
  45058. if ( renderContext.clearColor ) {
  45059. colorAttachment.clearValue = renderContext.clearColorValue;
  45060. colorAttachment.loadOp = GPULoadOp.Clear;
  45061. colorAttachment.storeOp = GPUStoreOp.Store;
  45062. } else {
  45063. colorAttachment.loadOp = GPULoadOp.Load;
  45064. colorAttachment.storeOp = GPUStoreOp.Store;
  45065. }
  45066. }
  45067. //
  45068. if ( renderContext.depth ) {
  45069. if ( renderContext.clearDepth ) {
  45070. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  45071. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  45072. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  45073. } else {
  45074. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  45075. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  45076. }
  45077. }
  45078. if ( renderContext.stencil ) {
  45079. if ( renderContext.clearStencil ) {
  45080. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  45081. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  45082. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  45083. } else {
  45084. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  45085. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  45086. }
  45087. }
  45088. //
  45089. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  45090. const currentPass = encoder.beginRenderPass( descriptor );
  45091. //
  45092. renderContextData.descriptor = descriptor;
  45093. renderContextData.encoder = encoder;
  45094. renderContextData.currentPass = currentPass;
  45095. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  45096. renderContextData.renderBundles = [];
  45097. //
  45098. if ( renderContext.viewport ) {
  45099. this.updateViewport( renderContext );
  45100. }
  45101. if ( renderContext.scissor ) {
  45102. const { x, y, width, height } = renderContext.scissorValue;
  45103. currentPass.setScissorRect( x, y, width, height );
  45104. }
  45105. }
  45106. /**
  45107. * This method is executed at the end of a render call and finalizes work
  45108. * after draw calls.
  45109. *
  45110. * @param {RenderContext} renderContext - The render context.
  45111. */
  45112. finishRender( renderContext ) {
  45113. const renderContextData = this.get( renderContext );
  45114. const occlusionQueryCount = renderContext.occlusionQueryCount;
  45115. if ( renderContextData.renderBundles.length > 0 ) {
  45116. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  45117. }
  45118. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  45119. renderContextData.currentPass.endOcclusionQuery();
  45120. }
  45121. renderContextData.currentPass.end();
  45122. if ( occlusionQueryCount > 0 ) {
  45123. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  45124. //
  45125. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  45126. if ( queryResolveBuffer === undefined ) {
  45127. queryResolveBuffer = this.device.createBuffer(
  45128. {
  45129. size: bufferSize,
  45130. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  45131. }
  45132. );
  45133. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  45134. }
  45135. //
  45136. const readBuffer = this.device.createBuffer(
  45137. {
  45138. size: bufferSize,
  45139. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  45140. }
  45141. );
  45142. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  45143. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  45144. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  45145. renderContextData.occlusionQueryBuffer = readBuffer;
  45146. //
  45147. this.resolveOccludedAsync( renderContext );
  45148. }
  45149. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  45150. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  45151. //
  45152. if ( renderContext.textures !== null ) {
  45153. const textures = renderContext.textures;
  45154. for ( let i = 0; i < textures.length; i ++ ) {
  45155. const texture = textures[ i ];
  45156. if ( texture.generateMipmaps === true ) {
  45157. this.textureUtils.generateMipmaps( texture );
  45158. }
  45159. }
  45160. }
  45161. }
  45162. /**
  45163. * Returns `true` if the given 3D object is fully occluded by other
  45164. * 3D objects in the scene.
  45165. *
  45166. * @param {RenderContext} renderContext - The render context.
  45167. * @param {Object3D} object - The 3D object to test.
  45168. * @return {Boolean} Whether the 3D object is fully occluded or not.
  45169. */
  45170. isOccluded( renderContext, object ) {
  45171. const renderContextData = this.get( renderContext );
  45172. return renderContextData.occluded && renderContextData.occluded.has( object );
  45173. }
  45174. /**
  45175. * This method processes the result of occlusion queries and writes it
  45176. * into render context data.
  45177. *
  45178. * @async
  45179. * @param {RenderContext} renderContext - The render context.
  45180. */
  45181. async resolveOccludedAsync( renderContext ) {
  45182. const renderContextData = this.get( renderContext );
  45183. // handle occlusion query results
  45184. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  45185. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  45186. const occluded = new WeakSet();
  45187. renderContextData.currentOcclusionQueryObjects = null;
  45188. renderContextData.currentOcclusionQueryBuffer = null;
  45189. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  45190. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  45191. const results = new BigUint64Array( buffer );
  45192. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  45193. if ( results[ i ] !== BigInt( 0 ) ) {
  45194. occluded.add( currentOcclusionQueryObjects[ i ] );
  45195. }
  45196. }
  45197. currentOcclusionQueryBuffer.destroy();
  45198. renderContextData.occluded = occluded;
  45199. }
  45200. }
  45201. /**
  45202. * Updates the viewport with the values from the given render context.
  45203. *
  45204. * @param {RenderContext} renderContext - The render context.
  45205. */
  45206. updateViewport( renderContext ) {
  45207. const { currentPass } = this.get( renderContext );
  45208. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  45209. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  45210. }
  45211. /**
  45212. * Performs a clear operation.
  45213. *
  45214. * @param {Boolean} color - Whether the color buffer should be cleared or not.
  45215. * @param {Boolean} depth - Whether the depth buffer should be cleared or not.
  45216. * @param {Boolean} stencil - Whether the stencil buffer should be cleared or not.
  45217. * @param {RenderContext?} [renderTargetContext=null] - The render context of the current set render target.
  45218. */
  45219. clear( color, depth, stencil, renderTargetContext = null ) {
  45220. const device = this.device;
  45221. const renderer = this.renderer;
  45222. let colorAttachments = [];
  45223. let depthStencilAttachment;
  45224. let clearValue;
  45225. let supportsDepth;
  45226. let supportsStencil;
  45227. if ( color ) {
  45228. const clearColor = this.getClearColor();
  45229. if ( this.renderer.alpha === true ) {
  45230. // premultiply alpha
  45231. const a = clearColor.a;
  45232. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  45233. } else {
  45234. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  45235. }
  45236. }
  45237. if ( renderTargetContext === null ) {
  45238. supportsDepth = renderer.depth;
  45239. supportsStencil = renderer.stencil;
  45240. const descriptor = this._getDefaultRenderPassDescriptor();
  45241. if ( color ) {
  45242. colorAttachments = descriptor.colorAttachments;
  45243. const colorAttachment = colorAttachments[ 0 ];
  45244. colorAttachment.clearValue = clearValue;
  45245. colorAttachment.loadOp = GPULoadOp.Clear;
  45246. colorAttachment.storeOp = GPUStoreOp.Store;
  45247. }
  45248. if ( supportsDepth || supportsStencil ) {
  45249. depthStencilAttachment = descriptor.depthStencilAttachment;
  45250. }
  45251. } else {
  45252. supportsDepth = renderTargetContext.depth;
  45253. supportsStencil = renderTargetContext.stencil;
  45254. if ( color ) {
  45255. const descriptor = this._getRenderPassDescriptor( renderTargetContext, { loadOp: GPULoadOp.Clear } );
  45256. colorAttachments = descriptor.colorAttachments;
  45257. }
  45258. if ( supportsDepth || supportsStencil ) {
  45259. const depthTextureData = this.get( renderTargetContext.depthTexture );
  45260. depthStencilAttachment = {
  45261. view: depthTextureData.texture.createView()
  45262. };
  45263. }
  45264. }
  45265. //
  45266. if ( supportsDepth ) {
  45267. if ( depth ) {
  45268. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  45269. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  45270. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  45271. } else {
  45272. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  45273. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  45274. }
  45275. }
  45276. //
  45277. if ( supportsStencil ) {
  45278. if ( stencil ) {
  45279. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  45280. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  45281. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  45282. } else {
  45283. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  45284. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  45285. }
  45286. }
  45287. //
  45288. const encoder = device.createCommandEncoder( {} );
  45289. const currentPass = encoder.beginRenderPass( {
  45290. colorAttachments,
  45291. depthStencilAttachment
  45292. } );
  45293. currentPass.end();
  45294. device.queue.submit( [ encoder.finish() ] );
  45295. }
  45296. // compute
  45297. /**
  45298. * This method is executed at the beginning of a compute call and
  45299. * prepares the state for upcoming compute tasks.
  45300. *
  45301. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  45302. */
  45303. beginCompute( computeGroup ) {
  45304. const groupGPU = this.get( computeGroup );
  45305. const descriptor = {};
  45306. this.initTimestampQuery( computeGroup, descriptor );
  45307. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  45308. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  45309. }
  45310. /**
  45311. * Executes a compute command for the given compute node.
  45312. *
  45313. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  45314. * @param {Node} computeNode - The compute node.
  45315. * @param {Array<BindGroup>} bindings - The bindings.
  45316. * @param {ComputePipeline} pipeline - The compute pipeline.
  45317. */
  45318. compute( computeGroup, computeNode, bindings, pipeline ) {
  45319. const { passEncoderGPU } = this.get( computeGroup );
  45320. // pipeline
  45321. const pipelineGPU = this.get( pipeline ).pipeline;
  45322. passEncoderGPU.setPipeline( pipelineGPU );
  45323. // bind groups
  45324. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  45325. const bindGroup = bindings[ i ];
  45326. const bindingsData = this.get( bindGroup );
  45327. passEncoderGPU.setBindGroup( i, bindingsData.group );
  45328. }
  45329. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  45330. const computeNodeData = this.get( computeNode );
  45331. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  45332. const { dispatchSize } = computeNodeData;
  45333. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  45334. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  45335. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  45336. } else {
  45337. dispatchSize.x = computeNode.dispatchCount;
  45338. }
  45339. passEncoderGPU.dispatchWorkgroups(
  45340. dispatchSize.x,
  45341. dispatchSize.y,
  45342. dispatchSize.z
  45343. );
  45344. }
  45345. /**
  45346. * This method is executed at the end of a compute call and
  45347. * finalizes work after compute tasks.
  45348. *
  45349. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  45350. */
  45351. finishCompute( computeGroup ) {
  45352. const groupData = this.get( computeGroup );
  45353. groupData.passEncoderGPU.end();
  45354. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  45355. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  45356. }
  45357. /**
  45358. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  45359. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  45360. *
  45361. * @async
  45362. * @return {Promise} A Promise that resolves when synchronization has been finished.
  45363. */
  45364. async waitForGPU() {
  45365. await this.device.queue.onSubmittedWorkDone();
  45366. }
  45367. // render object
  45368. /**
  45369. * Executes a draw command for the given render object.
  45370. *
  45371. * @param {RenderObject} renderObject - The render object to draw.
  45372. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  45373. */
  45374. draw( renderObject, info ) {
  45375. const { object, context, pipeline } = renderObject;
  45376. const bindings = renderObject.getBindings();
  45377. const renderContextData = this.get( context );
  45378. const pipelineGPU = this.get( pipeline ).pipeline;
  45379. const currentSets = renderContextData.currentSets;
  45380. const passEncoderGPU = renderContextData.currentPass;
  45381. const drawParams = renderObject.getDrawParameters();
  45382. if ( drawParams === null ) return;
  45383. // pipeline
  45384. if ( currentSets.pipeline !== pipelineGPU ) {
  45385. passEncoderGPU.setPipeline( pipelineGPU );
  45386. currentSets.pipeline = pipelineGPU;
  45387. }
  45388. // bind groups
  45389. const currentBindingGroups = currentSets.bindingGroups;
  45390. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  45391. const bindGroup = bindings[ i ];
  45392. const bindingsData = this.get( bindGroup );
  45393. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  45394. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  45395. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  45396. }
  45397. }
  45398. // attributes
  45399. const index = renderObject.getIndex();
  45400. const hasIndex = ( index !== null );
  45401. // index
  45402. if ( hasIndex === true ) {
  45403. if ( currentSets.index !== index ) {
  45404. const buffer = this.get( index ).buffer;
  45405. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  45406. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  45407. currentSets.index = index;
  45408. }
  45409. }
  45410. // vertex buffers
  45411. const vertexBuffers = renderObject.getVertexBuffers();
  45412. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  45413. const vertexBuffer = vertexBuffers[ i ];
  45414. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  45415. const buffer = this.get( vertexBuffer ).buffer;
  45416. passEncoderGPU.setVertexBuffer( i, buffer );
  45417. currentSets.attributes[ i ] = vertexBuffer;
  45418. }
  45419. }
  45420. // occlusion queries - handle multiple consecutive draw calls for an object
  45421. if ( renderContextData.occlusionQuerySet !== undefined ) {
  45422. const lastObject = renderContextData.lastOcclusionObject;
  45423. if ( lastObject !== object ) {
  45424. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  45425. passEncoderGPU.endOcclusionQuery();
  45426. renderContextData.occlusionQueryIndex ++;
  45427. }
  45428. if ( object.occlusionTest === true ) {
  45429. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  45430. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  45431. }
  45432. renderContextData.lastOcclusionObject = object;
  45433. }
  45434. }
  45435. // draw
  45436. if ( object.isBatchedMesh === true ) {
  45437. const starts = object._multiDrawStarts;
  45438. const counts = object._multiDrawCounts;
  45439. const drawCount = object._multiDrawCount;
  45440. const drawInstances = object._multiDrawInstances;
  45441. for ( let i = 0; i < drawCount; i ++ ) {
  45442. const count = drawInstances ? drawInstances[ i ] : 1;
  45443. const firstInstance = count > 1 ? 0 : i;
  45444. if ( hasIndex === true ) {
  45445. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  45446. } else {
  45447. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  45448. }
  45449. }
  45450. } else if ( hasIndex === true ) {
  45451. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  45452. const indirect = renderObject.getIndirect();
  45453. if ( indirect !== null ) {
  45454. const buffer = this.get( indirect ).buffer;
  45455. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  45456. } else {
  45457. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  45458. }
  45459. info.update( object, indexCount, instanceCount );
  45460. } else {
  45461. const { vertexCount, instanceCount, firstVertex } = drawParams;
  45462. const indirect = renderObject.getIndirect();
  45463. if ( indirect !== null ) {
  45464. const buffer = this.get( indirect ).buffer;
  45465. passEncoderGPU.drawIndirect( buffer, 0 );
  45466. } else {
  45467. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  45468. }
  45469. info.update( object, vertexCount, instanceCount );
  45470. }
  45471. }
  45472. // cache key
  45473. /**
  45474. * Returns `true` if the render pipeline requires an update.
  45475. *
  45476. * @param {RenderObject} renderObject - The render object.
  45477. * @return {Boolean} Whether the render pipeline requires an update or not.
  45478. */
  45479. needsRenderUpdate( renderObject ) {
  45480. const data = this.get( renderObject );
  45481. const { object, material } = renderObject;
  45482. const utils = this.utils;
  45483. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  45484. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  45485. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  45486. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  45487. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  45488. let needsUpdate = false;
  45489. if ( data.material !== material || data.materialVersion !== material.version ||
  45490. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  45491. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  45492. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  45493. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  45494. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  45495. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  45496. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  45497. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  45498. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  45499. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  45500. data.primitiveTopology !== primitiveTopology ||
  45501. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  45502. ) {
  45503. data.material = material; data.materialVersion = material.version;
  45504. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  45505. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  45506. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  45507. data.colorWrite = material.colorWrite;
  45508. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  45509. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  45510. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  45511. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  45512. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  45513. data.sampleCount = sampleCount;
  45514. data.colorSpace = colorSpace;
  45515. data.colorFormat = colorFormat;
  45516. data.depthStencilFormat = depthStencilFormat;
  45517. data.primitiveTopology = primitiveTopology;
  45518. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  45519. needsUpdate = true;
  45520. }
  45521. return needsUpdate;
  45522. }
  45523. /**
  45524. * Returns a cache key that is used to identify render pipelines.
  45525. *
  45526. * @param {RenderObject} renderObject - The render object.
  45527. * @return {String} The cache key.
  45528. */
  45529. getRenderCacheKey( renderObject ) {
  45530. const { object, material } = renderObject;
  45531. const utils = this.utils;
  45532. const renderContext = renderObject.context;
  45533. return [
  45534. material.transparent, material.blending, material.premultipliedAlpha,
  45535. material.blendSrc, material.blendDst, material.blendEquation,
  45536. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  45537. material.colorWrite,
  45538. material.depthWrite, material.depthTest, material.depthFunc,
  45539. material.stencilWrite, material.stencilFunc,
  45540. material.stencilFail, material.stencilZFail, material.stencilZPass,
  45541. material.stencilFuncMask, material.stencilWriteMask,
  45542. material.side,
  45543. utils.getSampleCountRenderContext( renderContext ),
  45544. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  45545. utils.getPrimitiveTopology( object, material ),
  45546. renderObject.getGeometryCacheKey(),
  45547. renderObject.clippingContextCacheKey
  45548. ].join();
  45549. }
  45550. // textures
  45551. /**
  45552. * Creates a GPU sampler for the given texture.
  45553. *
  45554. * @param {Texture} texture - The texture to create the sampler for.
  45555. */
  45556. createSampler( texture ) {
  45557. this.textureUtils.createSampler( texture );
  45558. }
  45559. /**
  45560. * Destroys the GPU sampler for the given texture.
  45561. *
  45562. * @param {Texture} texture - The texture to destroy the sampler for.
  45563. */
  45564. destroySampler( texture ) {
  45565. this.textureUtils.destroySampler( texture );
  45566. }
  45567. /**
  45568. * Creates a default texture for the given texture that can be used
  45569. * as a placeholder until the actual texture is ready for usage.
  45570. *
  45571. * @param {Texture} texture - The texture to create a default texture for.
  45572. */
  45573. createDefaultTexture( texture ) {
  45574. this.textureUtils.createDefaultTexture( texture );
  45575. }
  45576. /**
  45577. * Defines a texture on the GPU for the given texture object.
  45578. *
  45579. * @param {Texture} texture - The texture.
  45580. * @param {Object} [options={}] - Optional configuration parameter.
  45581. */
  45582. createTexture( texture, options ) {
  45583. this.textureUtils.createTexture( texture, options );
  45584. }
  45585. /**
  45586. * Uploads the updated texture data to the GPU.
  45587. *
  45588. * @param {Texture} texture - The texture.
  45589. * @param {Object} [options={}] - Optional configuration parameter.
  45590. */
  45591. updateTexture( texture, options ) {
  45592. this.textureUtils.updateTexture( texture, options );
  45593. }
  45594. /**
  45595. * Generates mipmaps for the given texture.
  45596. *
  45597. * @param {Texture} texture - The texture.
  45598. */
  45599. generateMipmaps( texture ) {
  45600. this.textureUtils.generateMipmaps( texture );
  45601. }
  45602. /**
  45603. * Destroys the GPU data for the given texture object.
  45604. *
  45605. * @param {Texture} texture - The texture.
  45606. */
  45607. destroyTexture( texture ) {
  45608. this.textureUtils.destroyTexture( texture );
  45609. }
  45610. /**
  45611. * Returns texture data as a typed array.
  45612. *
  45613. * @async
  45614. * @param {Texture} texture - The texture to copy.
  45615. * @param {Number} x - The x coordinate of the copy origin.
  45616. * @param {Number} y - The y coordinate of the copy origin.
  45617. * @param {Number} width - The width of the copy.
  45618. * @param {Number} height - The height of the copy.
  45619. * @param {Number} faceIndex - The face index.
  45620. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  45621. */
  45622. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  45623. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  45624. }
  45625. /**
  45626. * Inits a time stamp query for the given render context.
  45627. *
  45628. * @param {RenderContext} renderContext - The render context.
  45629. * @param {Object} descriptor - The query descriptor.
  45630. */
  45631. initTimestampQuery( renderContext, descriptor ) {
  45632. if ( ! this.trackTimestamp ) return;
  45633. const renderContextData = this.get( renderContext );
  45634. if ( ! renderContextData.timeStampQuerySet ) {
  45635. const type = renderContext.isComputeNode ? 'compute' : 'render';
  45636. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2, label: `timestamp_${type}_${renderContext.id}` } );
  45637. const timestampWrites = {
  45638. querySet: timeStampQuerySet,
  45639. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  45640. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  45641. };
  45642. Object.assign( descriptor, { timestampWrites } );
  45643. renderContextData.timeStampQuerySet = timeStampQuerySet;
  45644. }
  45645. }
  45646. /**
  45647. * Prepares the timestamp buffer.
  45648. *
  45649. * @param {RenderContext} renderContext - The render context.
  45650. * @param {GPUCommandEncoder} encoder - The command encoder.
  45651. */
  45652. prepareTimestampBuffer( renderContext, encoder ) {
  45653. if ( ! this.trackTimestamp ) return;
  45654. const renderContextData = this.get( renderContext );
  45655. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  45656. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  45657. renderContextData.currentTimestampQueryBuffers = {
  45658. resolveBuffer: this.device.createBuffer( {
  45659. label: 'timestamp resolve buffer',
  45660. size: size,
  45661. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  45662. } ),
  45663. resultBuffer: this.device.createBuffer( {
  45664. label: 'timestamp result buffer',
  45665. size: size,
  45666. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  45667. } )
  45668. };
  45669. }
  45670. const { resolveBuffer, resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  45671. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  45672. if ( resultBuffer.mapState === 'unmapped' ) {
  45673. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  45674. }
  45675. }
  45676. /**
  45677. * Resolves the time stamp for the given render context and type.
  45678. *
  45679. * @async
  45680. * @param {RenderContext} renderContext - The render context.
  45681. * @param {String} type - The render context.
  45682. * @return {Promise} A Promise that resolves when the time stamp has been computed.
  45683. */
  45684. async resolveTimestampAsync( renderContext, type = 'render' ) {
  45685. if ( ! this.trackTimestamp ) return;
  45686. const renderContextData = this.get( renderContext );
  45687. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  45688. const { resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  45689. if ( resultBuffer.mapState === 'unmapped' ) {
  45690. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  45691. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  45692. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  45693. this.renderer.info.updateTimestamp( type, duration );
  45694. resultBuffer.unmap();
  45695. } );
  45696. }
  45697. }
  45698. // node builder
  45699. /**
  45700. * Returns a node builder for the given render object.
  45701. *
  45702. * @param {RenderObject} object - The render object.
  45703. * @param {Renderer} renderer - The renderer.
  45704. * @return {WGSLNodeBuilder} The node builder.
  45705. */
  45706. createNodeBuilder( object, renderer ) {
  45707. return new WGSLNodeBuilder( object, renderer );
  45708. }
  45709. // program
  45710. /**
  45711. * Creates a shader program from the given programmable stage.
  45712. *
  45713. * @param {ProgrammableStage} program - The programmable stage.
  45714. */
  45715. createProgram( program ) {
  45716. const programGPU = this.get( program );
  45717. programGPU.module = {
  45718. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  45719. entryPoint: 'main'
  45720. };
  45721. }
  45722. /**
  45723. * Destroys the shader program of the given programmable stage.
  45724. *
  45725. * @param {ProgrammableStage} program - The programmable stage.
  45726. */
  45727. destroyProgram( program ) {
  45728. this.delete( program );
  45729. }
  45730. // pipelines
  45731. /**
  45732. * Creates a render pipeline for the given render object.
  45733. *
  45734. * @param {RenderObject} renderObject - The render object.
  45735. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  45736. */
  45737. createRenderPipeline( renderObject, promises ) {
  45738. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  45739. }
  45740. /**
  45741. * Creates a compute pipeline for the given compute node.
  45742. *
  45743. * @param {ComputePipeline} computePipeline - The compute pipeline.
  45744. * @param {Array<BindGroup>} bindings - The bindings.
  45745. */
  45746. createComputePipeline( computePipeline, bindings ) {
  45747. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  45748. }
  45749. /**
  45750. * Prepares the state for encoding render bundles.
  45751. *
  45752. * @param {RenderContext} renderContext - The render context.
  45753. */
  45754. beginBundle( renderContext ) {
  45755. const renderContextData = this.get( renderContext );
  45756. renderContextData._currentPass = renderContextData.currentPass;
  45757. renderContextData._currentSets = renderContextData.currentSets;
  45758. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  45759. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  45760. }
  45761. /**
  45762. * After processing render bundles this method finalizes related work.
  45763. *
  45764. * @param {RenderContext} renderContext - The render context.
  45765. * @param {RenderBundle} bundle - The render bundle.
  45766. */
  45767. finishBundle( renderContext, bundle ) {
  45768. const renderContextData = this.get( renderContext );
  45769. const bundleEncoder = renderContextData.currentPass;
  45770. const bundleGPU = bundleEncoder.finish();
  45771. this.get( bundle ).bundleGPU = bundleGPU;
  45772. // restore render pass state
  45773. renderContextData.currentSets = renderContextData._currentSets;
  45774. renderContextData.currentPass = renderContextData._currentPass;
  45775. }
  45776. /**
  45777. * Adds a render bundle to the render context data.
  45778. *
  45779. * @param {RenderContext} renderContext - The render context.
  45780. * @param {RenderBundle} bundle - The render bundle to add.
  45781. */
  45782. addBundle( renderContext, bundle ) {
  45783. const renderContextData = this.get( renderContext );
  45784. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  45785. }
  45786. // bindings
  45787. /**
  45788. * Creates bindings from the given bind group definition.
  45789. *
  45790. * @param {BindGroup} bindGroup - The bind group.
  45791. * @param {Array<BindGroup>} bindings - Array of bind groups.
  45792. * @param {Number} cacheIndex - The cache index.
  45793. * @param {Number} version - The version.
  45794. */
  45795. createBindings( bindGroup, bindings, cacheIndex, version ) {
  45796. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  45797. }
  45798. /**
  45799. * Updates the given bind group definition.
  45800. *
  45801. * @param {BindGroup} bindGroup - The bind group.
  45802. * @param {Array<BindGroup>} bindings - Array of bind groups.
  45803. * @param {Number} cacheIndex - The cache index.
  45804. * @param {Number} version - The version.
  45805. */
  45806. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  45807. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  45808. }
  45809. /**
  45810. * Updates a buffer binding.
  45811. *
  45812. * @param {Buffer} binding - The buffer binding to update.
  45813. */
  45814. updateBinding( binding ) {
  45815. this.bindingUtils.updateBinding( binding );
  45816. }
  45817. // attributes
  45818. /**
  45819. * Creates the buffer of an indexed shader attribute.
  45820. *
  45821. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  45822. */
  45823. createIndexAttribute( attribute ) {
  45824. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  45825. }
  45826. /**
  45827. * Creates the GPU buffer of a shader attribute.
  45828. *
  45829. * @param {BufferAttribute} attribute - The buffer attribute.
  45830. */
  45831. createAttribute( attribute ) {
  45832. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  45833. }
  45834. /**
  45835. * Creates the GPU buffer of a storage attribute.
  45836. *
  45837. * @param {BufferAttribute} attribute - The buffer attribute.
  45838. */
  45839. createStorageAttribute( attribute ) {
  45840. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  45841. }
  45842. /**
  45843. * Creates the GPU buffer of an indirect storage attribute.
  45844. *
  45845. * @param {BufferAttribute} attribute - The buffer attribute.
  45846. */
  45847. createIndirectStorageAttribute( attribute ) {
  45848. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  45849. }
  45850. /**
  45851. * Updates the GPU buffer of a shader attribute.
  45852. *
  45853. * @param {BufferAttribute} attribute - The buffer attribute to update.
  45854. */
  45855. updateAttribute( attribute ) {
  45856. this.attributeUtils.updateAttribute( attribute );
  45857. }
  45858. /**
  45859. * Destroys the GPU buffer of a shader attribute.
  45860. *
  45861. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  45862. */
  45863. destroyAttribute( attribute ) {
  45864. this.attributeUtils.destroyAttribute( attribute );
  45865. }
  45866. // canvas
  45867. /**
  45868. * Triggers an update of the default render pass descriptor.
  45869. */
  45870. updateSize() {
  45871. this.colorBuffer = this.textureUtils.getColorBuffer();
  45872. this.defaultRenderPassdescriptor = null;
  45873. }
  45874. // utils public
  45875. /**
  45876. * Returns the maximum anisotropy texture filtering value.
  45877. *
  45878. * @return {Number} The maximum anisotropy texture filtering value.
  45879. */
  45880. getMaxAnisotropy() {
  45881. return 16;
  45882. }
  45883. /**
  45884. * Checks if the given feature is supported by the backend.
  45885. *
  45886. * @param {String} name - The feature's name.
  45887. * @return {Boolean} Whether the feature is supported or not.
  45888. */
  45889. hasFeature( name ) {
  45890. return this.device.features.has( name );
  45891. }
  45892. /**
  45893. * Copies data of the given source texture to the given destination texture.
  45894. *
  45895. * @param {Texture} srcTexture - The source texture.
  45896. * @param {Texture} dstTexture - The destination texture.
  45897. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  45898. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  45899. * @param {Number} [level=0] - The mip level to copy.
  45900. */
  45901. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  45902. let dstX = 0;
  45903. let dstY = 0;
  45904. let dstLayer = 0;
  45905. let srcX = 0;
  45906. let srcY = 0;
  45907. let srcLayer = 0;
  45908. let srcWidth = srcTexture.image.width;
  45909. let srcHeight = srcTexture.image.height;
  45910. if ( srcRegion !== null ) {
  45911. srcX = srcRegion.x;
  45912. srcY = srcRegion.y;
  45913. srcLayer = srcRegion.z || 0;
  45914. srcWidth = srcRegion.width;
  45915. srcHeight = srcRegion.height;
  45916. }
  45917. if ( dstPosition !== null ) {
  45918. dstX = dstPosition.x;
  45919. dstY = dstPosition.y;
  45920. dstLayer = dstPosition.z || 0;
  45921. }
  45922. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  45923. const sourceGPU = this.get( srcTexture ).texture;
  45924. const destinationGPU = this.get( dstTexture ).texture;
  45925. encoder.copyTextureToTexture(
  45926. {
  45927. texture: sourceGPU,
  45928. mipLevel: level,
  45929. origin: { x: srcX, y: srcY, z: srcLayer }
  45930. },
  45931. {
  45932. texture: destinationGPU,
  45933. mipLevel: level,
  45934. origin: { x: dstX, y: dstY, z: dstLayer }
  45935. },
  45936. [
  45937. srcWidth,
  45938. srcHeight,
  45939. 1
  45940. ]
  45941. );
  45942. this.device.queue.submit( [ encoder.finish() ] );
  45943. }
  45944. /**
  45945. * Copies the current bound framebuffer to the given texture.
  45946. *
  45947. * @param {Texture} texture - The destination texture.
  45948. * @param {RenderContext} renderContext - The render context.
  45949. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  45950. */
  45951. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  45952. const renderContextData = this.get( renderContext );
  45953. let sourceGPU = null;
  45954. if ( renderContext.renderTarget ) {
  45955. if ( texture.isDepthTexture ) {
  45956. sourceGPU = this.get( renderContext.depthTexture ).texture;
  45957. } else {
  45958. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  45959. }
  45960. } else {
  45961. if ( texture.isDepthTexture ) {
  45962. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  45963. } else {
  45964. sourceGPU = this.context.getCurrentTexture();
  45965. }
  45966. }
  45967. const destinationGPU = this.get( texture ).texture;
  45968. if ( sourceGPU.format !== destinationGPU.format ) {
  45969. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  45970. return;
  45971. }
  45972. let encoder;
  45973. if ( renderContextData.currentPass ) {
  45974. renderContextData.currentPass.end();
  45975. encoder = renderContextData.encoder;
  45976. } else {
  45977. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  45978. }
  45979. encoder.copyTextureToTexture(
  45980. {
  45981. texture: sourceGPU,
  45982. origin: [ rectangle.x, rectangle.y, 0 ],
  45983. },
  45984. {
  45985. texture: destinationGPU
  45986. },
  45987. [
  45988. rectangle.z,
  45989. rectangle.w
  45990. ]
  45991. );
  45992. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  45993. if ( renderContextData.currentPass ) {
  45994. const { descriptor } = renderContextData;
  45995. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  45996. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  45997. }
  45998. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  45999. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  46000. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  46001. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  46002. if ( renderContext.viewport ) {
  46003. this.updateViewport( renderContext );
  46004. }
  46005. if ( renderContext.scissor ) {
  46006. const { x, y, width, height } = renderContext.scissorValue;
  46007. renderContextData.currentPass.setScissorRect( x, y, width, height );
  46008. }
  46009. } else {
  46010. this.device.queue.submit( [ encoder.finish() ] );
  46011. }
  46012. }
  46013. }
  46014. class IESSpotLight extends SpotLight {
  46015. constructor( color, intensity, distance, angle, penumbra, decay ) {
  46016. super( color, intensity, distance, angle, penumbra, decay );
  46017. this.iesMap = null;
  46018. }
  46019. copy( source, recursive ) {
  46020. super.copy( source, recursive );
  46021. this.iesMap = source.iesMap;
  46022. return this;
  46023. }
  46024. }
  46025. /**
  46026. * This version of a node library represents the standard version
  46027. * used in {@link WebGPURenderer}. It maps lights, tone mapping
  46028. * techniques and materials to node-based implementations.
  46029. *
  46030. * @private
  46031. * @augments NodeLibrary
  46032. */
  46033. class StandardNodeLibrary extends NodeLibrary {
  46034. /**
  46035. * Constructs a new standard node library.
  46036. */
  46037. constructor() {
  46038. super();
  46039. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  46040. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  46041. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  46042. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  46043. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  46044. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  46045. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  46046. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  46047. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  46048. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  46049. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  46050. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  46051. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  46052. this.addLight( PointLightNode, PointLight );
  46053. this.addLight( DirectionalLightNode, DirectionalLight );
  46054. this.addLight( RectAreaLightNode, RectAreaLight );
  46055. this.addLight( SpotLightNode, SpotLight );
  46056. this.addLight( AmbientLightNode, AmbientLight );
  46057. this.addLight( HemisphereLightNode, HemisphereLight );
  46058. this.addLight( LightProbeNode, LightProbe );
  46059. this.addLight( IESSpotLightNode, IESSpotLight );
  46060. this.addToneMapping( linearToneMapping, LinearToneMapping );
  46061. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  46062. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  46063. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  46064. this.addToneMapping( agxToneMapping, AgXToneMapping );
  46065. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  46066. }
  46067. }
  46068. /*
  46069. const debugHandler = {
  46070. get: function ( target, name ) {
  46071. // Add |update
  46072. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  46073. return target[ name ];
  46074. }
  46075. };
  46076. */
  46077. /**
  46078. * This renderer is the new alternative of `WebGLRenderer`. `WebGPURenderer` has the ability
  46079. * to target different backends. By default, the renderer tries to use a WebGPU backend if the
  46080. * browser supports WebGPU. If not, `WebGPURenderer` falls backs to a WebGL 2 backend.
  46081. *
  46082. * @augments module:Renderer~Renderer
  46083. */
  46084. class WebGPURenderer extends Renderer {
  46085. /**
  46086. * Constructs a new WebGPU renderer.
  46087. *
  46088. * @param {Object} parameters - The configuration parameter.
  46089. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  46090. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  46091. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  46092. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  46093. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  46094. * @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.
  46095. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  46096. */
  46097. constructor( parameters = {} ) {
  46098. let BackendClass;
  46099. if ( parameters.forceWebGL ) {
  46100. BackendClass = WebGLBackend;
  46101. } else {
  46102. BackendClass = WebGPUBackend;
  46103. parameters.getFallback = () => {
  46104. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  46105. return new WebGLBackend( parameters );
  46106. };
  46107. }
  46108. const backend = new BackendClass( parameters );
  46109. //super( new Proxy( backend, debugHandler ) );
  46110. super( backend, parameters );
  46111. /**
  46112. * The generic default value is overwritten with the
  46113. * standard node library for type mapping.
  46114. *
  46115. * @type {StandardNodeLibrary}
  46116. */
  46117. this.library = new StandardNodeLibrary();
  46118. /**
  46119. * This flag can be used for type testing.
  46120. *
  46121. * @type {Boolean}
  46122. * @readonly
  46123. * @default true
  46124. */
  46125. this.isWebGPURenderer = true;
  46126. }
  46127. }
  46128. /**
  46129. * A specialized group which enables applications access to the
  46130. * Render Bundle API of WebGPU. The group with all its descendant nodes
  46131. * are considered as one render bundle and processed as such by
  46132. * the renderer.
  46133. *
  46134. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  46135. * With a WebGL backend, the group can technically be rendered but without
  46136. * any performance improvements.
  46137. *
  46138. * @augments Group
  46139. */
  46140. class BundleGroup extends Group {
  46141. /**
  46142. * Constructs a new bundle group.
  46143. */
  46144. constructor() {
  46145. super();
  46146. /**
  46147. * This flag can be used for type testing.
  46148. *
  46149. * @type {Boolean}
  46150. * @readonly
  46151. * @default true
  46152. */
  46153. this.isBundleGroup = true;
  46154. /**
  46155. * This property is only relevant for detecting types
  46156. * during serialization/deserialization. It should always
  46157. * match the class name.
  46158. *
  46159. * @type {String}
  46160. * @readonly
  46161. * @default 'BundleGroup'
  46162. */
  46163. this.type = 'BundleGroup';
  46164. /**
  46165. * Whether the bundle is static or not. When set to `true`, the structure
  46166. * is assumed to be static and does not change. E.g. no new objects are
  46167. * added to the group
  46168. *
  46169. * If a change is required, an update can still be forced by setting the
  46170. * `needsUpdate` flag to `true`.
  46171. *
  46172. * @type {Boolean}
  46173. * @default true
  46174. */
  46175. this.static = true;
  46176. /**
  46177. * The bundle group's version.
  46178. *
  46179. * @type {Number}
  46180. * @readonly
  46181. * @default 0
  46182. */
  46183. this.version = 0;
  46184. }
  46185. /**
  46186. * Set this property to `true` when the bundle group has changed.
  46187. *
  46188. * @type {Boolean}
  46189. * @default false
  46190. * @param {Boolean} value
  46191. */
  46192. set needsUpdate( value ) {
  46193. if ( value === true ) this.version ++;
  46194. }
  46195. }
  46196. /**
  46197. * This module is responsible to manage the post processing setups in apps.
  46198. * You usually create a single instance of this class and use it to define
  46199. * the output of your post processing effect chain.
  46200. * ```js
  46201. * const postProcessing = new PostProcessing( renderer );
  46202. *
  46203. * const scenePass = pass( scene, camera );
  46204. *
  46205. * postProcessing.outputNode = scenePass;
  46206. * ```
  46207. */
  46208. class PostProcessing {
  46209. /**
  46210. * Constructs a new post processing management module.
  46211. *
  46212. * @param {Renderer} renderer - A reference to the renderer.
  46213. * @param {Node<vec4>} outputNode - An optional output node.
  46214. */
  46215. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  46216. /**
  46217. * A reference to the renderer.
  46218. *
  46219. * @type {Renderer}
  46220. */
  46221. this.renderer = renderer;
  46222. /**
  46223. * A node which defines the final output of the post
  46224. * processing. This is usually the last node in a chain
  46225. * of effect nodes.
  46226. *
  46227. * @type {Node<vec4>}
  46228. */
  46229. this.outputNode = outputNode;
  46230. /**
  46231. * Whether the default output tone mapping and color
  46232. * space transformation should be enabled or not.
  46233. *
  46234. * It is enabled by default by it must be disabled when
  46235. * effects must be executed after tone mapping and color
  46236. * space conversion. A typical example is FXAA which
  46237. * requires sRGB input.
  46238. *
  46239. * When set to `false`, the app must control the output
  46240. * transformation with `RenderOutputNode`.
  46241. *
  46242. * ```js
  46243. * const outputPass = renderOutput( scenePass );
  46244. * ```
  46245. *
  46246. * @type {Boolean}
  46247. */
  46248. this.outputColorTransform = true;
  46249. /**
  46250. * Must be set to `true` when the output node changes.
  46251. *
  46252. * @type {Node<vec4>}
  46253. */
  46254. this.needsUpdate = true;
  46255. const material = new NodeMaterial();
  46256. material.name = 'PostProcessing';
  46257. /**
  46258. * The full screen quad that is used to render
  46259. * the effects.
  46260. *
  46261. * @private
  46262. * @type {QuadMesh}
  46263. */
  46264. this._quadMesh = new QuadMesh( material );
  46265. }
  46266. /**
  46267. * When `PostProcessing` is used to apply post processing effects,
  46268. * the application must use this version of `render()` inside
  46269. * its animation loop (not the one from the renderer).
  46270. */
  46271. render() {
  46272. this._update();
  46273. const renderer = this.renderer;
  46274. const toneMapping = renderer.toneMapping;
  46275. const outputColorSpace = renderer.outputColorSpace;
  46276. renderer.toneMapping = NoToneMapping;
  46277. renderer.outputColorSpace = LinearSRGBColorSpace;
  46278. //
  46279. this._quadMesh.render( renderer );
  46280. //
  46281. renderer.toneMapping = toneMapping;
  46282. renderer.outputColorSpace = outputColorSpace;
  46283. }
  46284. /**
  46285. * Frees internal resources.
  46286. */
  46287. dispose() {
  46288. this._quadMesh.material.dispose();
  46289. }
  46290. /**
  46291. * Updates the state of the module.
  46292. *
  46293. * @private
  46294. */
  46295. _update() {
  46296. if ( this.needsUpdate === true ) {
  46297. const renderer = this.renderer;
  46298. const toneMapping = renderer.toneMapping;
  46299. const outputColorSpace = renderer.outputColorSpace;
  46300. this._quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  46301. this._quadMesh.material.needsUpdate = true;
  46302. this.needsUpdate = false;
  46303. }
  46304. }
  46305. /**
  46306. * When `PostProcessing` is used to apply post processing effects,
  46307. * the application must use this version of `renderAsync()` inside
  46308. * its animation loop (not the one from the renderer).
  46309. *
  46310. * @async
  46311. * @return {Promise} A Promise that resolves when the render has been finished.
  46312. */
  46313. async renderAsync() {
  46314. this._update();
  46315. const renderer = this.renderer;
  46316. const toneMapping = renderer.toneMapping;
  46317. const outputColorSpace = renderer.outputColorSpace;
  46318. renderer.toneMapping = NoToneMapping;
  46319. renderer.outputColorSpace = LinearSRGBColorSpace;
  46320. //
  46321. await this._quadMesh.renderAsync( renderer );
  46322. //
  46323. renderer.toneMapping = toneMapping;
  46324. renderer.outputColorSpace = outputColorSpace;
  46325. }
  46326. }
  46327. /**
  46328. * This special type of texture is intended for compute shaders.
  46329. * It can be used to compute the data of a texture with a compute shader.
  46330. *
  46331. * Note: This type of texture can only be used with `WebGPURenderer`
  46332. * and a WebGPU backend.
  46333. *
  46334. * @augments Texture
  46335. */
  46336. class StorageTexture extends Texture {
  46337. /**
  46338. * Constructs a new storage texture.
  46339. *
  46340. * @param {Number} [width=1] - The storage texture's width.
  46341. * @param {Number} [height=1] - The storage texture's height.
  46342. */
  46343. constructor( width = 1, height = 1 ) {
  46344. super();
  46345. /**
  46346. * The image object which just represents the texture's dimension.
  46347. *
  46348. * @type {{width: Number, height:Number}}
  46349. */
  46350. this.image = { width, height };
  46351. /**
  46352. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  46353. *
  46354. * @type {Number}
  46355. */
  46356. this.magFilter = LinearFilter;
  46357. /**
  46358. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  46359. *
  46360. * @type {Number}
  46361. */
  46362. this.minFilter = LinearFilter;
  46363. /**
  46364. * This flag can be used for type testing.
  46365. *
  46366. * @type {Boolean}
  46367. * @readonly
  46368. * @default true
  46369. */
  46370. this.isStorageTexture = true;
  46371. }
  46372. }
  46373. /**
  46374. * This special type of buffer attribute is intended for compute shaders.
  46375. * It can be used to encode draw parameters for indirect draw calls.
  46376. *
  46377. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  46378. * and a WebGPU backend.
  46379. *
  46380. * @augments StorageBufferAttribute
  46381. */
  46382. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  46383. /**
  46384. * Constructs a new storage buffer attribute.
  46385. *
  46386. * @param {Number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  46387. * The subsequent parameter is then obsolete.
  46388. * @param {Number} itemSize - The item size.
  46389. */
  46390. constructor( count, itemSize ) {
  46391. super( count, itemSize, Uint32Array );
  46392. /**
  46393. * This flag can be used for type testing.
  46394. *
  46395. * @type {Boolean}
  46396. * @readonly
  46397. * @default true
  46398. */
  46399. this.isIndirectStorageBufferAttribute = true;
  46400. }
  46401. }
  46402. /**
  46403. * A loader for loading node objects in the three.js JSON Object/Scene format.
  46404. *
  46405. * @augments Loader
  46406. */
  46407. class NodeLoader extends Loader {
  46408. /**
  46409. * Constructs a new node loader.
  46410. *
  46411. * @param {LoadingManager?} manager - A reference to a loading manager.
  46412. */
  46413. constructor( manager ) {
  46414. super( manager );
  46415. /**
  46416. * Represents a dictionary of textures.
  46417. *
  46418. * @type {Object<String,Texture>}
  46419. */
  46420. this.textures = {};
  46421. /**
  46422. * Represents a dictionary of node types.
  46423. *
  46424. * @type {Object<String,Node.constructor>}
  46425. */
  46426. this.nodes = {};
  46427. }
  46428. /**
  46429. * Loads the node definitions from the given URL.
  46430. *
  46431. * @param {String} url - The path/URL of the file to be loaded.
  46432. * @param {Function} onLoad - Will be called when load completes.
  46433. * @param {Function} onProgress - Will be called while load progresses.
  46434. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  46435. */
  46436. load( url, onLoad, onProgress, onError ) {
  46437. const loader = new FileLoader( this.manager );
  46438. loader.setPath( this.path );
  46439. loader.setRequestHeader( this.requestHeader );
  46440. loader.setWithCredentials( this.withCredentials );
  46441. loader.load( url, ( text ) => {
  46442. try {
  46443. onLoad( this.parse( JSON.parse( text ) ) );
  46444. } catch ( e ) {
  46445. if ( onError ) {
  46446. onError( e );
  46447. } else {
  46448. console.error( e );
  46449. }
  46450. this.manager.itemError( url );
  46451. }
  46452. }, onProgress, onError );
  46453. }
  46454. /**
  46455. * Parse the node dependencies for the loaded node.
  46456. *
  46457. * @param {Object} json - The JSON definition
  46458. * @return {Object<String,Node>} A dictionary with node dependencies.
  46459. */
  46460. parseNodes( json ) {
  46461. const nodes = {};
  46462. if ( json !== undefined ) {
  46463. for ( const nodeJSON of json ) {
  46464. const { uuid, type } = nodeJSON;
  46465. nodes[ uuid ] = this.createNodeFromType( type );
  46466. nodes[ uuid ].uuid = uuid;
  46467. }
  46468. const meta = { nodes, textures: this.textures };
  46469. for ( const nodeJSON of json ) {
  46470. nodeJSON.meta = meta;
  46471. const node = nodes[ nodeJSON.uuid ];
  46472. node.deserialize( nodeJSON );
  46473. delete nodeJSON.meta;
  46474. }
  46475. }
  46476. return nodes;
  46477. }
  46478. /**
  46479. * Parses the node from the given JSON.
  46480. *
  46481. * @param {Object} json - The JSON definition
  46482. * @return {Node} The parsed node.
  46483. */
  46484. parse( json ) {
  46485. const node = this.createNodeFromType( json.type );
  46486. node.uuid = json.uuid;
  46487. const nodes = this.parseNodes( json.nodes );
  46488. const meta = { nodes, textures: this.textures };
  46489. json.meta = meta;
  46490. node.deserialize( json );
  46491. delete json.meta;
  46492. return node;
  46493. }
  46494. /**
  46495. * Defines the dictionary of textures.
  46496. *
  46497. * @param {Object<String,Texture>} value - The texture library defines as `<uuid,texture>`.
  46498. * @return {NodeLoader} A reference to this loader.
  46499. */
  46500. setTextures( value ) {
  46501. this.textures = value;
  46502. return this;
  46503. }
  46504. /**
  46505. * Defines the dictionary of node types.
  46506. *
  46507. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  46508. * @return {NodeLoader} A reference to this loader.
  46509. */
  46510. setNodes( value ) {
  46511. this.nodes = value;
  46512. return this;
  46513. }
  46514. /**
  46515. * Creates a node object from the given type.
  46516. *
  46517. * @param {String} type - The node type.
  46518. * @return {Node} The created node instance.
  46519. */
  46520. createNodeFromType( type ) {
  46521. if ( this.nodes[ type ] === undefined ) {
  46522. console.error( 'THREE.NodeLoader: Node type not found:', type );
  46523. return float();
  46524. }
  46525. return nodeObject( new this.nodes[ type ]() );
  46526. }
  46527. }
  46528. /**
  46529. * A special type of material loader for loading node materials.
  46530. *
  46531. * @augments MaterialLoader
  46532. */
  46533. class NodeMaterialLoader extends MaterialLoader {
  46534. /**
  46535. * Constructs a new node material loader.
  46536. *
  46537. * @param {LoadingManager?} manager - A reference to a loading manager.
  46538. */
  46539. constructor( manager ) {
  46540. super( manager );
  46541. /**
  46542. * Represents a dictionary of node types.
  46543. *
  46544. * @type {Object<String,Node.constructor>}
  46545. */
  46546. this.nodes = {};
  46547. /**
  46548. * Represents a dictionary of node material types.
  46549. *
  46550. * @type {Object<String,NodeMaterial.constructor>}
  46551. */
  46552. this.nodeMaterials = {};
  46553. }
  46554. /**
  46555. * Parses the node material from the given JSON.
  46556. *
  46557. * @param {Object} json - The JSON definition
  46558. * @return {NodeMaterial}. The parsed material.
  46559. */
  46560. parse( json ) {
  46561. const material = super.parse( json );
  46562. const nodes = this.nodes;
  46563. const inputNodes = json.inputNodes;
  46564. for ( const property in inputNodes ) {
  46565. const uuid = inputNodes[ property ];
  46566. material[ property ] = nodes[ uuid ];
  46567. }
  46568. return material;
  46569. }
  46570. /**
  46571. * Defines the dictionary of node types.
  46572. *
  46573. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  46574. * @return {NodeLoader} A reference to this loader.
  46575. */
  46576. setNodes( value ) {
  46577. this.nodes = value;
  46578. return this;
  46579. }
  46580. /**
  46581. * Defines the dictionary of node material types.
  46582. *
  46583. * @param {Object<String,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  46584. * @return {NodeLoader} A reference to this loader.
  46585. */
  46586. setNodeMaterials( value ) {
  46587. this.nodeMaterials = value;
  46588. return this;
  46589. }
  46590. /**
  46591. * Creates a node material from the given type.
  46592. *
  46593. * @param {String} type - The node material type.
  46594. * @return {Node} The created node material instance.
  46595. */
  46596. createMaterialFromType( type ) {
  46597. const materialClass = this.nodeMaterials[ type ];
  46598. if ( materialClass !== undefined ) {
  46599. return new materialClass();
  46600. }
  46601. return super.createMaterialFromType( type );
  46602. }
  46603. }
  46604. /**
  46605. * A special type of object loader for loading 3D objects using
  46606. * node materials.
  46607. *
  46608. * @augments ObjectLoader
  46609. */
  46610. class NodeObjectLoader extends ObjectLoader {
  46611. /**
  46612. * Constructs a new node object loader.
  46613. *
  46614. * @param {LoadingManager?} manager - A reference to a loading manager.
  46615. */
  46616. constructor( manager ) {
  46617. super( manager );
  46618. /**
  46619. * Represents a dictionary of node types.
  46620. *
  46621. * @type {Object<String,Node.constructor>}
  46622. */
  46623. this.nodes = {};
  46624. /**
  46625. * Represents a dictionary of node material types.
  46626. *
  46627. * @type {Object<String,NodeMaterial.constructor>}
  46628. */
  46629. this.nodeMaterials = {};
  46630. /**
  46631. * A reference to hold the `nodes` JSON property.
  46632. *
  46633. * @private
  46634. * @type {Object?}
  46635. */
  46636. this._nodesJSON = null;
  46637. }
  46638. /**
  46639. * Defines the dictionary of node types.
  46640. *
  46641. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  46642. * @return {NodeLoader} A reference to this loader.
  46643. */
  46644. setNodes( value ) {
  46645. this.nodes = value;
  46646. return this;
  46647. }
  46648. /**
  46649. * Defines the dictionary of node material types.
  46650. *
  46651. * @param {Object<String,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  46652. * @return {NodeLoader} A reference to this loader.
  46653. */
  46654. setNodeMaterials( value ) {
  46655. this.nodeMaterials = value;
  46656. return this;
  46657. }
  46658. /**
  46659. * Parses the node objects from the given JSON.
  46660. *
  46661. * @param {Object} json - The JSON definition
  46662. * @param {Function} onLoad - The onLoad callback function.
  46663. * @return {Object3D}. The parsed 3D object.
  46664. */
  46665. parse( json, onLoad ) {
  46666. this._nodesJSON = json.nodes;
  46667. const data = super.parse( json, onLoad );
  46668. this._nodesJSON = null; // dispose
  46669. return data;
  46670. }
  46671. /**
  46672. * Parses the node objects from the given JSON and textures.
  46673. *
  46674. * @param {Object} json - The JSON definition
  46675. * @param {Object<String,Texture>} textures - The texture library.
  46676. * @return {Object<String,Node>}. The parsed nodes.
  46677. */
  46678. parseNodes( json, textures ) {
  46679. if ( json !== undefined ) {
  46680. const loader = new NodeLoader();
  46681. loader.setNodes( this.nodes );
  46682. loader.setTextures( textures );
  46683. return loader.parseNodes( json );
  46684. }
  46685. return {};
  46686. }
  46687. /**
  46688. * Parses the node objects from the given JSON and textures.
  46689. *
  46690. * @param {Object} json - The JSON definition
  46691. * @param {Object<String,Texture>} textures - The texture library.
  46692. * @return {Object<String,NodeMaterial>}. The parsed materials.
  46693. */
  46694. parseMaterials( json, textures ) {
  46695. const materials = {};
  46696. if ( json !== undefined ) {
  46697. const nodes = this.parseNodes( this._nodesJSON, textures );
  46698. const loader = new NodeMaterialLoader();
  46699. loader.setTextures( textures );
  46700. loader.setNodes( nodes );
  46701. loader.setNodeMaterials( this.nodeMaterials );
  46702. for ( let i = 0, l = json.length; i < l; i ++ ) {
  46703. const data = json[ i ];
  46704. materials[ data.uuid ] = loader.parse( data );
  46705. }
  46706. }
  46707. return materials;
  46708. }
  46709. }
  46710. /**
  46711. * In earlier three.js versions, clipping was defined globally
  46712. * on the renderer or on material level. This special version of
  46713. * `THREE.Group` allows to encode the clipping state into the scene
  46714. * graph. Meaning if you create an instance of this group, all
  46715. * descendant 3D objects will be affected by the respective clipping
  46716. * planes.
  46717. *
  46718. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  46719. *
  46720. * @augments Group
  46721. */
  46722. class ClippingGroup extends Group {
  46723. /**
  46724. * Constructs a new clipping group.
  46725. */
  46726. constructor() {
  46727. super();
  46728. /**
  46729. * This flag can be used for type testing.
  46730. *
  46731. * @type {Boolean}
  46732. * @readonly
  46733. * @default true
  46734. */
  46735. this.isClippingGroup = true;
  46736. /**
  46737. * An array with clipping planes.
  46738. *
  46739. * @type {Array<Plane>}
  46740. */
  46741. this.clippingPlanes = [];
  46742. /**
  46743. * Whether clipping should be enabled or not.
  46744. *
  46745. * @type {Boolean}
  46746. * @default true
  46747. */
  46748. this.enabled = true;
  46749. /**
  46750. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  46751. *
  46752. * @type {Boolean}
  46753. * @default false
  46754. */
  46755. this.clipIntersection = false;
  46756. /**
  46757. * Whether shadows should be clipped or not.
  46758. *
  46759. * @type {Boolean}
  46760. * @default false
  46761. */
  46762. this.clipShadows = false;
  46763. }
  46764. }
  46765. 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, Camera, 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号